/*
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 __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.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 __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all2) => {
for (var name in all2)
__defProp(target, name, { get: all2[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || 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);
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());
});
};
// node_modules/extend/index.js
var require_extend = __commonJS({
"node_modules/extend/index.js"(exports, module2) {
"use strict";
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var defineProperty = Object.defineProperty;
var gOPD = Object.getOwnPropertyDescriptor;
var isArray = function isArray2(arr) {
if (typeof Array.isArray === "function") {
return Array.isArray(arr);
}
return toStr.call(arr) === "[object Array]";
};
var isPlainObject2 = function isPlainObject3(obj) {
if (!obj || toStr.call(obj) !== "[object Object]") {
return false;
}
var hasOwnConstructor = hasOwn.call(obj, "constructor");
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf");
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
var key;
for (key in obj) {
}
return typeof key === "undefined" || hasOwn.call(obj, key);
};
var setProperty = function setProperty2(target, options) {
if (defineProperty && options.name === "__proto__") {
defineProperty(target, options.name, {
enumerable: true,
configurable: true,
value: options.newValue,
writable: true
});
} else {
target[options.name] = options.newValue;
}
};
var getProperty = function getProperty2(obj, name) {
if (name === "__proto__") {
if (!hasOwn.call(obj, name)) {
return void 0;
} else if (gOPD) {
return gOPD(obj, name).value;
}
}
return obj[name];
};
module2.exports = function extend2() {
var options, name, src, copy, copyIsArray, clone;
var target = arguments[0];
var i = 1;
var length = arguments.length;
var deep = false;
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
i = 2;
}
if (target == null || typeof target !== "object" && typeof target !== "function") {
target = {};
}
for (; i < length; ++i) {
options = arguments[i];
if (options != null) {
for (name in options) {
src = getProperty(target, name);
copy = getProperty(options, name);
if (target !== copy) {
if (deep && copy && (isPlainObject2(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject2(src) ? src : {};
}
setProperty(target, { name, newValue: extend2(deep, clone, copy) });
} else if (typeof copy !== "undefined") {
setProperty(target, { name, newValue: copy });
}
}
}
}
}
return target;
};
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/common.js
var require_common = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/common.js"(exports, module2) {
"use strict";
function isNothing(subject) {
return typeof subject === "undefined" || subject === null;
}
function isObject(subject) {
return typeof subject === "object" && subject !== null;
}
function toArray(sequence) {
if (Array.isArray(sequence))
return sequence;
else if (isNothing(sequence))
return [];
return [sequence];
}
function extend2(target, source) {
var index2, length, key, sourceKeys;
if (source) {
sourceKeys = Object.keys(source);
for (index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) {
key = sourceKeys[index2];
target[key] = source[key];
}
}
return target;
}
function repeat(string3, count) {
var result = "", cycle;
for (cycle = 0; cycle < count; cycle += 1) {
result += string3;
}
return result;
}
function isNegativeZero(number) {
return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
}
module2.exports.isNothing = isNothing;
module2.exports.isObject = isObject;
module2.exports.toArray = toArray;
module2.exports.repeat = repeat;
module2.exports.isNegativeZero = isNegativeZero;
module2.exports.extend = extend2;
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/exception.js
var require_exception = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/exception.js"(exports, module2) {
"use strict";
function YAMLException(reason, mark) {
Error.call(this);
this.name = "YAMLException";
this.reason = reason;
this.mark = mark;
this.message = (this.reason || "(unknown reason)") + (this.mark ? " " + this.mark.toString() : "");
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error().stack || "";
}
}
YAMLException.prototype = Object.create(Error.prototype);
YAMLException.prototype.constructor = YAMLException;
YAMLException.prototype.toString = function toString2(compact) {
var result = this.name + ": ";
result += this.reason || "(unknown reason)";
if (!compact && this.mark) {
result += " " + this.mark.toString();
}
return result;
};
module2.exports = YAMLException;
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/mark.js
var require_mark = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/mark.js"(exports, module2) {
"use strict";
var common = require_common();
function Mark(name, buffer, position2, line, column) {
this.name = name;
this.buffer = buffer;
this.position = position2;
this.line = line;
this.column = column;
}
Mark.prototype.getSnippet = function getSnippet(indent2, maxLength) {
var head, start, tail, end, snippet;
if (!this.buffer)
return null;
indent2 = indent2 || 4;
maxLength = maxLength || 75;
head = "";
start = this.position;
while (start > 0 && "\0\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(start - 1)) === -1) {
start -= 1;
if (this.position - start > maxLength / 2 - 1) {
head = " ... ";
start += 5;
break;
}
}
tail = "";
end = this.position;
while (end < this.buffer.length && "\0\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(end)) === -1) {
end += 1;
if (end - this.position > maxLength / 2 - 1) {
tail = " ... ";
end -= 5;
break;
}
}
snippet = this.buffer.slice(start, end);
return common.repeat(" ", indent2) + head + snippet + tail + "\n" + common.repeat(" ", indent2 + this.position - start + head.length) + "^";
};
Mark.prototype.toString = function toString2(compact) {
var snippet, where = "";
if (this.name) {
where += 'in "' + this.name + '" ';
}
where += "at line " + (this.line + 1) + ", column " + (this.column + 1);
if (!compact) {
snippet = this.getSnippet();
if (snippet) {
where += ":\n" + snippet;
}
}
return where;
};
module2.exports = Mark;
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type.js
var require_type = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type.js"(exports, module2) {
"use strict";
var YAMLException = require_exception();
var TYPE_CONSTRUCTOR_OPTIONS = [
"kind",
"resolve",
"construct",
"instanceOf",
"predicate",
"represent",
"defaultStyle",
"styleAliases"
];
var YAML_NODE_KINDS = [
"scalar",
"sequence",
"mapping"
];
function compileStyleAliases(map3) {
var result = {};
if (map3 !== null) {
Object.keys(map3).forEach(function(style) {
map3[style].forEach(function(alias) {
result[String(alias)] = style;
});
});
}
return result;
}
function Type(tag, options) {
options = options || {};
Object.keys(options).forEach(function(name) {
if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
}
});
this.tag = tag;
this.kind = options["kind"] || null;
this.resolve = options["resolve"] || function() {
return true;
};
this.construct = options["construct"] || function(data) {
return data;
};
this.instanceOf = options["instanceOf"] || null;
this.predicate = options["predicate"] || null;
this.represent = options["represent"] || null;
this.defaultStyle = options["defaultStyle"] || null;
this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
}
}
module2.exports = Type;
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema.js
var require_schema = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema.js"(exports, module2) {
"use strict";
var common = require_common();
var YAMLException = require_exception();
var Type = require_type();
function compileList(schema, name, result) {
var exclude = [];
schema.include.forEach(function(includedSchema) {
result = compileList(includedSchema, name, result);
});
schema[name].forEach(function(currentType) {
result.forEach(function(previousType, previousIndex) {
if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
exclude.push(previousIndex);
}
});
result.push(currentType);
});
return result.filter(function(type, index2) {
return exclude.indexOf(index2) === -1;
});
}
function compileMap() {
var result = {
scalar: {},
sequence: {},
mapping: {},
fallback: {}
}, index2, length;
function collectType(type) {
result[type.kind][type.tag] = result["fallback"][type.tag] = type;
}
for (index2 = 0, length = arguments.length; index2 < length; index2 += 1) {
arguments[index2].forEach(collectType);
}
return result;
}
function Schema(definition3) {
this.include = definition3.include || [];
this.implicit = definition3.implicit || [];
this.explicit = definition3.explicit || [];
this.implicit.forEach(function(type) {
if (type.loadKind && type.loadKind !== "scalar") {
throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
}
});
this.compiledImplicit = compileList(this, "implicit", []);
this.compiledExplicit = compileList(this, "explicit", []);
this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
}
Schema.DEFAULT = null;
Schema.create = function createSchema() {
var schemas, types;
switch (arguments.length) {
case 1:
schemas = Schema.DEFAULT;
types = arguments[0];
break;
case 2:
schemas = arguments[0];
types = arguments[1];
break;
default:
throw new YAMLException("Wrong number of arguments for Schema.create function");
}
schemas = common.toArray(schemas);
types = common.toArray(types);
if (!schemas.every(function(schema) {
return schema instanceof Schema;
})) {
throw new YAMLException("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");
}
if (!types.every(function(type) {
return type instanceof Type;
})) {
throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");
}
return new Schema({
include: schemas,
explicit: types
});
};
module2.exports = Schema;
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/str.js
var require_str = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/str.js"(exports, module2) {
"use strict";
var Type = require_type();
module2.exports = new Type("tag:yaml.org,2002:str", {
kind: "scalar",
construct: function(data) {
return data !== null ? data : "";
}
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/seq.js
var require_seq = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/seq.js"(exports, module2) {
"use strict";
var Type = require_type();
module2.exports = new Type("tag:yaml.org,2002:seq", {
kind: "sequence",
construct: function(data) {
return data !== null ? data : [];
}
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/map.js
var require_map = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/map.js"(exports, module2) {
"use strict";
var Type = require_type();
module2.exports = new Type("tag:yaml.org,2002:map", {
kind: "mapping",
construct: function(data) {
return data !== null ? data : {};
}
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js
var require_failsafe = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js"(exports, module2) {
"use strict";
var Schema = require_schema();
module2.exports = new Schema({
explicit: [
require_str(),
require_seq(),
require_map()
]
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/null.js
var require_null = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/null.js"(exports, module2) {
"use strict";
var Type = require_type();
function resolveYamlNull(data) {
if (data === null)
return true;
var max = data.length;
return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
}
function constructYamlNull() {
return null;
}
function isNull(object) {
return object === null;
}
module2.exports = new Type("tag:yaml.org,2002:null", {
kind: "scalar",
resolve: resolveYamlNull,
construct: constructYamlNull,
predicate: isNull,
represent: {
canonical: function() {
return "~";
},
lowercase: function() {
return "null";
},
uppercase: function() {
return "NULL";
},
camelcase: function() {
return "Null";
}
},
defaultStyle: "lowercase"
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/bool.js
var require_bool = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/bool.js"(exports, module2) {
"use strict";
var Type = require_type();
function resolveYamlBoolean(data) {
if (data === null)
return false;
var max = data.length;
return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
}
function constructYamlBoolean(data) {
return data === "true" || data === "True" || data === "TRUE";
}
function isBoolean(object) {
return Object.prototype.toString.call(object) === "[object Boolean]";
}
module2.exports = new Type("tag:yaml.org,2002:bool", {
kind: "scalar",
resolve: resolveYamlBoolean,
construct: constructYamlBoolean,
predicate: isBoolean,
represent: {
lowercase: function(object) {
return object ? "true" : "false";
},
uppercase: function(object) {
return object ? "TRUE" : "FALSE";
},
camelcase: function(object) {
return object ? "True" : "False";
}
},
defaultStyle: "lowercase"
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/int.js
var require_int = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/int.js"(exports, module2) {
"use strict";
var common = require_common();
var Type = require_type();
function isHexCode(c) {
return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
}
function isOctCode(c) {
return 48 <= c && c <= 55;
}
function isDecCode(c) {
return 48 <= c && c <= 57;
}
function resolveYamlInteger(data) {
if (data === null)
return false;
var max = data.length, index2 = 0, hasDigits = false, ch;
if (!max)
return false;
ch = data[index2];
if (ch === "-" || ch === "+") {
ch = data[++index2];
}
if (ch === "0") {
if (index2 + 1 === max)
return true;
ch = data[++index2];
if (ch === "b") {
index2++;
for (; index2 < max; index2++) {
ch = data[index2];
if (ch === "_")
continue;
if (ch !== "0" && ch !== "1")
return false;
hasDigits = true;
}
return hasDigits && ch !== "_";
}
if (ch === "x") {
index2++;
for (; index2 < max; index2++) {
ch = data[index2];
if (ch === "_")
continue;
if (!isHexCode(data.charCodeAt(index2)))
return false;
hasDigits = true;
}
return hasDigits && ch !== "_";
}
for (; index2 < max; index2++) {
ch = data[index2];
if (ch === "_")
continue;
if (!isOctCode(data.charCodeAt(index2)))
return false;
hasDigits = true;
}
return hasDigits && ch !== "_";
}
if (ch === "_")
return false;
for (; index2 < max; index2++) {
ch = data[index2];
if (ch === "_")
continue;
if (ch === ":")
break;
if (!isDecCode(data.charCodeAt(index2))) {
return false;
}
hasDigits = true;
}
if (!hasDigits || ch === "_")
return false;
if (ch !== ":")
return true;
return /^(:[0-5]?[0-9])+$/.test(data.slice(index2));
}
function constructYamlInteger(data) {
var value = data, sign = 1, ch, base, digits = [];
if (value.indexOf("_") !== -1) {
value = value.replace(/_/g, "");
}
ch = value[0];
if (ch === "-" || ch === "+") {
if (ch === "-")
sign = -1;
value = value.slice(1);
ch = value[0];
}
if (value === "0")
return 0;
if (ch === "0") {
if (value[1] === "b")
return sign * parseInt(value.slice(2), 2);
if (value[1] === "x")
return sign * parseInt(value, 16);
return sign * parseInt(value, 8);
}
if (value.indexOf(":") !== -1) {
value.split(":").forEach(function(v) {
digits.unshift(parseInt(v, 10));
});
value = 0;
base = 1;
digits.forEach(function(d) {
value += d * base;
base *= 60;
});
return sign * value;
}
return sign * parseInt(value, 10);
}
function isInteger(object) {
return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
}
module2.exports = new Type("tag:yaml.org,2002:int", {
kind: "scalar",
resolve: resolveYamlInteger,
construct: constructYamlInteger,
predicate: isInteger,
represent: {
binary: function(obj) {
return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
},
octal: function(obj) {
return obj >= 0 ? "0" + obj.toString(8) : "-0" + obj.toString(8).slice(1);
},
decimal: function(obj) {
return obj.toString(10);
},
/* eslint-disable max-len */
hexadecimal: function(obj) {
return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
}
},
defaultStyle: "decimal",
styleAliases: {
binary: [2, "bin"],
octal: [8, "oct"],
decimal: [10, "dec"],
hexadecimal: [16, "hex"]
}
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/float.js
var require_float = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/float.js"(exports, module2) {
"use strict";
var common = require_common();
var Type = require_type();
var YAML_FLOAT_PATTERN = new RegExp(
// 2.5e4, 2.5 and integers
"^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
);
function resolveYamlFloat(data) {
if (data === null)
return false;
if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
// Probably should update regexp & check speed
data[data.length - 1] === "_") {
return false;
}
return true;
}
function constructYamlFloat(data) {
var value, sign, base, digits;
value = data.replace(/_/g, "").toLowerCase();
sign = value[0] === "-" ? -1 : 1;
digits = [];
if ("+-".indexOf(value[0]) >= 0) {
value = value.slice(1);
}
if (value === ".inf") {
return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
} else if (value === ".nan") {
return NaN;
} else if (value.indexOf(":") >= 0) {
value.split(":").forEach(function(v) {
digits.unshift(parseFloat(v, 10));
});
value = 0;
base = 1;
digits.forEach(function(d) {
value += d * base;
base *= 60;
});
return sign * value;
}
return sign * parseFloat(value, 10);
}
var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) {
var res;
if (isNaN(object)) {
switch (style) {
case "lowercase":
return ".nan";
case "uppercase":
return ".NAN";
case "camelcase":
return ".NaN";
}
} else if (Number.POSITIVE_INFINITY === object) {
switch (style) {
case "lowercase":
return ".inf";
case "uppercase":
return ".INF";
case "camelcase":
return ".Inf";
}
} else if (Number.NEGATIVE_INFINITY === object) {
switch (style) {
case "lowercase":
return "-.inf";
case "uppercase":
return "-.INF";
case "camelcase":
return "-.Inf";
}
} else if (common.isNegativeZero(object)) {
return "-0.0";
}
res = object.toString(10);
return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
}
function isFloat(object) {
return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
}
module2.exports = new Type("tag:yaml.org,2002:float", {
kind: "scalar",
resolve: resolveYamlFloat,
construct: constructYamlFloat,
predicate: isFloat,
represent: representYamlFloat,
defaultStyle: "lowercase"
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/json.js
var require_json = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/json.js"(exports, module2) {
"use strict";
var Schema = require_schema();
module2.exports = new Schema({
include: [
require_failsafe()
],
implicit: [
require_null(),
require_bool(),
require_int(),
require_float()
]
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/core.js
var require_core = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/core.js"(exports, module2) {
"use strict";
var Schema = require_schema();
module2.exports = new Schema({
include: [
require_json()
]
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/timestamp.js
var require_timestamp = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/timestamp.js"(exports, module2) {
"use strict";
var Type = require_type();
var YAML_DATE_REGEXP = new RegExp(
"^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
);
var YAML_TIMESTAMP_REGEXP = new RegExp(
"^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
);
function resolveYamlTimestamp(data) {
if (data === null)
return false;
if (YAML_DATE_REGEXP.exec(data) !== null)
return true;
if (YAML_TIMESTAMP_REGEXP.exec(data) !== null)
return true;
return false;
}
function constructYamlTimestamp(data) {
var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
match = YAML_DATE_REGEXP.exec(data);
if (match === null)
match = YAML_TIMESTAMP_REGEXP.exec(data);
if (match === null)
throw new Error("Date resolve error");
year = +match[1];
month = +match[2] - 1;
day = +match[3];
if (!match[4]) {
return new Date(Date.UTC(year, month, day));
}
hour = +match[4];
minute = +match[5];
second = +match[6];
if (match[7]) {
fraction = match[7].slice(0, 3);
while (fraction.length < 3) {
fraction += "0";
}
fraction = +fraction;
}
if (match[9]) {
tz_hour = +match[10];
tz_minute = +(match[11] || 0);
delta = (tz_hour * 60 + tz_minute) * 6e4;
if (match[9] === "-")
delta = -delta;
}
date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
if (delta)
date.setTime(date.getTime() - delta);
return date;
}
function representYamlTimestamp(object) {
return object.toISOString();
}
module2.exports = new Type("tag:yaml.org,2002:timestamp", {
kind: "scalar",
resolve: resolveYamlTimestamp,
construct: constructYamlTimestamp,
instanceOf: Date,
represent: representYamlTimestamp
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/merge.js
var require_merge = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/merge.js"(exports, module2) {
"use strict";
var Type = require_type();
function resolveYamlMerge(data) {
return data === "<<" || data === null;
}
module2.exports = new Type("tag:yaml.org,2002:merge", {
kind: "scalar",
resolve: resolveYamlMerge
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/binary.js
var require_binary = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/binary.js"(exports, module2) {
"use strict";
var NodeBuffer;
try {
_require = require;
NodeBuffer = _require("buffer").Buffer;
} catch (__) {
}
var _require;
var Type = require_type();
var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
function resolveYamlBinary(data) {
if (data === null)
return false;
var code4, idx, bitlen = 0, max = data.length, map3 = BASE64_MAP;
for (idx = 0; idx < max; idx++) {
code4 = map3.indexOf(data.charAt(idx));
if (code4 > 64)
continue;
if (code4 < 0)
return false;
bitlen += 6;
}
return bitlen % 8 === 0;
}
function constructYamlBinary(data) {
var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map3 = BASE64_MAP, bits = 0, result = [];
for (idx = 0; idx < max; idx++) {
if (idx % 4 === 0 && idx) {
result.push(bits >> 16 & 255);
result.push(bits >> 8 & 255);
result.push(bits & 255);
}
bits = bits << 6 | map3.indexOf(input.charAt(idx));
}
tailbits = max % 4 * 6;
if (tailbits === 0) {
result.push(bits >> 16 & 255);
result.push(bits >> 8 & 255);
result.push(bits & 255);
} else if (tailbits === 18) {
result.push(bits >> 10 & 255);
result.push(bits >> 2 & 255);
} else if (tailbits === 12) {
result.push(bits >> 4 & 255);
}
if (NodeBuffer) {
return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
}
return result;
}
function representYamlBinary(object) {
var result = "", bits = 0, idx, tail, max = object.length, map3 = BASE64_MAP;
for (idx = 0; idx < max; idx++) {
if (idx % 3 === 0 && idx) {
result += map3[bits >> 18 & 63];
result += map3[bits >> 12 & 63];
result += map3[bits >> 6 & 63];
result += map3[bits & 63];
}
bits = (bits << 8) + object[idx];
}
tail = max % 3;
if (tail === 0) {
result += map3[bits >> 18 & 63];
result += map3[bits >> 12 & 63];
result += map3[bits >> 6 & 63];
result += map3[bits & 63];
} else if (tail === 2) {
result += map3[bits >> 10 & 63];
result += map3[bits >> 4 & 63];
result += map3[bits << 2 & 63];
result += map3[64];
} else if (tail === 1) {
result += map3[bits >> 2 & 63];
result += map3[bits << 4 & 63];
result += map3[64];
result += map3[64];
}
return result;
}
function isBinary(object) {
return NodeBuffer && NodeBuffer.isBuffer(object);
}
module2.exports = new Type("tag:yaml.org,2002:binary", {
kind: "scalar",
resolve: resolveYamlBinary,
construct: constructYamlBinary,
predicate: isBinary,
represent: representYamlBinary
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/omap.js
var require_omap = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/omap.js"(exports, module2) {
"use strict";
var Type = require_type();
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var _toString = Object.prototype.toString;
function resolveYamlOmap(data) {
if (data === null)
return true;
var objectKeys = [], index2, length, pair, pairKey, pairHasKey, object = data;
for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
pair = object[index2];
pairHasKey = false;
if (_toString.call(pair) !== "[object Object]")
return false;
for (pairKey in pair) {
if (_hasOwnProperty.call(pair, pairKey)) {
if (!pairHasKey)
pairHasKey = true;
else
return false;
}
}
if (!pairHasKey)
return false;
if (objectKeys.indexOf(pairKey) === -1)
objectKeys.push(pairKey);
else
return false;
}
return true;
}
function constructYamlOmap(data) {
return data !== null ? data : [];
}
module2.exports = new Type("tag:yaml.org,2002:omap", {
kind: "sequence",
resolve: resolveYamlOmap,
construct: constructYamlOmap
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/pairs.js
var require_pairs = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/pairs.js"(exports, module2) {
"use strict";
var Type = require_type();
var _toString = Object.prototype.toString;
function resolveYamlPairs(data) {
if (data === null)
return true;
var index2, length, pair, keys, result, object = data;
result = new Array(object.length);
for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
pair = object[index2];
if (_toString.call(pair) !== "[object Object]")
return false;
keys = Object.keys(pair);
if (keys.length !== 1)
return false;
result[index2] = [keys[0], pair[keys[0]]];
}
return true;
}
function constructYamlPairs(data) {
if (data === null)
return [];
var index2, length, pair, keys, result, object = data;
result = new Array(object.length);
for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
pair = object[index2];
keys = Object.keys(pair);
result[index2] = [keys[0], pair[keys[0]]];
}
return result;
}
module2.exports = new Type("tag:yaml.org,2002:pairs", {
kind: "sequence",
resolve: resolveYamlPairs,
construct: constructYamlPairs
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/set.js
var require_set = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/set.js"(exports, module2) {
"use strict";
var Type = require_type();
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function resolveYamlSet(data) {
if (data === null)
return true;
var key, object = data;
for (key in object) {
if (_hasOwnProperty.call(object, key)) {
if (object[key] !== null)
return false;
}
}
return true;
}
function constructYamlSet(data) {
return data !== null ? data : {};
}
module2.exports = new Type("tag:yaml.org,2002:set", {
kind: "mapping",
resolve: resolveYamlSet,
construct: constructYamlSet
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js
var require_default_safe = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js"(exports, module2) {
"use strict";
var Schema = require_schema();
module2.exports = new Schema({
include: [
require_core()
],
implicit: [
require_timestamp(),
require_merge()
],
explicit: [
require_binary(),
require_omap(),
require_pairs(),
require_set()
]
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js
var require_undefined = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js"(exports, module2) {
"use strict";
var Type = require_type();
function resolveJavascriptUndefined() {
return true;
}
function constructJavascriptUndefined() {
return void 0;
}
function representJavascriptUndefined() {
return "";
}
function isUndefined(object) {
return typeof object === "undefined";
}
module2.exports = new Type("tag:yaml.org,2002:js/undefined", {
kind: "scalar",
resolve: resolveJavascriptUndefined,
construct: constructJavascriptUndefined,
predicate: isUndefined,
represent: representJavascriptUndefined
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js
var require_regexp = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js"(exports, module2) {
"use strict";
var Type = require_type();
function resolveJavascriptRegExp(data) {
if (data === null)
return false;
if (data.length === 0)
return false;
var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = "";
if (regexp[0] === "/") {
if (tail)
modifiers = tail[1];
if (modifiers.length > 3)
return false;
if (regexp[regexp.length - modifiers.length - 1] !== "/")
return false;
}
return true;
}
function constructJavascriptRegExp(data) {
var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = "";
if (regexp[0] === "/") {
if (tail)
modifiers = tail[1];
regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
}
return new RegExp(regexp, modifiers);
}
function representJavascriptRegExp(object) {
var result = "/" + object.source + "/";
if (object.global)
result += "g";
if (object.multiline)
result += "m";
if (object.ignoreCase)
result += "i";
return result;
}
function isRegExp(object) {
return Object.prototype.toString.call(object) === "[object RegExp]";
}
module2.exports = new Type("tag:yaml.org,2002:js/regexp", {
kind: "scalar",
resolve: resolveJavascriptRegExp,
construct: constructJavascriptRegExp,
predicate: isRegExp,
represent: representJavascriptRegExp
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/js/function.js
var require_function = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/type/js/function.js"(exports, module2) {
"use strict";
var esprima;
try {
_require = require;
esprima = _require("esprima");
} catch (_) {
if (typeof window !== "undefined")
esprima = window.esprima;
}
var _require;
var Type = require_type();
function resolveJavascriptFunction(data) {
if (data === null)
return false;
try {
var source = "(" + data + ")", ast = esprima.parse(source, { range: true });
if (ast.type !== "Program" || ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement" || ast.body[0].expression.type !== "ArrowFunctionExpression" && ast.body[0].expression.type !== "FunctionExpression") {
return false;
}
return true;
} catch (err) {
return false;
}
}
function constructJavascriptFunction(data) {
var source = "(" + data + ")", ast = esprima.parse(source, { range: true }), params = [], body;
if (ast.type !== "Program" || ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement" || ast.body[0].expression.type !== "ArrowFunctionExpression" && ast.body[0].expression.type !== "FunctionExpression") {
throw new Error("Failed to resolve function");
}
ast.body[0].expression.params.forEach(function(param) {
params.push(param.name);
});
body = ast.body[0].expression.body.range;
if (ast.body[0].expression.body.type === "BlockStatement") {
return new Function(params, source.slice(body[0] + 1, body[1] - 1));
}
return new Function(params, "return " + source.slice(body[0], body[1]));
}
function representJavascriptFunction(object) {
return object.toString();
}
function isFunction(object) {
return Object.prototype.toString.call(object) === "[object Function]";
}
module2.exports = new Type("tag:yaml.org,2002:js/function", {
kind: "scalar",
resolve: resolveJavascriptFunction,
construct: constructJavascriptFunction,
predicate: isFunction,
represent: representJavascriptFunction
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/default_full.js
var require_default_full = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/schema/default_full.js"(exports, module2) {
"use strict";
var Schema = require_schema();
module2.exports = Schema.DEFAULT = new Schema({
include: [
require_default_safe()
],
explicit: [
require_undefined(),
require_regexp(),
require_function()
]
});
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/loader.js
var require_loader = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/loader.js"(exports, module2) {
"use strict";
var common = require_common();
var YAMLException = require_exception();
var Mark = require_mark();
var DEFAULT_SAFE_SCHEMA = require_default_safe();
var DEFAULT_FULL_SCHEMA = require_default_full();
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CONTEXT_FLOW_IN = 1;
var CONTEXT_FLOW_OUT = 2;
var CONTEXT_BLOCK_IN = 3;
var CONTEXT_BLOCK_OUT = 4;
var CHOMPING_CLIP = 1;
var CHOMPING_STRIP = 2;
var CHOMPING_KEEP = 3;
var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
function _class(obj) {
return Object.prototype.toString.call(obj);
}
function is_EOL(c) {
return c === 10 || c === 13;
}
function is_WHITE_SPACE(c) {
return c === 9 || c === 32;
}
function is_WS_OR_EOL(c) {
return c === 9 || c === 32 || c === 10 || c === 13;
}
function is_FLOW_INDICATOR(c) {
return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
}
function fromHexCode(c) {
var lc;
if (48 <= c && c <= 57) {
return c - 48;
}
lc = c | 32;
if (97 <= lc && lc <= 102) {
return lc - 97 + 10;
}
return -1;
}
function escapedHexLen(c) {
if (c === 120) {
return 2;
}
if (c === 117) {
return 4;
}
if (c === 85) {
return 8;
}
return 0;
}
function fromDecimalCode(c) {
if (48 <= c && c <= 57) {
return c - 48;
}
return -1;
}
function simpleEscapeSequence(c) {
return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? " " : c === 9 ? " " : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
}
function charFromCodepoint(c) {
if (c <= 65535) {
return String.fromCharCode(c);
}
return String.fromCharCode(
(c - 65536 >> 10) + 55296,
(c - 65536 & 1023) + 56320
);
}
function setProperty(object, key, value) {
if (key === "__proto__") {
Object.defineProperty(object, key, {
configurable: true,
enumerable: true,
writable: true,
value
});
} else {
object[key] = value;
}
}
var simpleEscapeCheck = new Array(256);
var simpleEscapeMap = new Array(256);
for (i = 0; i < 256; i++) {
simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
simpleEscapeMap[i] = simpleEscapeSequence(i);
}
var i;
function State(input, options) {
this.input = input;
this.filename = options["filename"] || null;
this.schema = options["schema"] || DEFAULT_FULL_SCHEMA;
this.onWarning = options["onWarning"] || null;
this.legacy = options["legacy"] || false;
this.json = options["json"] || false;
this.listener = options["listener"] || null;
this.implicitTypes = this.schema.compiledImplicit;
this.typeMap = this.schema.compiledTypeMap;
this.length = input.length;
this.position = 0;
this.line = 0;
this.lineStart = 0;
this.lineIndent = 0;
this.documents = [];
}
function generateError(state, message) {
return new YAMLException(
message,
new Mark(state.filename, state.input, state.position, state.line, state.position - state.lineStart)
);
}
function throwError(state, message) {
throw generateError(state, message);
}
function throwWarning(state, message) {
if (state.onWarning) {
state.onWarning.call(null, generateError(state, message));
}
}
var directiveHandlers = {
YAML: function handleYamlDirective(state, name, args) {
var match, major, minor;
if (state.version !== null) {
throwError(state, "duplication of %YAML directive");
}
if (args.length !== 1) {
throwError(state, "YAML directive accepts exactly one argument");
}
match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
if (match === null) {
throwError(state, "ill-formed argument of the YAML directive");
}
major = parseInt(match[1], 10);
minor = parseInt(match[2], 10);
if (major !== 1) {
throwError(state, "unacceptable YAML version of the document");
}
state.version = args[0];
state.checkLineBreaks = minor < 2;
if (minor !== 1 && minor !== 2) {
throwWarning(state, "unsupported YAML version of the document");
}
},
TAG: function handleTagDirective(state, name, args) {
var handle2, prefix;
if (args.length !== 2) {
throwError(state, "TAG directive accepts exactly two arguments");
}
handle2 = args[0];
prefix = args[1];
if (!PATTERN_TAG_HANDLE.test(handle2)) {
throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
}
if (_hasOwnProperty.call(state.tagMap, handle2)) {
throwError(state, 'there is a previously declared suffix for "' + handle2 + '" tag handle');
}
if (!PATTERN_TAG_URI.test(prefix)) {
throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
}
state.tagMap[handle2] = prefix;
}
};
function captureSegment(state, start, end, checkJson) {
var _position, _length, _character, _result;
if (start < end) {
_result = state.input.slice(start, end);
if (checkJson) {
for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
_character = _result.charCodeAt(_position);
if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
throwError(state, "expected valid JSON character");
}
}
} else if (PATTERN_NON_PRINTABLE.test(_result)) {
throwError(state, "the stream contains non-printable characters");
}
state.result += _result;
}
}
function mergeMappings(state, destination, source, overridableKeys) {
var sourceKeys, key, index2, quantity;
if (!common.isObject(source)) {
throwError(state, "cannot merge mappings; the provided source object is unacceptable");
}
sourceKeys = Object.keys(source);
for (index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) {
key = sourceKeys[index2];
if (!_hasOwnProperty.call(destination, key)) {
setProperty(destination, key, source[key]);
overridableKeys[key] = true;
}
}
}
function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
var index2, quantity;
if (Array.isArray(keyNode)) {
keyNode = Array.prototype.slice.call(keyNode);
for (index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) {
if (Array.isArray(keyNode[index2])) {
throwError(state, "nested arrays are not supported inside keys");
}
if (typeof keyNode === "object" && _class(keyNode[index2]) === "[object Object]") {
keyNode[index2] = "[object Object]";
}
}
}
if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
keyNode = "[object Object]";
}
keyNode = String(keyNode);
if (_result === null) {
_result = {};
}
if (keyTag === "tag:yaml.org,2002:merge") {
if (Array.isArray(valueNode)) {
for (index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) {
mergeMappings(state, _result, valueNode[index2], overridableKeys);
}
} else {
mergeMappings(state, _result, valueNode, overridableKeys);
}
} else {
if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
state.line = startLine || state.line;
state.position = startPos || state.position;
throwError(state, "duplicated mapping key");
}
setProperty(_result, keyNode, valueNode);
delete overridableKeys[keyNode];
}
return _result;
}
function readLineBreak(state) {
var ch;
ch = state.input.charCodeAt(state.position);
if (ch === 10) {
state.position++;
} else if (ch === 13) {
state.position++;
if (state.input.charCodeAt(state.position) === 10) {
state.position++;
}
} else {
throwError(state, "a line break is expected");
}
state.line += 1;
state.lineStart = state.position;
}
function skipSeparationSpace(state, allowComments, checkIndent) {
var lineBreaks = 0, ch = state.input.charCodeAt(state.position);
while (ch !== 0) {
while (is_WHITE_SPACE(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (allowComments && ch === 35) {
do {
ch = state.input.charCodeAt(++state.position);
} while (ch !== 10 && ch !== 13 && ch !== 0);
}
if (is_EOL(ch)) {
readLineBreak(state);
ch = state.input.charCodeAt(state.position);
lineBreaks++;
state.lineIndent = 0;
while (ch === 32) {
state.lineIndent++;
ch = state.input.charCodeAt(++state.position);
}
} else {
break;
}
}
if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
throwWarning(state, "deficient indentation");
}
return lineBreaks;
}
function testDocumentSeparator(state) {
var _position = state.position, ch;
ch = state.input.charCodeAt(_position);
if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
_position += 3;
ch = state.input.charCodeAt(_position);
if (ch === 0 || is_WS_OR_EOL(ch)) {
return true;
}
}
return false;
}
function writeFoldedLines(state, count) {
if (count === 1) {
state.result += " ";
} else if (count > 1) {
state.result += common.repeat("\n", count - 1);
}
}
function readPlainScalar(state, nodeIndent, withinFlowCollection) {
var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;
ch = state.input.charCodeAt(state.position);
if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
return false;
}
if (ch === 63 || ch === 45) {
following = state.input.charCodeAt(state.position + 1);
if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
return false;
}
}
state.kind = "scalar";
state.result = "";
captureStart = captureEnd = state.position;
hasPendingContent = false;
while (ch !== 0) {
if (ch === 58) {
following = state.input.charCodeAt(state.position + 1);
if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
break;
}
} else if (ch === 35) {
preceding = state.input.charCodeAt(state.position - 1);
if (is_WS_OR_EOL(preceding)) {
break;
}
} else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
break;
} else if (is_EOL(ch)) {
_line = state.line;
_lineStart = state.lineStart;
_lineIndent = state.lineIndent;
skipSeparationSpace(state, false, -1);
if (state.lineIndent >= nodeIndent) {
hasPendingContent = true;
ch = state.input.charCodeAt(state.position);
continue;
} else {
state.position = captureEnd;
state.line = _line;
state.lineStart = _lineStart;
state.lineIndent = _lineIndent;
break;
}
}
if (hasPendingContent) {
captureSegment(state, captureStart, captureEnd, false);
writeFoldedLines(state, state.line - _line);
captureStart = captureEnd = state.position;
hasPendingContent = false;
}
if (!is_WHITE_SPACE(ch)) {
captureEnd = state.position + 1;
}
ch = state.input.charCodeAt(++state.position);
}
captureSegment(state, captureStart, captureEnd, false);
if (state.result) {
return true;
}
state.kind = _kind;
state.result = _result;
return false;
}
function readSingleQuotedScalar(state, nodeIndent) {
var ch, captureStart, captureEnd;
ch = state.input.charCodeAt(state.position);
if (ch !== 39) {
return false;
}
state.kind = "scalar";
state.result = "";
state.position++;
captureStart = captureEnd = state.position;
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
if (ch === 39) {
captureSegment(state, captureStart, state.position, true);
ch = state.input.charCodeAt(++state.position);
if (ch === 39) {
captureStart = state.position;
state.position++;
captureEnd = state.position;
} else {
return true;
}
} else if (is_EOL(ch)) {
captureSegment(state, captureStart, captureEnd, true);
writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
captureStart = captureEnd = state.position;
} else if (state.position === state.lineStart && testDocumentSeparator(state)) {
throwError(state, "unexpected end of the document within a single quoted scalar");
} else {
state.position++;
captureEnd = state.position;
}
}
throwError(state, "unexpected end of the stream within a single quoted scalar");
}
function readDoubleQuotedScalar(state, nodeIndent) {
var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 34) {
return false;
}
state.kind = "scalar";
state.result = "";
state.position++;
captureStart = captureEnd = state.position;
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
if (ch === 34) {
captureSegment(state, captureStart, state.position, true);
state.position++;
return true;
} else if (ch === 92) {
captureSegment(state, captureStart, state.position, true);
ch = state.input.charCodeAt(++state.position);
if (is_EOL(ch)) {
skipSeparationSpace(state, false, nodeIndent);
} else if (ch < 256 && simpleEscapeCheck[ch]) {
state.result += simpleEscapeMap[ch];
state.position++;
} else if ((tmp = escapedHexLen(ch)) > 0) {
hexLength = tmp;
hexResult = 0;
for (; hexLength > 0; hexLength--) {
ch = state.input.charCodeAt(++state.position);
if ((tmp = fromHexCode(ch)) >= 0) {
hexResult = (hexResult << 4) + tmp;
} else {
throwError(state, "expected hexadecimal character");
}
}
state.result += charFromCodepoint(hexResult);
state.position++;
} else {
throwError(state, "unknown escape sequence");
}
captureStart = captureEnd = state.position;
} else if (is_EOL(ch)) {
captureSegment(state, captureStart, captureEnd, true);
writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
captureStart = captureEnd = state.position;
} else if (state.position === state.lineStart && testDocumentSeparator(state)) {
throwError(state, "unexpected end of the document within a double quoted scalar");
} else {
state.position++;
captureEnd = state.position;
}
}
throwError(state, "unexpected end of the stream within a double quoted scalar");
}
function readFlowCollection(state, nodeIndent) {
var readNext = true, _line, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = {}, keyNode, keyTag, valueNode, ch;
ch = state.input.charCodeAt(state.position);
if (ch === 91) {
terminator = 93;
isMapping = false;
_result = [];
} else if (ch === 123) {
terminator = 125;
isMapping = true;
_result = {};
} else {
return false;
}
if (state.anchor !== null) {
state.anchorMap[state.anchor] = _result;
}
ch = state.input.charCodeAt(++state.position);
while (ch !== 0) {
skipSeparationSpace(state, true, nodeIndent);
ch = state.input.charCodeAt(state.position);
if (ch === terminator) {
state.position++;
state.tag = _tag;
state.anchor = _anchor;
state.kind = isMapping ? "mapping" : "sequence";
state.result = _result;
return true;
} else if (!readNext) {
throwError(state, "missed comma between flow collection entries");
}
keyTag = keyNode = valueNode = null;
isPair = isExplicitPair = false;
if (ch === 63) {
following = state.input.charCodeAt(state.position + 1);
if (is_WS_OR_EOL(following)) {
isPair = isExplicitPair = true;
state.position++;
skipSeparationSpace(state, true, nodeIndent);
}
}
_line = state.line;
composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
keyTag = state.tag;
keyNode = state.result;
skipSeparationSpace(state, true, nodeIndent);
ch = state.input.charCodeAt(state.position);
if ((isExplicitPair || state.line === _line) && ch === 58) {
isPair = true;
ch = state.input.charCodeAt(++state.position);
skipSeparationSpace(state, true, nodeIndent);
composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
valueNode = state.result;
}
if (isMapping) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
} else if (isPair) {
_result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
} else {
_result.push(keyNode);
}
skipSeparationSpace(state, true, nodeIndent);
ch = state.input.charCodeAt(state.position);
if (ch === 44) {
readNext = true;
ch = state.input.charCodeAt(++state.position);
} else {
readNext = false;
}
}
throwError(state, "unexpected end of the stream within a flow collection");
}
function readBlockScalar(state, nodeIndent) {
var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
ch = state.input.charCodeAt(state.position);
if (ch === 124) {
folding = false;
} else if (ch === 62) {
folding = true;
} else {
return false;
}
state.kind = "scalar";
state.result = "";
while (ch !== 0) {
ch = state.input.charCodeAt(++state.position);
if (ch === 43 || ch === 45) {
if (CHOMPING_CLIP === chomping) {
chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
} else {
throwError(state, "repeat of a chomping mode identifier");
}
} else if ((tmp = fromDecimalCode(ch)) >= 0) {
if (tmp === 0) {
throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
} else if (!detectedIndent) {
textIndent = nodeIndent + tmp - 1;
detectedIndent = true;
} else {
throwError(state, "repeat of an indentation width identifier");
}
} else {
break;
}
}
if (is_WHITE_SPACE(ch)) {
do {
ch = state.input.charCodeAt(++state.position);
} while (is_WHITE_SPACE(ch));
if (ch === 35) {
do {
ch = state.input.charCodeAt(++state.position);
} while (!is_EOL(ch) && ch !== 0);
}
}
while (ch !== 0) {
readLineBreak(state);
state.lineIndent = 0;
ch = state.input.charCodeAt(state.position);
while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
state.lineIndent++;
ch = state.input.charCodeAt(++state.position);
}
if (!detectedIndent && state.lineIndent > textIndent) {
textIndent = state.lineIndent;
}
if (is_EOL(ch)) {
emptyLines++;
continue;
}
if (state.lineIndent < textIndent) {
if (chomping === CHOMPING_KEEP) {
state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
} else if (chomping === CHOMPING_CLIP) {
if (didReadContent) {
state.result += "\n";
}
}
break;
}
if (folding) {
if (is_WHITE_SPACE(ch)) {
atMoreIndented = true;
state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
} else if (atMoreIndented) {
atMoreIndented = false;
state.result += common.repeat("\n", emptyLines + 1);
} else if (emptyLines === 0) {
if (didReadContent) {
state.result += " ";
}
} else {
state.result += common.repeat("\n", emptyLines);
}
} else {
state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
}
didReadContent = true;
detectedIndent = true;
emptyLines = 0;
captureStart = state.position;
while (!is_EOL(ch) && ch !== 0) {
ch = state.input.charCodeAt(++state.position);
}
captureSegment(state, captureStart, state.position, false);
}
return true;
}
function readBlockSequence(state, nodeIndent) {
var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;
if (state.anchor !== null) {
state.anchorMap[state.anchor] = _result;
}
ch = state.input.charCodeAt(state.position);
while (ch !== 0) {
if (ch !== 45) {
break;
}
following = state.input.charCodeAt(state.position + 1);
if (!is_WS_OR_EOL(following)) {
break;
}
detected = true;
state.position++;
if (skipSeparationSpace(state, true, -1)) {
if (state.lineIndent <= nodeIndent) {
_result.push(null);
ch = state.input.charCodeAt(state.position);
continue;
}
}
_line = state.line;
composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
_result.push(state.result);
skipSeparationSpace(state, true, -1);
ch = state.input.charCodeAt(state.position);
if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
throwError(state, "bad indentation of a sequence entry");
} else if (state.lineIndent < nodeIndent) {
break;
}
}
if (detected) {
state.tag = _tag;
state.anchor = _anchor;
state.kind = "sequence";
state.result = _result;
return true;
}
return false;
}
function readBlockMapping(state, nodeIndent, flowIndent) {
var following, allowCompact, _line, _pos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = {}, keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
if (state.anchor !== null) {
state.anchorMap[state.anchor] = _result;
}
ch = state.input.charCodeAt(state.position);
while (ch !== 0) {
following = state.input.charCodeAt(state.position + 1);
_line = state.line;
_pos = state.position;
if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
if (ch === 63) {
if (atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
keyTag = keyNode = valueNode = null;
}
detected = true;
atExplicitKey = true;
allowCompact = true;
} else if (atExplicitKey) {
atExplicitKey = false;
allowCompact = true;
} else {
throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
}
state.position += 1;
ch = following;
} else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
if (state.line === _line) {
ch = state.input.charCodeAt(state.position);
while (is_WHITE_SPACE(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (ch === 58) {
ch = state.input.charCodeAt(++state.position);
if (!is_WS_OR_EOL(ch)) {
throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
}
if (atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
keyTag = keyNode = valueNode = null;
}
detected = true;
atExplicitKey = false;
allowCompact = false;
keyTag = state.tag;
keyNode = state.result;
} else if (detected) {
throwError(state, "can not read an implicit mapping pair; a colon is missed");
} else {
state.tag = _tag;
state.anchor = _anchor;
return true;
}
} else if (detected) {
throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
} else {
state.tag = _tag;
state.anchor = _anchor;
return true;
}
} else {
break;
}
if (state.line === _line || state.lineIndent > nodeIndent) {
if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
if (atExplicitKey) {
keyNode = state.result;
} else {
valueNode = state.result;
}
}
if (!atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
keyTag = keyNode = valueNode = null;
}
skipSeparationSpace(state, true, -1);
ch = state.input.charCodeAt(state.position);
}
if (state.lineIndent > nodeIndent && ch !== 0) {
throwError(state, "bad indentation of a mapping entry");
} else if (state.lineIndent < nodeIndent) {
break;
}
}
if (atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
}
if (detected) {
state.tag = _tag;
state.anchor = _anchor;
state.kind = "mapping";
state.result = _result;
}
return detected;
}
function readTagProperty(state) {
var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 33)
return false;
if (state.tag !== null) {
throwError(state, "duplication of a tag property");
}
ch = state.input.charCodeAt(++state.position);
if (ch === 60) {
isVerbatim = true;
ch = state.input.charCodeAt(++state.position);
} else if (ch === 33) {
isNamed = true;
tagHandle = "!!";
ch = state.input.charCodeAt(++state.position);
} else {
tagHandle = "!";
}
_position = state.position;
if (isVerbatim) {
do {
ch = state.input.charCodeAt(++state.position);
} while (ch !== 0 && ch !== 62);
if (state.position < state.length) {
tagName = state.input.slice(_position, state.position);
ch = state.input.charCodeAt(++state.position);
} else {
throwError(state, "unexpected end of the stream within a verbatim tag");
}
} else {
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
if (ch === 33) {
if (!isNamed) {
tagHandle = state.input.slice(_position - 1, state.position + 1);
if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
throwError(state, "named tag handle cannot contain such characters");
}
isNamed = true;
_position = state.position + 1;
} else {
throwError(state, "tag suffix cannot contain exclamation marks");
}
}
ch = state.input.charCodeAt(++state.position);
}
tagName = state.input.slice(_position, state.position);
if (PATTERN_FLOW_INDICATORS.test(tagName)) {
throwError(state, "tag suffix cannot contain flow indicator characters");
}
}
if (tagName && !PATTERN_TAG_URI.test(tagName)) {
throwError(state, "tag name cannot contain such characters: " + tagName);
}
if (isVerbatim) {
state.tag = tagName;
} else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
state.tag = state.tagMap[tagHandle] + tagName;
} else if (tagHandle === "!") {
state.tag = "!" + tagName;
} else if (tagHandle === "!!") {
state.tag = "tag:yaml.org,2002:" + tagName;
} else {
throwError(state, 'undeclared tag handle "' + tagHandle + '"');
}
return true;
}
function readAnchorProperty(state) {
var _position, ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 38)
return false;
if (state.anchor !== null) {
throwError(state, "duplication of an anchor property");
}
ch = state.input.charCodeAt(++state.position);
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (state.position === _position) {
throwError(state, "name of an anchor node must contain at least one character");
}
state.anchor = state.input.slice(_position, state.position);
return true;
}
function readAlias(state) {
var _position, alias, ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 42)
return false;
ch = state.input.charCodeAt(++state.position);
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (state.position === _position) {
throwError(state, "name of an alias node must contain at least one character");
}
alias = state.input.slice(_position, state.position);
if (!_hasOwnProperty.call(state.anchorMap, alias)) {
throwError(state, 'unidentified alias "' + alias + '"');
}
state.result = state.anchorMap[alias];
skipSeparationSpace(state, true, -1);
return true;
}
function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, type, flowIndent, blockIndent;
if (state.listener !== null) {
state.listener("open", state);
}
state.tag = null;
state.anchor = null;
state.kind = null;
state.result = null;
allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
if (allowToSeek) {
if (skipSeparationSpace(state, true, -1)) {
atNewLine = true;
if (state.lineIndent > parentIndent) {
indentStatus = 1;
} else if (state.lineIndent === parentIndent) {
indentStatus = 0;
} else if (state.lineIndent < parentIndent) {
indentStatus = -1;
}
}
}
if (indentStatus === 1) {
while (readTagProperty(state) || readAnchorProperty(state)) {
if (skipSeparationSpace(state, true, -1)) {
atNewLine = true;
allowBlockCollections = allowBlockStyles;
if (state.lineIndent > parentIndent) {
indentStatus = 1;
} else if (state.lineIndent === parentIndent) {
indentStatus = 0;
} else if (state.lineIndent < parentIndent) {
indentStatus = -1;
}
} else {
allowBlockCollections = false;
}
}
}
if (allowBlockCollections) {
allowBlockCollections = atNewLine || allowCompact;
}
if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
flowIndent = parentIndent;
} else {
flowIndent = parentIndent + 1;
}
blockIndent = state.position - state.lineStart;
if (indentStatus === 1) {
if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
hasContent = true;
} else {
if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
hasContent = true;
} else if (readAlias(state)) {
hasContent = true;
if (state.tag !== null || state.anchor !== null) {
throwError(state, "alias node should not have any properties");
}
} else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
hasContent = true;
if (state.tag === null) {
state.tag = "?";
}
}
if (state.anchor !== null) {
state.anchorMap[state.anchor] = state.result;
}
}
} else if (indentStatus === 0) {
hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
}
}
if (state.tag !== null && state.tag !== "!") {
if (state.tag === "?") {
if (state.result !== null && state.kind !== "scalar") {
throwError(state, 'unacceptable node kind for !> tag; it should be "scalar", not "' + state.kind + '"');
}
for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
type = state.implicitTypes[typeIndex];
if (type.resolve(state.result)) {
state.result = type.construct(state.result);
state.tag = type.tag;
if (state.anchor !== null) {
state.anchorMap[state.anchor] = state.result;
}
break;
}
}
} else if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) {
type = state.typeMap[state.kind || "fallback"][state.tag];
if (state.result !== null && type.kind !== state.kind) {
throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
}
if (!type.resolve(state.result)) {
throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
} else {
state.result = type.construct(state.result);
if (state.anchor !== null) {
state.anchorMap[state.anchor] = state.result;
}
}
} else {
throwError(state, "unknown tag !<" + state.tag + ">");
}
}
if (state.listener !== null) {
state.listener("close", state);
}
return state.tag !== null || state.anchor !== null || hasContent;
}
function readDocument(state) {
var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
state.version = null;
state.checkLineBreaks = state.legacy;
state.tagMap = {};
state.anchorMap = {};
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
skipSeparationSpace(state, true, -1);
ch = state.input.charCodeAt(state.position);
if (state.lineIndent > 0 || ch !== 37) {
break;
}
hasDirectives = true;
ch = state.input.charCodeAt(++state.position);
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
ch = state.input.charCodeAt(++state.position);
}
directiveName = state.input.slice(_position, state.position);
directiveArgs = [];
if (directiveName.length < 1) {
throwError(state, "directive name must not be less than one character in length");
}
while (ch !== 0) {
while (is_WHITE_SPACE(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (ch === 35) {
do {
ch = state.input.charCodeAt(++state.position);
} while (ch !== 0 && !is_EOL(ch));
break;
}
if (is_EOL(ch))
break;
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
ch = state.input.charCodeAt(++state.position);
}
directiveArgs.push(state.input.slice(_position, state.position));
}
if (ch !== 0)
readLineBreak(state);
if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
directiveHandlers[directiveName](state, directiveName, directiveArgs);
} else {
throwWarning(state, 'unknown document directive "' + directiveName + '"');
}
}
skipSeparationSpace(state, true, -1);
if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
state.position += 3;
skipSeparationSpace(state, true, -1);
} else if (hasDirectives) {
throwError(state, "directives end mark is expected");
}
composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
skipSeparationSpace(state, true, -1);
if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
throwWarning(state, "non-ASCII line breaks are interpreted as content");
}
state.documents.push(state.result);
if (state.position === state.lineStart && testDocumentSeparator(state)) {
if (state.input.charCodeAt(state.position) === 46) {
state.position += 3;
skipSeparationSpace(state, true, -1);
}
return;
}
if (state.position < state.length - 1) {
throwError(state, "end of the stream or a document separator is expected");
} else {
return;
}
}
function loadDocuments(input, options) {
input = String(input);
options = options || {};
if (input.length !== 0) {
if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
input += "\n";
}
if (input.charCodeAt(0) === 65279) {
input = input.slice(1);
}
}
var state = new State(input, options);
var nullpos = input.indexOf("\0");
if (nullpos !== -1) {
state.position = nullpos;
throwError(state, "null byte is not allowed in input");
}
state.input += "\0";
while (state.input.charCodeAt(state.position) === 32) {
state.lineIndent += 1;
state.position += 1;
}
while (state.position < state.length - 1) {
readDocument(state);
}
return state.documents;
}
function loadAll(input, iterator, options) {
if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
options = iterator;
iterator = null;
}
var documents = loadDocuments(input, options);
if (typeof iterator !== "function") {
return documents;
}
for (var index2 = 0, length = documents.length; index2 < length; index2 += 1) {
iterator(documents[index2]);
}
}
function load(input, options) {
var documents = loadDocuments(input, options);
if (documents.length === 0) {
return void 0;
} else if (documents.length === 1) {
return documents[0];
}
throw new YAMLException("expected a single document in the stream, but found more");
}
function safeLoadAll(input, iterator, options) {
if (typeof iterator === "object" && iterator !== null && typeof options === "undefined") {
options = iterator;
iterator = null;
}
return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
function safeLoad(input, options) {
return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
module2.exports.loadAll = loadAll;
module2.exports.load = load;
module2.exports.safeLoadAll = safeLoadAll;
module2.exports.safeLoad = safeLoad;
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/dumper.js
var require_dumper = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml/dumper.js"(exports, module2) {
"use strict";
var common = require_common();
var YAMLException = require_exception();
var DEFAULT_FULL_SCHEMA = require_default_full();
var DEFAULT_SAFE_SCHEMA = require_default_safe();
var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CHAR_TAB = 9;
var CHAR_LINE_FEED = 10;
var CHAR_CARRIAGE_RETURN = 13;
var CHAR_SPACE = 32;
var CHAR_EXCLAMATION = 33;
var CHAR_DOUBLE_QUOTE = 34;
var CHAR_SHARP = 35;
var CHAR_PERCENT = 37;
var CHAR_AMPERSAND = 38;
var CHAR_SINGLE_QUOTE = 39;
var CHAR_ASTERISK = 42;
var CHAR_COMMA = 44;
var CHAR_MINUS = 45;
var CHAR_COLON = 58;
var CHAR_EQUALS = 61;
var CHAR_GREATER_THAN = 62;
var CHAR_QUESTION = 63;
var CHAR_COMMERCIAL_AT = 64;
var CHAR_LEFT_SQUARE_BRACKET = 91;
var CHAR_RIGHT_SQUARE_BRACKET = 93;
var CHAR_GRAVE_ACCENT = 96;
var CHAR_LEFT_CURLY_BRACKET = 123;
var CHAR_VERTICAL_LINE = 124;
var CHAR_RIGHT_CURLY_BRACKET = 125;
var ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0] = "\\0";
ESCAPE_SEQUENCES[7] = "\\a";
ESCAPE_SEQUENCES[8] = "\\b";
ESCAPE_SEQUENCES[9] = "\\t";
ESCAPE_SEQUENCES[10] = "\\n";
ESCAPE_SEQUENCES[11] = "\\v";
ESCAPE_SEQUENCES[12] = "\\f";
ESCAPE_SEQUENCES[13] = "\\r";
ESCAPE_SEQUENCES[27] = "\\e";
ESCAPE_SEQUENCES[34] = '\\"';
ESCAPE_SEQUENCES[92] = "\\\\";
ESCAPE_SEQUENCES[133] = "\\N";
ESCAPE_SEQUENCES[160] = "\\_";
ESCAPE_SEQUENCES[8232] = "\\L";
ESCAPE_SEQUENCES[8233] = "\\P";
var DEPRECATED_BOOLEANS_SYNTAX = [
"y",
"Y",
"yes",
"Yes",
"YES",
"on",
"On",
"ON",
"n",
"N",
"no",
"No",
"NO",
"off",
"Off",
"OFF"
];
function compileStyleMap(schema, map3) {
var result, keys, index2, length, tag, style, type;
if (map3 === null)
return {};
result = {};
keys = Object.keys(map3);
for (index2 = 0, length = keys.length; index2 < length; index2 += 1) {
tag = keys[index2];
style = String(map3[tag]);
if (tag.slice(0, 2) === "!!") {
tag = "tag:yaml.org,2002:" + tag.slice(2);
}
type = schema.compiledTypeMap["fallback"][tag];
if (type && _hasOwnProperty.call(type.styleAliases, style)) {
style = type.styleAliases[style];
}
result[tag] = style;
}
return result;
}
function encodeHex(character) {
var string3, handle2, length;
string3 = character.toString(16).toUpperCase();
if (character <= 255) {
handle2 = "x";
length = 2;
} else if (character <= 65535) {
handle2 = "u";
length = 4;
} else if (character <= 4294967295) {
handle2 = "U";
length = 8;
} else {
throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF");
}
return "\\" + handle2 + common.repeat("0", length - string3.length) + string3;
}
function State(options) {
this.schema = options["schema"] || DEFAULT_FULL_SCHEMA;
this.indent = Math.max(1, options["indent"] || 2);
this.noArrayIndent = options["noArrayIndent"] || false;
this.skipInvalid = options["skipInvalid"] || false;
this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
this.sortKeys = options["sortKeys"] || false;
this.lineWidth = options["lineWidth"] || 80;
this.noRefs = options["noRefs"] || false;
this.noCompatMode = options["noCompatMode"] || false;
this.condenseFlow = options["condenseFlow"] || false;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
this.tag = null;
this.result = "";
this.duplicates = [];
this.usedDuplicates = null;
}
function indentString(string3, spaces) {
var ind = common.repeat(" ", spaces), position2 = 0, next = -1, result = "", line, length = string3.length;
while (position2 < length) {
next = string3.indexOf("\n", position2);
if (next === -1) {
line = string3.slice(position2);
position2 = length;
} else {
line = string3.slice(position2, next + 1);
position2 = next + 1;
}
if (line.length && line !== "\n")
result += ind;
result += line;
}
return result;
}
function generateNextLine(state, level) {
return "\n" + common.repeat(" ", state.indent * level);
}
function testImplicitResolving(state, str) {
var index2, length, type;
for (index2 = 0, length = state.implicitTypes.length; index2 < length; index2 += 1) {
type = state.implicitTypes[index2];
if (type.resolve(str)) {
return true;
}
}
return false;
}
function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
function isPrintable(c) {
return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== 65279 || 65536 <= c && c <= 1114111;
}
function isNsChar(c) {
return isPrintable(c) && !isWhitespace(c) && c !== 65279 && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
}
function isPlainSafe(c, prev) {
return isPrintable(c) && c !== 65279 && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_COLON && (c !== CHAR_SHARP || prev && isNsChar(prev));
}
function isPlainSafeFirst(c) {
return isPrintable(c) && c !== 65279 && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
}
function needIndentIndicator(string3) {
var leadingSpaceRe = /^\n* /;
return leadingSpaceRe.test(string3);
}
var STYLE_PLAIN = 1;
var STYLE_SINGLE = 2;
var STYLE_LITERAL = 3;
var STYLE_FOLDED = 4;
var STYLE_DOUBLE = 5;
function chooseScalarStyle(string3, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
var i;
var char, prev_char;
var hasLineBreak = false;
var hasFoldableLine = false;
var shouldTrackWidth = lineWidth !== -1;
var previousLineBreak = -1;
var plain = isPlainSafeFirst(string3.charCodeAt(0)) && !isWhitespace(string3.charCodeAt(string3.length - 1));
if (singleLineOnly) {
for (i = 0; i < string3.length; i++) {
char = string3.charCodeAt(i);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
prev_char = i > 0 ? string3.charCodeAt(i - 1) : null;
plain = plain && isPlainSafe(char, prev_char);
}
} else {
for (i = 0; i < string3.length; i++) {
char = string3.charCodeAt(i);
if (char === CHAR_LINE_FEED) {
hasLineBreak = true;
if (shouldTrackWidth) {
hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
i - previousLineBreak - 1 > lineWidth && string3[previousLineBreak + 1] !== " ";
previousLineBreak = i;
}
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
prev_char = i > 0 ? string3.charCodeAt(i - 1) : null;
plain = plain && isPlainSafe(char, prev_char);
}
hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string3[previousLineBreak + 1] !== " ");
}
if (!hasLineBreak && !hasFoldableLine) {
return plain && !testAmbiguousType(string3) ? STYLE_PLAIN : STYLE_SINGLE;
}
if (indentPerLevel > 9 && needIndentIndicator(string3)) {
return STYLE_DOUBLE;
}
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}
function writeScalar(state, string3, level, iskey) {
state.dump = function() {
if (string3.length === 0) {
return "''";
}
if (!state.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string3) !== -1) {
return "'" + string3 + "'";
}
var indent2 = state.indent * Math.max(1, level);
var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent2);
var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
function testAmbiguity(string4) {
return testImplicitResolving(state, string4);
}
switch (chooseScalarStyle(string3, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
case STYLE_PLAIN:
return string3;
case STYLE_SINGLE:
return "'" + string3.replace(/'/g, "''") + "'";
case STYLE_LITERAL:
return "|" + blockHeader(string3, state.indent) + dropEndingNewline(indentString(string3, indent2));
case STYLE_FOLDED:
return ">" + blockHeader(string3, state.indent) + dropEndingNewline(indentString(foldString(string3, lineWidth), indent2));
case STYLE_DOUBLE:
return '"' + escapeString(string3, lineWidth) + '"';
default:
throw new YAMLException("impossible error: invalid scalar style");
}
}();
}
function blockHeader(string3, indentPerLevel) {
var indentIndicator = needIndentIndicator(string3) ? String(indentPerLevel) : "";
var clip = string3[string3.length - 1] === "\n";
var keep = clip && (string3[string3.length - 2] === "\n" || string3 === "\n");
var chomp = keep ? "+" : clip ? "" : "-";
return indentIndicator + chomp + "\n";
}
function dropEndingNewline(string3) {
return string3[string3.length - 1] === "\n" ? string3.slice(0, -1) : string3;
}
function foldString(string3, width) {
var lineRe = /(\n+)([^\n]*)/g;
var result = function() {
var nextLF = string3.indexOf("\n");
nextLF = nextLF !== -1 ? nextLF : string3.length;
lineRe.lastIndex = nextLF;
return foldLine(string3.slice(0, nextLF), width);
}();
var prevMoreIndented = string3[0] === "\n" || string3[0] === " ";
var moreIndented;
var match;
while (match = lineRe.exec(string3)) {
var prefix = match[1], line = match[2];
moreIndented = line[0] === " ";
result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
prevMoreIndented = moreIndented;
}
return result;
}
function foldLine(line, width) {
if (line === "" || line[0] === " ")
return line;
var breakRe = / [^ ]/g;
var match;
var start = 0, end, curr = 0, next = 0;
var result = "";
while (match = breakRe.exec(line)) {
next = match.index;
if (next - start > width) {
end = curr > start ? curr : next;
result += "\n" + line.slice(start, end);
start = end + 1;
}
curr = next;
}
result += "\n";
if (line.length - start > width && curr > start) {
result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
} else {
result += line.slice(start);
}
return result.slice(1);
}
function escapeString(string3) {
var result = "";
var char, nextChar;
var escapeSeq;
for (var i = 0; i < string3.length; i++) {
char = string3.charCodeAt(i);
if (char >= 55296 && char <= 56319) {
nextChar = string3.charCodeAt(i + 1);
if (nextChar >= 56320 && nextChar <= 57343) {
result += encodeHex((char - 55296) * 1024 + nextChar - 56320 + 65536);
i++;
continue;
}
}
escapeSeq = ESCAPE_SEQUENCES[char];
result += !escapeSeq && isPrintable(char) ? string3[i] : escapeSeq || encodeHex(char);
}
return result;
}
function writeFlowSequence(state, level, object) {
var _result = "", _tag = state.tag, index2, length;
for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
if (writeNode(state, level, object[index2], false, false)) {
if (index2 !== 0)
_result += "," + (!state.condenseFlow ? " " : "");
_result += state.dump;
}
}
state.tag = _tag;
state.dump = "[" + _result + "]";
}
function writeBlockSequence(state, level, object, compact) {
var _result = "", _tag = state.tag, index2, length;
for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
if (writeNode(state, level + 1, object[index2], true, true)) {
if (!compact || index2 !== 0) {
_result += generateNextLine(state, level);
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
_result += "-";
} else {
_result += "- ";
}
_result += state.dump;
}
}
state.tag = _tag;
state.dump = _result || "[]";
}
function writeFlowMapping(state, level, object) {
var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, pairBuffer;
for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
pairBuffer = "";
if (index2 !== 0)
pairBuffer += ", ";
if (state.condenseFlow)
pairBuffer += '"';
objectKey = objectKeyList[index2];
objectValue = object[objectKey];
if (!writeNode(state, level, objectKey, false, false)) {
continue;
}
if (state.dump.length > 1024)
pairBuffer += "? ";
pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
if (!writeNode(state, level, objectValue, false, false)) {
continue;
}
pairBuffer += state.dump;
_result += pairBuffer;
}
state.tag = _tag;
state.dump = "{" + _result + "}";
}
function writeBlockMapping(state, level, object, compact) {
var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, explicitPair, pairBuffer;
if (state.sortKeys === true) {
objectKeyList.sort();
} else if (typeof state.sortKeys === "function") {
objectKeyList.sort(state.sortKeys);
} else if (state.sortKeys) {
throw new YAMLException("sortKeys must be a boolean or a function");
}
for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
pairBuffer = "";
if (!compact || index2 !== 0) {
pairBuffer += generateNextLine(state, level);
}
objectKey = objectKeyList[index2];
objectValue = object[objectKey];
if (!writeNode(state, level + 1, objectKey, true, true, true)) {
continue;
}
explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
if (explicitPair) {
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += "?";
} else {
pairBuffer += "? ";
}
}
pairBuffer += state.dump;
if (explicitPair) {
pairBuffer += generateNextLine(state, level);
}
if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
continue;
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += ":";
} else {
pairBuffer += ": ";
}
pairBuffer += state.dump;
_result += pairBuffer;
}
state.tag = _tag;
state.dump = _result || "{}";
}
function detectType(state, object, explicit) {
var _result, typeList, index2, length, type, style;
typeList = explicit ? state.explicitTypes : state.implicitTypes;
for (index2 = 0, length = typeList.length; index2 < length; index2 += 1) {
type = typeList[index2];
if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {
state.tag = explicit ? type.tag : "?";
if (type.represent) {
style = state.styleMap[type.tag] || type.defaultStyle;
if (_toString.call(type.represent) === "[object Function]") {
_result = type.represent(object, style);
} else if (_hasOwnProperty.call(type.represent, style)) {
_result = type.represent[style](object, style);
} else {
throw new YAMLException("!<" + type.tag + '> tag resolver accepts not "' + style + '" style');
}
state.dump = _result;
}
return true;
}
}
return false;
}
function writeNode(state, level, object, block, compact, iskey) {
state.tag = null;
state.dump = object;
if (!detectType(state, object, false)) {
detectType(state, object, true);
}
var type = _toString.call(state.dump);
if (block) {
block = state.flowLevel < 0 || state.flowLevel > level;
}
var objectOrArray = type === "[object Object]" || type === "[object Array]", duplicateIndex, duplicate;
if (objectOrArray) {
duplicateIndex = state.duplicates.indexOf(object);
duplicate = duplicateIndex !== -1;
}
if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
compact = false;
}
if (duplicate && state.usedDuplicates[duplicateIndex]) {
state.dump = "*ref_" + duplicateIndex;
} else {
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
state.usedDuplicates[duplicateIndex] = true;
}
if (type === "[object Object]") {
if (block && Object.keys(state.dump).length !== 0) {
writeBlockMapping(state, level, state.dump, compact);
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + state.dump;
}
} else {
writeFlowMapping(state, level, state.dump);
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + " " + state.dump;
}
}
} else if (type === "[object Array]") {
var arrayLevel = state.noArrayIndent && level > 0 ? level - 1 : level;
if (block && state.dump.length !== 0) {
writeBlockSequence(state, arrayLevel, state.dump, compact);
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + state.dump;
}
} else {
writeFlowSequence(state, arrayLevel, state.dump);
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + " " + state.dump;
}
}
} else if (type === "[object String]") {
if (state.tag !== "?") {
writeScalar(state, state.dump, level, iskey);
}
} else {
if (state.skipInvalid)
return false;
throw new YAMLException("unacceptable kind of an object to dump " + type);
}
if (state.tag !== null && state.tag !== "?") {
state.dump = "!<" + state.tag + "> " + state.dump;
}
}
return true;
}
function getDuplicateReferences(object, state) {
var objects = [], duplicatesIndexes = [], index2, length;
inspectNode(object, objects, duplicatesIndexes);
for (index2 = 0, length = duplicatesIndexes.length; index2 < length; index2 += 1) {
state.duplicates.push(objects[duplicatesIndexes[index2]]);
}
state.usedDuplicates = new Array(length);
}
function inspectNode(object, objects, duplicatesIndexes) {
var objectKeyList, index2, length;
if (object !== null && typeof object === "object") {
index2 = objects.indexOf(object);
if (index2 !== -1) {
if (duplicatesIndexes.indexOf(index2) === -1) {
duplicatesIndexes.push(index2);
}
} else {
objects.push(object);
if (Array.isArray(object)) {
for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
inspectNode(object[index2], objects, duplicatesIndexes);
}
} else {
objectKeyList = Object.keys(object);
for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
inspectNode(object[objectKeyList[index2]], objects, duplicatesIndexes);
}
}
}
}
}
function dump(input, options) {
options = options || {};
var state = new State(options);
if (!state.noRefs)
getDuplicateReferences(input, state);
if (writeNode(state, 0, input, true, true))
return state.dump + "\n";
return "";
}
function safeDump(input, options) {
return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
module2.exports.dump = dump;
module2.exports.safeDump = safeDump;
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml.js
var require_js_yaml = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/lib/js-yaml.js"(exports, module2) {
"use strict";
var loader = require_loader();
var dumper = require_dumper();
function deprecated(name) {
return function() {
throw new Error("Function " + name + " is deprecated and cannot be used.");
};
}
module2.exports.Type = require_type();
module2.exports.Schema = require_schema();
module2.exports.FAILSAFE_SCHEMA = require_failsafe();
module2.exports.JSON_SCHEMA = require_json();
module2.exports.CORE_SCHEMA = require_core();
module2.exports.DEFAULT_SAFE_SCHEMA = require_default_safe();
module2.exports.DEFAULT_FULL_SCHEMA = require_default_full();
module2.exports.load = loader.load;
module2.exports.loadAll = loader.loadAll;
module2.exports.safeLoad = loader.safeLoad;
module2.exports.safeLoadAll = loader.safeLoadAll;
module2.exports.dump = dumper.dump;
module2.exports.safeDump = dumper.safeDump;
module2.exports.YAMLException = require_exception();
module2.exports.MINIMAL_SCHEMA = require_failsafe();
module2.exports.SAFE_SCHEMA = require_default_safe();
module2.exports.DEFAULT_SCHEMA = require_default_full();
module2.exports.scan = deprecated("scan");
module2.exports.parse = deprecated("parse");
module2.exports.compose = deprecated("compose");
module2.exports.addConstructor = deprecated("addConstructor");
}
});
// node_modules/yaml-front-matter/node_modules/js-yaml/index.js
var require_js_yaml2 = __commonJS({
"node_modules/yaml-front-matter/node_modules/js-yaml/index.js"(exports, module2) {
"use strict";
var yaml = require_js_yaml();
module2.exports = yaml;
}
});
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => ObsidianSyncNotionPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian16 = require("obsidian");
// src/ui/icon.ts
var import_obsidian = require("obsidian");
var icons = {
"notion-logo": `
`
};
var addIcons = () => {
Object.keys(icons).forEach((key) => {
(0, import_obsidian.addIcon)(key, icons[key]);
});
};
// src/lang/locale/en.ts
var en = {
databaseFormat: "Database Format",
databaseFormatDesc: "Select the database format to sync to: NotionNext or General.",
databaseNext: "NotionNext",
databaseGeneral: "General",
databaseCustom: "Custom",
databaseFullName: "Database Full Name",
databaseFullNameDesc: "Set a full name for your database.",
databaseFullNameText: "Enter your database's full name",
databaseAbbreviateName: "Abbreviated Name",
databaseAbbreviateNameDesc: "Set a shorter, abbreviated name for your database.",
databaseAbbreviateNameText: "Enter your database's abbreviated name",
ribbonIcon: "Sync to NotionNext",
GeneralSetting: "General Settings",
CommandID: "share-to-notionnext",
CommandName: "Sync to NotionNext",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "Sync to General Database",
NotionNextButton: "NotionNext Sync",
NotionNextButtonDesc: "Enables the 'Sync to NotionNext' command in the command palette (default: on).",
NotionNextSettingHeader: "NotionNext Database Settings",
NotionAPI: "Notion API Token",
NotionAPIDesc: "Get yours from notion.so/my-integrations.",
NotionAPIText: "Enter your Notion API Token",
DatabaseID: "Database ID",
DatabaseIDDesc: "Find this in your Notion page's top-right 'Share' menu.",
DatabaseIDText: "Enter your Database ID",
BannerUrl: "Banner URL (optional)",
BannerUrlDesc: "Leave empty for no banner. If you want a banner, enter an image URL (e.g., https://abc.com/b.png).",
BannerUrlText: "Enter your banner URL",
NotionUser: "Notion Username (optional)",
NotionUserDesc: "If your site is username.notion.site, your username is [username].",
NotionUserText: "Enter your Notion username",
NotionLinkDisplay: "Display Notion Link",
NotionLinkDisplayDesc: "If disabled, the Notion link won't be added to the front matter after syncing (default: on).",
AutoCopyNotionLink: "Auto-copy Notion Link",
AutoCopyNotionLinkDesc: "Automatically copy the Notion page link to the clipboard after syncing (default: on).",
AutoSync: "Auto Sync",
AutoSyncDesc: "Automatically syncs changes to Notion when the file's frontmatter or content is modified. Supports creating and updating pages.",
AutoSyncFrontmatterKey: "Auto Sync Frontmatter Key",
AutoSyncFrontmatterKeyDesc: "Specify the frontmatter key used to list the databases this file should auto-sync to (defaults to 'autosync-database').",
AutoSyncDelay: "Auto Sync Delay (seconds)",
AutoSyncDelayDesc: "Delay in seconds to wait before syncing after a change. Prevents excessive syncs (default: 5s, min: 2s).",
AutoSyncDelayText: "Enter delay in seconds",
AutoSyncSuccessNotice: "Auto Sync Success Notice",
AutoSyncSuccessNoticeDesc: "Show a notification when auto-sync succeeds (default: off; failures are still notified).",
NotionGeneralSettingHeader: "General Notion Database Settings",
NotionGeneralButton: "General Database Sync",
NotionGeneralButtonDesc: "Enables the 'Sync to General Database' command in the command palette (default: on).",
NotionTagButton: "Sync Tags",
NotionTagButtonDesc: "Sync Obsidian tags to the Notion database (default: on).",
NotionCustomTitle: "Custom Title Property",
NotionCustomTitleDesc: "Customize the title property's name in your Notion database (default: off).",
NotionCustomTitleName: "Custom Title Property Name",
NotionCustomTitleNameDesc: "Enter the custom name for the title property of your Notion database (default: 'title').",
NotionCustomTitleText: "Enter the property name",
NotionCustomValues: "Custom Properties",
NotionCustomValuesDesc: "Define custom properties to sync to your Notion database, one per line.",
NotionCustomValuesText: "Enter all properties you want to sync",
NotYetFinish: "This feature will be available in a future version.",
PlaceHolder: "Enter database name",
"notion-logo": "Sync to NotionNext",
"sync-preffix": "\u{1F4C4}",
"sync-success": "Successfully synced to NotionNext:\n",
"sync-fail": "Failed to sync to NotionNext:\n",
"open-notion": "Please open a file to sync first.",
"config-secrets-notion-api": "Please configure your Notion API key in the plugin settings.",
"config-secrets-database-id": "Please configure your Database ID in the plugin settings.",
"set-tags-fail": "Failed to set tags. Check the frontmatter or disable tag sync in settings.",
NNonMissing: "The 'NNon' property is not set. Please select a NotionNext database in settings.",
"set-api-id": "Please configure your Notion API key and Database ID in the plugin settings.",
NotionCustomSettingHeader: "Notion Custom Database Settings",
NotionCustomButton: "Enable Custom Database Command",
NotionCustomButtonDesc: "If enabled, the 'Sync to Custom Database' command appears in the command palette.",
CustomPropertyName: "Property Name",
CustomPropertyFirstColumn: "Title Property Name",
CustomPropertyFirstColumnDesc: "The page title. This must be the first property in the list.",
CustomProperty: "Property",
AddCustomProperty: "Add Custom Property",
AddNewProperty: "Add New Property",
AddNewPropertyDesc: "Add a new property that matches a property in your Notion database.",
CopyErrorMessage: "Auto-copy failed. Please copy the link manually.",
BlockUploaded: "All content blocks uploaded successfully.",
ExtraBlockUploaded: "Additional blocks uploaded successfully.",
CheckConsole: "For more details, open the developer console (opt+cmd+i or ctrl+shift+i).",
SettingsMigrated: "\u2728 Settings updated! Auto-Sync is now available. Check the settings to learn more.",
AutoSyncNoNotionID: "\u{1F195} Auto-sync: First upload to Notion",
AutoSyncMissingDatabaseList: "\u26A0\uFE0F Auto-sync skipped: Add `{key}: [database_name]` to your frontmatter to specify target databases.",
AutoSyncSkippedAttachments: "\u26A0\uFE0F Auto-sync skipped: {filename} contains internal attachments (images/PDFs). Please sync manually.",
AutoSyncMultipleSync: "\u{1F504} Auto-sync: Syncing to {count} database(s)...",
AutoSyncFailed: "Auto-sync to {database} failed: {error}",
AutoSyncError: "Auto-sync for {filename} failed: {error}",
"reach-mobile-limit": "Block limit (100) reached. For unlimited blocks, please use the desktop version.",
StartUpload: "Starting upload for {filename}...",
AddNewDatabase: "Add New Database",
AddNewDatabaseDesc: "Add a new database configuration",
AddNewDatabaseTooltip: "Add New Database",
EditDatabase: "Edit Database",
Preview: "Preview",
DatabaseFormatLabel: "Database Format",
DatabaseFullNameLabel: "Database Full Name",
DatabaseAbbreviateNameLabel: "Abbreviated Name",
NotionAPILabel: "Notion API Key",
DatabaseIDLabel: "Database ID",
ToggleAPIKeyVisibility: "Toggle API Key Visibility",
CopyAPIKey: "Copy API Key",
APIKeyCopied: "API key copied to clipboard.",
ToggleDatabaseIDVisibility: "Toggle Database ID Visibility",
CopyDatabaseID: "Copy Database ID",
DatabaseIDCopied: "Database ID copied to clipboard.",
AddNewDatabaseModal: "Add New Database"
};
// src/lang/locale/zh.ts
var zh = {
databaseFormat: "\u6570\u636E\u5E93\u683C\u5F0F",
databaseFormatDesc: "\u9009\u62E9\u540C\u6B65\u7684\u76EE\u6807\u6570\u636E\u5E93\u683C\u5F0F\uFF1ANotionNext \u6216 \u901A\u7528",
databaseNext: "NotionNext",
databaseGeneral: "\u901A\u7528",
databaseCustom: "\u81EA\u5B9A\u4E49",
databaseFullName: "\u6570\u636E\u5E93\u5168\u540D",
databaseFullNameDesc: "\u4E3A\u6570\u636E\u5E93\u8BBE\u7F6E\u4E00\u4E2A\u5168\u540D",
databaseFullNameText: "\u8F93\u5165\u60A8\u7684\u6570\u636E\u5E93\u5168\u540D",
databaseAbbreviateName: "\u6570\u636E\u5E93\u7B80\u79F0",
databaseAbbreviateNameDesc: "\u4E3A\u6570\u636E\u5E93\u8BBE\u7F6E\u4E00\u4E2A\u7B80\u79F0",
databaseAbbreviateNameText: "\u8F93\u5165\u60A8\u7684\u6570\u636E\u5E93\u7B80\u79F0",
ribbonIcon: "\u540C\u6B65\u5230 NotionNext",
GeneralSetting: "\u901A\u7528\u8BBE\u7F6E",
CommandID: "share-to-notionnext",
CommandName: "\u540C\u6B65\u5230 NotionNext",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "\u540C\u6B65\u5230\u901A\u7528\u6570\u636E\u5E93",
NotionNextButton: "NotionNext \u540C\u6B65",
NotionNextButtonDesc: "\u542F\u7528\u540E\uFF0C\u547D\u4EE4\u9762\u677F\u4E2D\u5C06\u663E\u793A\u201C\u540C\u6B65\u5230 NotionNext\u201D\u547D\u4EE4\uFF08\u9ED8\u8BA4\u5F00\u542F\uFF09",
NotionNextSettingHeader: "NotionNext \u6570\u636E\u5E93\u8BBE\u7F6E",
NotionAPI: "Notion API \u4EE4\u724C",
NotionAPIDesc: "\u4ECE notion.so/my-integrations \u83B7\u53D6",
NotionAPIText: "\u8F93\u5165\u60A8\u7684 Notion API \u4EE4\u724C",
DatabaseID: "\u6570\u636E\u5E93 ID",
DatabaseIDDesc: "\u53EF\u4ECE Notion \u9875\u9762\u53F3\u4E0A\u89D2\u7684\u201C\u5206\u4EAB\u201D\u83DC\u5355\u4E2D\u83B7\u53D6",
DatabaseIDText: "\u8F93\u5165\u60A8\u7684\u6570\u636E\u5E93 ID",
BannerUrl: "\u5C01\u9762\u56FE\u7247\u5730\u5740\uFF08\u53EF\u9009\uFF09",
BannerUrlDesc: "\u7559\u7A7A\u5219\u4E0D\u663E\u793A\u3002\u5982\u9700\u5C01\u9762\uFF0C\u8BF7\u8F93\u5165\u56FE\u7247\u5730\u5740\uFF08\u4F8B\u5982\uFF1Ahttps://abc.com/b.png\uFF09",
BannerUrlText: "\u8F93\u5165\u60A8\u7684\u5C01\u9762\u56FE\u7247\u5730\u5740",
NotionUser: "Notion \u7528\u6237\u540D\uFF08\u53EF\u9009\uFF09",
NotionUserDesc: "\u82E5\u5206\u4EAB\u94FE\u63A5\u4E3A username.notion.site\uFF0C\u4F60\u7684 Notion \u7528\u6237\u540D\u5373\u4E3A [username]",
NotionUserText: "\u8F93\u5165\u60A8\u7684 Notion \u7528\u6237\u540D",
NotionLinkDisplay: "\u663E\u793A Notion \u94FE\u63A5",
NotionLinkDisplayDesc: "\u9ED8\u8BA4\u5F00\u542F\u3002\u5173\u95ED\u540E\uFF0C\u540C\u6B65\u6210\u529F\u65F6 frontmatter \u4E2D\u4E0D\u4F1A\u51FA\u73B0 Notion \u94FE\u63A5",
AutoCopyNotionLink: "\u81EA\u52A8\u590D\u5236 Notion \u94FE\u63A5",
AutoCopyNotionLinkDesc: "\u540C\u6B65\u540E\u81EA\u52A8\u5C06 Notion \u94FE\u63A5\u590D\u5236\u5230\u526A\u8D34\u677F\uFF08\u9ED8\u8BA4\u5F00\u542F\uFF09",
AutoSync: "\u81EA\u52A8\u540C\u6B65",
AutoSyncDesc: "\u5F53\u6587\u6863\u7684 frontmatter \u6216\u5185\u5BB9\u4FEE\u6539\u65F6\uFF0C\u5C06\u81EA\u52A8\u540C\u6B65\u5230 Notion\uFF08\u652F\u6301\u65B0\u5EFA\u548C\u66F4\u65B0\uFF09",
AutoSyncFrontmatterKey: "\u81EA\u52A8\u540C\u6B65 Frontmatter \u952E\u540D",
AutoSyncFrontmatterKeyDesc: "\u8BBE\u7F6E\u7528\u4E8E\u6307\u5B9A\u81EA\u52A8\u540C\u6B65\u6570\u636E\u5E93\u5217\u8868\u7684 frontmatter \u952E\u540D\uFF08\u9ED8\u8BA4\u4E3A autosync-database\uFF09\u3002",
AutoSyncDelay: "\u81EA\u52A8\u540C\u6B65\u5EF6\u8FDF\uFF08\u79D2\uFF09",
AutoSyncDelayDesc: "\u6587\u6863\u4FEE\u6539\u540E\uFF0C\u7B49\u5F85\u6307\u5B9A\u79D2\u6570\u518D\u89E6\u53D1\u81EA\u52A8\u540C\u6B65\uFF0C\u4EE5\u907F\u514D\u9891\u7E41\u64CD\u4F5C\uFF08\u9ED8\u8BA4 5 \u79D2\uFF0C\u6700\u5C11 2 \u79D2\uFF09",
AutoSyncDelayText: "\u8F93\u5165\u5EF6\u8FDF\u79D2\u6570",
AutoSyncSuccessNotice: "\u81EA\u52A8\u540C\u6B65\u6210\u529F\u901A\u77E5",
AutoSyncSuccessNoticeDesc: "\u662F\u5426\u5728\u81EA\u52A8\u540C\u6B65\u6210\u529F\u540E\u5F39\u51FA\u901A\u77E5\uFF08\u9ED8\u8BA4\u5173\u95ED\uFF0C\u4EC5\u5728\u5931\u8D25\u65F6\u901A\u77E5\uFF09",
NotionGeneralSettingHeader: "\u901A\u7528 Notion \u6570\u636E\u5E93\u8BBE\u7F6E",
NotionGeneralButton: "\u901A\u7528\u6570\u636E\u5E93\u540C\u6B65",
NotionGeneralButtonDesc: "\u542F\u7528\u540E\uFF0C\u547D\u4EE4\u9762\u677F\u4E2D\u5C06\u663E\u793A\u201C\u540C\u6B65\u5230\u901A\u7528\u6570\u636E\u5E93\u201D\u547D\u4EE4\uFF08\u9ED8\u8BA4\u5F00\u542F\uFF09",
NotionTagButton: "\u6807\u7B7E\u540C\u6B65",
NotionTagButtonDesc: "\u5C06 Obsidian \u6807\u7B7E\u540C\u6B65\u5230 Notion \u6570\u636E\u5E93\uFF08\u9ED8\u8BA4\u5F00\u542F\uFF09",
NotionCustomTitle: "\u81EA\u5B9A\u4E49\u6807\u9898\u5C5E\u6027",
NotionCustomTitleDesc: "\u81EA\u5B9A\u4E49 Notion \u6570\u636E\u5E93\u4E2D\u6807\u9898\u5217\u7684\u540D\u79F0\uFF08\u9ED8\u8BA4\u5173\u95ED\uFF09",
NotionCustomTitleName: "\u81EA\u5B9A\u4E49\u6807\u9898\u540D\u79F0",
NotionCustomTitleNameDesc: "\u4E3A Notion \u6570\u636E\u5E93\u7684\u6807\u9898\u5217\u8BBE\u7F6E\u4E00\u4E2A\u81EA\u5B9A\u4E49\u540D\u79F0\uFF08\u9ED8\u8BA4\u4E3A title\uFF09",
NotionCustomTitleText: "\u8F93\u5165\u6807\u9898\u540D\u79F0",
NotionCustomValues: "\u81EA\u5B9A\u4E49\u5C5E\u6027",
NotionCustomValuesDesc: "\u81EA\u5B9A\u4E49\u540C\u6B65\u5230 Notion \u6570\u636E\u5E93\u7684\u5C5E\u6027\uFF0C\u6BCF\u884C\u4E00\u4E2A\u3002",
NotionCustomValuesText: "\u8F93\u5165\u6240\u6709\u4F60\u5E0C\u671B\u540C\u6B65\u7684\u5C5E\u6027",
NotYetFinish: "\u6B64\u529F\u80FD\u5C06\u5728\u672A\u6765\u7248\u672C\u4E2D\u63D0\u4F9B",
PlaceHolder: "\u8F93\u5165\u6570\u636E\u5E93\u540D\u79F0",
"notion-logo": "\u540C\u6B65\u5230 NotionNext",
"sync-preffix": "\u{1F4C4}",
"sync-success": "\u6210\u529F\u540C\u6B65\u5230 NotionNext\uFF1A\n",
"sync-fail": "\u540C\u6B65\u5230 NotionNext \u5931\u8D25\uFF1A\n",
"open-file": "\u8BF7\u5148\u6253\u5F00\u8981\u540C\u6B65\u7684\u6587\u4EF6\u3002",
"config-secrets-notion-api": "\u8BF7\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u914D\u7F6E Notion API \u5BC6\u94A5\u3002",
"config-secrets-database-id": "\u8BF7\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u914D\u7F6E\u6570\u636E\u5E93 ID\u3002",
"set-tags-fail": "\u6807\u7B7E\u8BBE\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 frontmatter \u6216\u5728\u8BBE\u7F6E\u4E2D\u5173\u95ED\u6807\u7B7E\u540C\u6B65\u3002",
NNonMissing: "\u672A\u8BBE\u7F6E 'NNon' \u5C5E\u6027\uFF0C\u8BF7\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u9009\u62E9\u4E00\u4E2A NotionNext \u6570\u636E\u5E93\u3002",
"set-api-id": "\u8BF7\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u914D\u7F6E Notion API \u548C\u6570\u636E\u5E93 ID\u3002",
NotionCustomSettingHeader: "Notion \u81EA\u5B9A\u4E49\u6570\u636E\u5E93\u8BBE\u7F6E",
NotionCustomButton: "\u542F\u7528\u81EA\u5B9A\u4E49\u6570\u636E\u5E93\u540C\u6B65\u547D\u4EE4",
NotionCustomButtonDesc: "\u542F\u7528\u540E\uFF0C\u201C\u540C\u6B65\u5230\u81EA\u5B9A\u4E49\u6570\u636E\u5E93\u201D\u7684\u547D\u4EE4\u5C06\u51FA\u73B0\u5728\u547D\u4EE4\u9762\u677F\u4E2D\u3002",
CustomPropertyName: "\u81EA\u5B9A\u4E49\u5C5E\u6027\u540D",
CustomPropertyFirstColumn: "\u6807\u9898\u5C5E\u6027",
CustomPropertyFirstColumnDesc: "\u7B2C\u4E00\u5217\u5FC5\u987B\u4E3A\u6807\u9898\u5C5E\u6027\u3002",
CustomProperty: "\u81EA\u5B9A\u4E49\u5C5E\u6027",
AddCustomProperty: "\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5C5E\u6027",
AddNewProperty: "\u6DFB\u52A0\u65B0\u5C5E\u6027",
AddNewPropertyDesc: "\u6DFB\u52A0\u4E00\u4E2A\u4E0E\u60A8 Notion \u6570\u636E\u5E93\u4E2D\u7684\u5C5E\u6027\u76F8\u5339\u914D\u7684\u65B0\u5C5E\u6027\u3002",
CopyErrorMessage: "\u81EA\u52A8\u590D\u5236\u94FE\u63A5\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u3002",
BlockUploaded: "\u6240\u6709\u5757\u5DF2\u4E0A\u4F20\u6210\u529F",
ExtraBlockUploaded: "\u989D\u5916\u5757\u5DF2\u4E0A\u4F20\u6210\u529F",
CheckConsole: "\u6309 opt+cmd+i / ctrl+shift+i \u6253\u5F00\u63A7\u5236\u53F0\u67E5\u770B\u8BE6\u60C5\u3002",
SettingsMigrated: "\u2728 \u63D2\u4EF6\u8BBE\u7F6E\u5DF2\u66F4\u65B0\uFF01\u65B0\u589E\u81EA\u52A8\u540C\u6B65\u529F\u80FD\uFF0C\u8BE6\u60C5\u8BF7\u67E5\u770B\u8BBE\u7F6E\u3002",
AutoSyncNoNotionID: "\u{1F195} \u81EA\u52A8\u540C\u6B65\uFF1A\u9996\u6B21\u4E0A\u4F20\u5230 Notion",
AutoSyncMissingDatabaseList: '\u26A0\uFE0F \u81EA\u52A8\u540C\u6B65\u5DF2\u8DF3\u8FC7\uFF1A\u8BF7\u5728 frontmatter \u4E2D\u6DFB\u52A0 "{key}" \u4EE5\u6307\u5B9A\u76EE\u6807\u6570\u636E\u5E93\u3002',
AutoSyncSkippedAttachments: "\u26A0\uFE0F \u81EA\u52A8\u540C\u6B65\u5DF2\u8DF3\u8FC7\uFF1A\u68C0\u6D4B\u5230 {filename} \u542B\u6709\u672C\u5730\u9644\u4EF6\uFF08\u56FE\u7247/PDF\uFF09\uFF0C\u8BF7\u624B\u52A8\u540C\u6B65\u3002",
AutoSyncMultipleSync: "\u{1F504} \u81EA\u52A8\u540C\u6B65\uFF1A\u6B63\u5728\u540C\u6B65\u5230 {count} \u4E2A\u6570\u636E\u5E93...",
AutoSyncFailed: "\u540C\u6B65\u5230 {database} \u5931\u8D25\uFF1A{error}",
AutoSyncError: "\u540C\u6B65 {filename} \u5931\u8D25\uFF1A{error}",
StartUpload: "\u5F00\u59CB\u4E0A\u4F20 {filename}...",
AddNewDatabase: "\u6DFB\u52A0\u65B0\u6570\u636E\u5E93",
AddNewDatabaseDesc: "\u6DFB\u52A0\u65B0\u7684\u6570\u636E\u5E93\u914D\u7F6E",
AddNewDatabaseTooltip: "\u6DFB\u52A0\u65B0\u6570\u636E\u5E93",
EditDatabase: "\u7F16\u8F91\u6570\u636E\u5E93",
Preview: "\u9884\u89C8",
DatabaseFormatLabel: "\u6570\u636E\u5E93\u683C\u5F0F",
DatabaseFullNameLabel: "\u6570\u636E\u5E93\u5168\u540D",
DatabaseAbbreviateNameLabel: "\u6570\u636E\u5E93\u7B80\u79F0",
NotionAPILabel: "Notion API \u5BC6\u94A5",
DatabaseIDLabel: "\u6570\u636E\u5E93 ID",
ToggleAPIKeyVisibility: "\u5207\u6362 API \u5BC6\u94A5\u53EF\u89C1\u6027",
CopyAPIKey: "\u590D\u5236 API \u5BC6\u94A5",
APIKeyCopied: "API \u5BC6\u94A5\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\u3002",
ToggleDatabaseIDVisibility: "\u5207\u6362\u6570\u636E\u5E93 ID \u53EF\u89C1\u6027",
CopyDatabaseID: "\u590D\u5236\u6570\u636E\u5E93 ID",
DatabaseIDCopied: "\u6570\u636E\u5E93 ID \u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\u3002",
AddNewDatabaseModal: "\u6DFB\u52A0\u65B0\u6570\u636E\u5E93"
};
// src/lang/locale/ja.ts
var ja = {
databaseFormat: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u5F62\u5F0F",
databaseFormatDesc: "\u540C\u671F\u5148\u306E\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u5F62\u5F0F\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\uFF08NotionNext \u307E\u305F\u306F \u4E00\u822C\uFF09\u3002",
databaseNext: "NotionNext",
databaseGeneral: "\u4E00\u822C",
databaseCustom: "\u30AB\u30B9\u30BF\u30E0",
databaseFullName: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u5168\u79F0",
databaseFullNameDesc: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u30D5\u30EB\u30CD\u30FC\u30E0\u3092\u8A2D\u5B9A\u3057\u307E\u3059\u3002",
databaseFullNameText: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u5168\u79F0\u3092\u5165\u529B",
databaseAbbreviateName: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u7565\u79F0",
databaseAbbreviateNameDesc: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u7565\u79F0\u3092\u8A2D\u5B9A\u3057\u307E\u3059\u3002",
databaseAbbreviateNameText: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u7565\u79F0\u3092\u5165\u529B",
ribbonIcon: "NotionNext\u3078\u540C\u671F",
GeneralSetting: "\u4E00\u822C\u8A2D\u5B9A",
CommandID: "share-to-notionnext",
CommandName: "NotionNext\u3078\u540C\u671F",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "\u4E00\u822C\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3078\u540C\u671F",
NotionNextButton: "NotionNext\u540C\u671F",
NotionNextButtonDesc: "\u6709\u52B9\u306B\u3059\u308B\u3068\u3001\u30B3\u30DE\u30F3\u30C9\u30D1\u30EC\u30C3\u30C8\u306B\u300CNotionNext\u3078\u540C\u671F\u300D\u304C\u8868\u793A\u3055\u308C\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A\u30AA\u30F3\uFF09\u3002",
NotionNextSettingHeader: "NotionNext\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u8A2D\u5B9A",
NotionAPI: "Notion API \u30C8\u30FC\u30AF\u30F3",
NotionAPIDesc: "notion.so/my-integrations \u304B\u3089\u53D6\u5F97\u3057\u307E\u3059\u3002",
NotionAPIText: "Notion API \u30C8\u30FC\u30AF\u30F3\u3092\u5165\u529B",
DatabaseID: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9ID",
DatabaseIDDesc: "Notion\u30DA\u30FC\u30B8\u306E\u53F3\u4E0A\u300C\u5171\u6709\u300D\u30E1\u30CB\u30E5\u30FC\u304B\u3089\u53D6\u5F97\u3057\u307E\u3059\u3002",
DatabaseIDText: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9ID\u3092\u5165\u529B",
BannerUrl: "\u30D0\u30CA\u30FCURL\uFF08\u4EFB\u610F\uFF09",
BannerUrlDesc: "\u7A7A\u306E\u307E\u307E\u306B\u3059\u308B\u3068\u30D0\u30CA\u30FC\u306F\u8868\u793A\u3055\u308C\u307E\u305B\u3093\u3002\u8868\u793A\u3059\u308B\u306B\u306F\u753B\u50CF\u306EURL\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u4F8B\uFF1Ahttps://abc.com/b.png\uFF09\u3002",
BannerUrlText: "\u30D0\u30CA\u30FC\u306EURL\u3092\u5165\u529B",
NotionUser: "Notion\u30E6\u30FC\u30B6\u30FC\u540D\uFF08\u4EFB\u610F\uFF09",
NotionUserDesc: "\u5171\u6709\u30EA\u30F3\u30AF\u304C `username.notion.site` \u306E\u5834\u5408\u3001Notion\u30E6\u30FC\u30B6\u30FC\u540D\u306F `[username]` \u3067\u3059\u3002",
NotionUserText: "Notion\u30E6\u30FC\u30B6\u30FC\u540D\u3092\u5165\u529B",
NotionLinkDisplay: "Notion\u30EA\u30F3\u30AF\u8868\u793A",
NotionLinkDisplayDesc: "\u30C7\u30D5\u30A9\u30EB\u30C8\u3067\u6709\u52B9\u3002\u7121\u52B9\u306B\u3059\u308B\u3068\u3001\u540C\u671F\u5F8C\u306Bfront matter\u3078Notion\u30EA\u30F3\u30AF\u304C\u8FFD\u52A0\u3055\u308C\u307E\u305B\u3093\u3002",
AutoCopyNotionLink: "Notion\u30EA\u30F3\u30AF\u3092\u81EA\u52D5\u30B3\u30D4\u30FC",
AutoCopyNotionLinkDesc: "\u540C\u671F\u5B8C\u4E86\u5F8C\u3001Notion\u30DA\u30FC\u30B8\u306E\u30EA\u30F3\u30AF\u3092\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u306B\u81EA\u52D5\u30B3\u30D4\u30FC\u3057\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A\u30AA\u30F3\uFF09\u3002",
AutoSync: "\u81EA\u52D5\u540C\u671F",
AutoSyncDesc: "\u30D5\u30A1\u30A4\u30EB\u306E\u5185\u5BB9\uFF08frontmatter\u307E\u305F\u306F\u672C\u6587\uFF09\u304C\u5909\u66F4\u3055\u308C\u308B\u3068\u3001\u81EA\u52D5\u3067Notion\u306B\u540C\u671F\u3057\u307E\u3059\u3002\u65B0\u898F\u4F5C\u6210\u3068\u66F4\u65B0\u306E\u4E21\u65B9\u306B\u5BFE\u5FDC\u3002",
AutoSyncFrontmatterKey: "\u81EA\u52D5\u540C\u671F frontmatter \u30AD\u30FC",
AutoSyncFrontmatterKeyDesc: "\u81EA\u52D5\u540C\u671F\u306E\u5BFE\u8C61\u3068\u306A\u308B\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3092\u30EA\u30B9\u30C8\u30A2\u30C3\u30D7\u3059\u308B\u305F\u3081\u306E frontmatter\u30AD\u30FC\u3092\u8A2D\u5B9A\u3057\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1Aautosync-database\uFF09\u3002",
AutoSyncDelay: "\u81EA\u52D5\u540C\u671F\u306E\u9045\u5EF6\uFF08\u79D2\uFF09",
AutoSyncDelayDesc: "\u5909\u66F4\u304C\u691C\u77E5\u3055\u308C\u3066\u304B\u3089\u540C\u671F\u3092\u958B\u59CB\u3059\u308B\u307E\u3067\u306E\u9045\u5EF6\u6642\u9593\uFF08\u79D2\uFF09\u3002\u540C\u671F\u306E\u983B\u767A\u3092\u9632\u304E\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A5\u79D2\u3001\u6700\u5C0F\uFF1A2\u79D2\uFF09\u3002",
AutoSyncDelayText: "\u9045\u5EF6\u79D2\u6570\u3092\u5165\u529B",
AutoSyncSuccessNotice: "\u81EA\u52D5\u540C\u671F\u6210\u529F\u901A\u77E5",
AutoSyncSuccessNoticeDesc: "\u81EA\u52D5\u540C\u671F\u304C\u6210\u529F\u3057\u305F\u3068\u304D\u306B\u901A\u77E5\u3092\u8868\u793A\u3057\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A\u30AA\u30D5\u3002\u5931\u6557\u6642\u306F\u901A\u77E5\u3055\u308C\u307E\u3059\uFF09\u3002",
NotionGeneralSettingHeader: "\u4E00\u822CNotion\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u8A2D\u5B9A",
NotionGeneralButton: "\u4E00\u822C\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u540C\u671F",
NotionGeneralButtonDesc: "\u6709\u52B9\u306B\u3059\u308B\u3068\u3001\u30B3\u30DE\u30F3\u30C9\u30D1\u30EC\u30C3\u30C8\u306B\u300C\u4E00\u822C\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3078\u540C\u671F\u300D\u304C\u8868\u793A\u3055\u308C\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A\u30AA\u30F3\uFF09\u3002",
NotionTagButton: "\u30BF\u30B0\u3092\u540C\u671F",
NotionTagButtonDesc: "Obsidian\u306E\u30BF\u30B0\u3092Notion\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306B\u540C\u671F\u3057\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A\u30AA\u30F3\uFF09\u3002",
NotionCustomTitle: "\u30BF\u30A4\u30C8\u30EB\u30D7\u30ED\u30D1\u30C6\u30A3\u3092\u30AB\u30B9\u30BF\u30E0",
NotionCustomTitleDesc: "Notion\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u30BF\u30A4\u30C8\u30EB\u5217\u306E\u540D\u524D\u3092\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA\u3057\u307E\u3059\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A\u30AA\u30D5\uFF09\u3002",
NotionCustomTitleName: "\u30AB\u30B9\u30BF\u30E0\u30BF\u30A4\u30C8\u30EB\u540D",
NotionCustomTitleNameDesc: "Notion\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u30BF\u30A4\u30C8\u30EB\u5217\u306B\u4F7F\u7528\u3059\u308B\u30AB\u30B9\u30BF\u30E0\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF1A\u300Ctitle\u300D\uFF09\u3002",
NotionCustomTitleText: "\u30D7\u30ED\u30D1\u30C6\u30A3\u540D\u3092\u5165\u529B",
NotionCustomValues: "\u30AB\u30B9\u30BF\u30E0\u30D7\u30ED\u30D1\u30C6\u30A3",
NotionCustomValuesDesc: "Notion\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306B\u540C\u671F\u3059\u308B\u30AB\u30B9\u30BF\u30E0\u30D7\u30ED\u30D1\u30C6\u30A3\u30921\u884C\u306B1\u3064\u305A\u3064\u5B9A\u7FA9\u3057\u307E\u3059\u3002",
NotionCustomValuesText: "\u540C\u671F\u3057\u305F\u3044\u3059\u3079\u3066\u306E\u30D7\u30ED\u30D1\u30C6\u30A3\u3092\u5165\u529B",
NotYetFinish: "\u3053\u306E\u6A5F\u80FD\u306F\u5C06\u6765\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u3067\u5229\u7528\u53EF\u80FD\u306B\u306A\u308A\u307E\u3059\u3002",
PlaceHolder: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u540D\u3092\u5165\u529B",
"notion-logo": "NotionNext\u3078\u540C\u671F",
"sync-preffix": "\u{1F4C4}",
"sync-success": "NotionNext\u3078\u306E\u540C\u671F\u304C\u6210\u529F\u3057\u307E\u3057\u305F\u3002\n",
"sync-fail": "NotionNext\u3078\u306E\u540C\u671F\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002\n",
"open-notion": "\u540C\u671F\u3059\u308B\u30D5\u30A1\u30A4\u30EB\u3092\u5148\u306B\u958B\u3044\u3066\u304F\u3060\u3055\u3044\u3002",
"config-secrets-notion-api": "\u30D7\u30E9\u30B0\u30A4\u30F3\u8A2D\u5B9A\u3067Notion API\u30AD\u30FC\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
"config-secrets-database-id": "\u30D7\u30E9\u30B0\u30A4\u30F3\u8A2D\u5B9A\u3067\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9ID\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
"set-tags-fail": "\u30BF\u30B0\u306E\u8A2D\u5B9A\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002frontmatter\u3092\u78BA\u8A8D\u3059\u308B\u304B\u3001\u8A2D\u5B9A\u3067\u30BF\u30B0\u540C\u671F\u3092\u7121\u52B9\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
NNonMissing: "'NNon'\u30D7\u30ED\u30D1\u30C6\u30A3\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u8A2D\u5B9A\u3067NotionNext\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
"set-api-id": "\u30D7\u30E9\u30B0\u30A4\u30F3\u8A2D\u5B9A\u3067Notion API\u30AD\u30FC\u3068\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9ID\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
NotionCustomSettingHeader: "Notion\u30AB\u30B9\u30BF\u30E0\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u8A2D\u5B9A",
NotionCustomButton: "\u30AB\u30B9\u30BF\u30E0\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u30B3\u30DE\u30F3\u30C9\u3092\u6709\u52B9\u5316",
NotionCustomButtonDesc: "\u6709\u52B9\u306B\u3059\u308B\u3068\u3001\u300C\u30AB\u30B9\u30BF\u30E0\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3078\u540C\u671F\u300D\u30B3\u30DE\u30F3\u30C9\u304C\u30B3\u30DE\u30F3\u30C9\u30D1\u30EC\u30C3\u30C8\u306B\u8868\u793A\u3055\u308C\u307E\u3059\u3002",
CustomPropertyName: "\u30D7\u30ED\u30D1\u30C6\u30A3\u540D",
CustomPropertyFirstColumn: "\u30BF\u30A4\u30C8\u30EB\u30D7\u30ED\u30D1\u30C6\u30A3\u540D",
CustomPropertyFirstColumnDesc: "\u30DA\u30FC\u30B8\u306E\u30BF\u30A4\u30C8\u30EB\u3002\u3053\u308C\u306F\u30EA\u30B9\u30C8\u306E\u6700\u521D\u306E\u30D7\u30ED\u30D1\u30C6\u30A3\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002",
CustomProperty: "\u30D7\u30ED\u30D1\u30C6\u30A3",
AddCustomProperty: "\u30AB\u30B9\u30BF\u30E0\u30D7\u30ED\u30D1\u30C6\u30A3\u3092\u8FFD\u52A0",
AddNewProperty: "\u65B0\u3057\u3044\u30D7\u30ED\u30D1\u30C6\u30A3\u3092\u8FFD\u52A0",
AddNewPropertyDesc: "Notion\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u30D7\u30ED\u30D1\u30C6\u30A3\u3068\u4E00\u81F4\u3059\u308B\u65B0\u3057\u3044\u30D7\u30ED\u30D1\u30C6\u30A3\u3092\u8FFD\u52A0\u3057\u307E\u3059\u3002",
CopyErrorMessage: "\u30EA\u30F3\u30AF\u306E\u81EA\u52D5\u30B3\u30D4\u30FC\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002\u624B\u52D5\u3067\u30B3\u30D4\u30FC\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
BlockUploaded: "\u3059\u3079\u3066\u306E\u30D6\u30ED\u30C3\u30AF\u3092\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3057\u307E\u3057\u305F",
ExtraBlockUploaded: "\u8FFD\u52A0\u306E\u30D6\u30ED\u30C3\u30AF\u3092\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3057\u307E\u3057\u305F",
CheckConsole: "\u8A73\u7D30\u306F\u3001\u958B\u767A\u8005\u30B3\u30F3\u30BD\u30FC\u30EB\uFF08opt+cmd+i \u307E\u305F\u306F ctrl+shift+i\uFF09\u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059\u3002",
SettingsMigrated: "\u2728 \u8A2D\u5B9A\u304C\u66F4\u65B0\u3055\u308C\u307E\u3057\u305F\uFF01\u81EA\u52D5\u540C\u671F\u304C\u5229\u7528\u53EF\u80FD\u3067\u3059\u3002\u8A73\u7D30\u306F\u8A2D\u5B9A\u753B\u9762\u3092\u3054\u78BA\u8A8D\u304F\u3060\u3055\u3044\u3002",
AutoSyncNoNotionID: "\u{1F195} \u81EA\u52D5\u540C\u671F\uFF1ANotion\u3078\u521D\u3081\u3066\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3057\u307E\u3059",
AutoSyncMissingDatabaseList: "\u26A0\uFE0F \u81EA\u52D5\u540C\u671F\u3092\u30B9\u30AD\u30C3\u30D7\uFF1Afrontmatter\u306B `{key}: [\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u540D]` \u3092\u8FFD\u52A0\u3057\u3066\u540C\u671F\u5148\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
AutoSyncSkippedAttachments: "\u26A0\uFE0F \u81EA\u52D5\u540C\u671F\u3092\u30B9\u30AD\u30C3\u30D7\uFF1A{filename} \u306B\u5185\u90E8\u6DFB\u4ED8\uFF08\u753B\u50CF/PDF\uFF09\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002\u624B\u52D5\u3067\u540C\u671F\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
AutoSyncMultipleSync: "\u{1F504} \u81EA\u52D5\u540C\u671F\uFF1A{count}\u500B\u306E\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306B\u540C\u671F\u3057\u3066\u3044\u307E\u3059...",
AutoSyncFailed: "{database}\u3078\u306E\u81EA\u52D5\u540C\u671F\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF1A{error}",
AutoSyncError: "{filename}\u306E\u81EA\u52D5\u540C\u671F\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF1A{error}",
"reach-mobile-limit": "\u30D6\u30ED\u30C3\u30AF\u4E0A\u9650\uFF08100\uFF09\u306B\u9054\u3057\u307E\u3057\u305F\u3002\u30D6\u30ED\u30C3\u30AF\u6570\u306B\u5236\u9650\u306E\u306A\u3044\u30C7\u30B9\u30AF\u30C8\u30C3\u30D7\u7248\u3092\u3054\u5229\u7528\u304F\u3060\u3055\u3044\u3002",
StartUpload: "{filename} \u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3092\u958B\u59CB\u3057\u307E\u3059...",
AddNewDatabase: "\u65B0\u3057\u3044\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3092\u8FFD\u52A0",
AddNewDatabaseDesc: "\u65B0\u3057\u3044\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u69CB\u6210\u3092\u8FFD\u52A0",
AddNewDatabaseTooltip: "\u65B0\u3057\u3044\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3092\u8FFD\u52A0",
EditDatabase: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3092\u7DE8\u96C6",
Preview: "\u30D7\u30EC\u30D3\u30E5\u30FC",
DatabaseFormatLabel: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u5F62\u5F0F",
DatabaseFullNameLabel: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u5168\u79F0",
DatabaseAbbreviateNameLabel: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u306E\u7565\u79F0",
NotionAPILabel: "Notion API \u30AD\u30FC",
DatabaseIDLabel: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9 ID",
ToggleAPIKeyVisibility: "API \u30AD\u30FC\u306E\u8868\u793A\u3092\u5207\u308A\u66FF\u3048",
CopyAPIKey: "API \u30AD\u30FC\u3092\u30B3\u30D4\u30FC",
APIKeyCopied: "API\u30AD\u30FC\u3092\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u306B\u30B3\u30D4\u30FC\u3057\u307E\u3057\u305F\u3002",
ToggleDatabaseIDVisibility: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9 ID \u306E\u8868\u793A\u3092\u5207\u308A\u66FF\u3048",
CopyDatabaseID: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9 ID \u3092\u30B3\u30D4\u30FC",
DatabaseIDCopied: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9ID\u3092\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u306B\u30B3\u30D4\u30FC\u3057\u307E\u3057\u305F\u3002",
AddNewDatabaseModal: "\u65B0\u3057\u3044\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u3092\u8FFD\u52A0"
};
// src/lang/I18n.ts
var I18n = {
en,
zh,
ja
};
var I18nManager = class {
constructor() {
this.currentLanguage = this.detectLanguage();
}
// return the language to use
detectLanguage() {
const storedLanguage = window.localStorage.getItem("language");
if (storedLanguage && this.isLanguageSupported(storedLanguage)) {
console.log(`Using stored language: ${storedLanguage}`);
return storedLanguage;
}
const browserLanguage = window.navigator.language.split("-")[0];
if (this.isLanguageSupported(browserLanguage)) {
console.log(`Using browser language: ${browserLanguage}`);
return browserLanguage;
}
console.log("Using default language: en");
return "en";
}
isLanguageSupported(lang) {
return Object.prototype.hasOwnProperty.call(I18n, lang);
}
// Get the i18n configuration for the current language
getConfig() {
return I18n[this.currentLanguage];
}
};
var i18nManager = new I18nManager();
var i18nConfig = i18nManager.getConfig();
// src/commands/FuzzySuggester.ts
var import_obsidian2 = require("obsidian");
var FuzzySuggester = class extends import_obsidian2.FuzzySuggestModal {
constructor(plugin) {
super(plugin.app);
this.plugin = plugin;
this.setPlaceholder(i18nConfig.PlaceHolder);
}
setSuggesterData(suggesterData) {
this.data = suggesterData;
}
display(callBack) {
return __async(this, null, function* () {
this.callback = callBack;
this.open();
});
}
// Store the data
getItems() {
return this.data;
}
getItemText(item) {
return item.name;
}
onChooseItem(item, evt) {
}
onChooseSuggestion(item, evt) {
this.callback(item.item, evt);
}
renderSuggestion(item, el) {
el.createEl("div", { text: item.item.name });
}
};
// src/upload/uploadCommand.ts
var import_obsidian10 = require("obsidian");
// node_modules/bail/index.js
function bail(error) {
if (error) {
throw error;
}
}
// node_modules/unified/lib/index.js
var import_extend = __toESM(require_extend(), 1);
// node_modules/devlop/lib/default.js
function ok() {
}
// node_modules/is-plain-obj/index.js
function isPlainObject(value) {
if (typeof value !== "object" || value === null) {
return false;
}
const prototype = Object.getPrototypeOf(value);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}
// node_modules/trough/lib/index.js
function trough() {
const fns = [];
const pipeline = { run, use };
return pipeline;
function run(...values) {
let middlewareIndex = -1;
const callback = values.pop();
if (typeof callback !== "function") {
throw new TypeError("Expected function as last argument, not " + callback);
}
next(null, ...values);
function next(error, ...output) {
const fn = fns[++middlewareIndex];
let index2 = -1;
if (error) {
callback(error);
return;
}
while (++index2 < values.length) {
if (output[index2] === null || output[index2] === void 0) {
output[index2] = values[index2];
}
}
values = output;
if (fn) {
wrap(fn, next)(...output);
} else {
callback(null, ...output);
}
}
}
function use(middelware) {
if (typeof middelware !== "function") {
throw new TypeError(
"Expected `middelware` to be a function, not " + middelware
);
}
fns.push(middelware);
return pipeline;
}
}
function wrap(middleware, callback) {
let called;
return wrapped;
function wrapped(...parameters) {
const fnExpectsCallback = middleware.length > parameters.length;
let result;
if (fnExpectsCallback) {
parameters.push(done);
}
try {
result = middleware.apply(this, parameters);
} catch (error) {
const exception = (
/** @type {Error} */
error
);
if (fnExpectsCallback && called) {
throw exception;
}
return done(exception);
}
if (!fnExpectsCallback) {
if (result && result.then && typeof result.then === "function") {
result.then(then, done);
} else if (result instanceof Error) {
done(result);
} else {
then(result);
}
}
}
function done(error, ...output) {
if (!called) {
called = true;
callback(error, ...output);
}
}
function then(value) {
done(null, value);
}
}
// node_modules/unist-util-stringify-position/lib/index.js
function stringifyPosition(value) {
if (!value || typeof value !== "object") {
return "";
}
if ("position" in value || "type" in value) {
return position(value.position);
}
if ("start" in value || "end" in value) {
return position(value);
}
if ("line" in value || "column" in value) {
return point(value);
}
return "";
}
function point(point3) {
return index(point3 && point3.line) + ":" + index(point3 && point3.column);
}
function position(pos) {
return point(pos && pos.start) + "-" + point(pos && pos.end);
}
function index(value) {
return value && typeof value === "number" ? value : 1;
}
// node_modules/vfile-message/lib/index.js
var VFileMessage = class extends Error {
/**
* Create a message for `reason`.
*
* > 🪦 **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {Options | null | undefined} [options]
* @returns
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* `'my-package:my-rule'` or `'my-rule'`).
* @returns
* Instance of `VFileMessage`.
*/
// eslint-disable-next-line complexity
constructor(causeOrReason, optionsOrParentOrPlace, origin) {
super();
if (typeof optionsOrParentOrPlace === "string") {
origin = optionsOrParentOrPlace;
optionsOrParentOrPlace = void 0;
}
let reason = "";
let options = {};
let legacyCause = false;
if (optionsOrParentOrPlace) {
if ("line" in optionsOrParentOrPlace && "column" in optionsOrParentOrPlace) {
options = { place: optionsOrParentOrPlace };
} else if ("start" in optionsOrParentOrPlace && "end" in optionsOrParentOrPlace) {
options = { place: optionsOrParentOrPlace };
} else if ("type" in optionsOrParentOrPlace) {
options = {
ancestors: [optionsOrParentOrPlace],
place: optionsOrParentOrPlace.position
};
} else {
options = __spreadValues({}, optionsOrParentOrPlace);
}
}
if (typeof causeOrReason === "string") {
reason = causeOrReason;
} else if (!options.cause && causeOrReason) {
legacyCause = true;
reason = causeOrReason.message;
options.cause = causeOrReason;
}
if (!options.ruleId && !options.source && typeof origin === "string") {
const index2 = origin.indexOf(":");
if (index2 === -1) {
options.ruleId = origin;
} else {
options.source = origin.slice(0, index2);
options.ruleId = origin.slice(index2 + 1);
}
}
if (!options.place && options.ancestors && options.ancestors) {
const parent = options.ancestors[options.ancestors.length - 1];
if (parent) {
options.place = parent.position;
}
}
const start = options.place && "start" in options.place ? options.place.start : options.place;
this.ancestors = options.ancestors || void 0;
this.cause = options.cause || void 0;
this.column = start ? start.column : void 0;
this.fatal = void 0;
this.file = "";
this.message = reason;
this.line = start ? start.line : void 0;
this.name = stringifyPosition(options.place) || "1:1";
this.place = options.place || void 0;
this.reason = this.message;
this.ruleId = options.ruleId || void 0;
this.source = options.source || void 0;
this.stack = legacyCause && options.cause && typeof options.cause.stack === "string" ? options.cause.stack : "";
this.actual = void 0;
this.expected = void 0;
this.note = void 0;
this.url = void 0;
}
};
VFileMessage.prototype.file = "";
VFileMessage.prototype.name = "";
VFileMessage.prototype.reason = "";
VFileMessage.prototype.message = "";
VFileMessage.prototype.stack = "";
VFileMessage.prototype.column = void 0;
VFileMessage.prototype.line = void 0;
VFileMessage.prototype.ancestors = void 0;
VFileMessage.prototype.cause = void 0;
VFileMessage.prototype.fatal = void 0;
VFileMessage.prototype.place = void 0;
VFileMessage.prototype.ruleId = void 0;
VFileMessage.prototype.source = void 0;
// node_modules/vfile/lib/minpath.browser.js
var minpath = { basename, dirname, extname, join, sep: "/" };
function basename(path3, extname2) {
if (extname2 !== void 0 && typeof extname2 !== "string") {
throw new TypeError('"ext" argument must be a string');
}
assertPath(path3);
let start = 0;
let end = -1;
let index2 = path3.length;
let seenNonSlash;
if (extname2 === void 0 || extname2.length === 0 || extname2.length > path3.length) {
while (index2--) {
if (path3.codePointAt(index2) === 47) {
if (seenNonSlash) {
start = index2 + 1;
break;
}
} else if (end < 0) {
seenNonSlash = true;
end = index2 + 1;
}
}
return end < 0 ? "" : path3.slice(start, end);
}
if (extname2 === path3) {
return "";
}
let firstNonSlashEnd = -1;
let extnameIndex = extname2.length - 1;
while (index2--) {
if (path3.codePointAt(index2) === 47) {
if (seenNonSlash) {
start = index2 + 1;
break;
}
} else {
if (firstNonSlashEnd < 0) {
seenNonSlash = true;
firstNonSlashEnd = index2 + 1;
}
if (extnameIndex > -1) {
if (path3.codePointAt(index2) === extname2.codePointAt(extnameIndex--)) {
if (extnameIndex < 0) {
end = index2;
}
} else {
extnameIndex = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) {
end = firstNonSlashEnd;
} else if (end < 0) {
end = path3.length;
}
return path3.slice(start, end);
}
function dirname(path3) {
assertPath(path3);
if (path3.length === 0) {
return ".";
}
let end = -1;
let index2 = path3.length;
let unmatchedSlash;
while (--index2) {
if (path3.codePointAt(index2) === 47) {
if (unmatchedSlash) {
end = index2;
break;
}
} else if (!unmatchedSlash) {
unmatchedSlash = true;
}
}
return end < 0 ? path3.codePointAt(0) === 47 ? "/" : "." : end === 1 && path3.codePointAt(0) === 47 ? "//" : path3.slice(0, end);
}
function extname(path3) {
assertPath(path3);
let index2 = path3.length;
let end = -1;
let startPart = 0;
let startDot = -1;
let preDotState = 0;
let unmatchedSlash;
while (index2--) {
const code4 = path3.codePointAt(index2);
if (code4 === 47) {
if (unmatchedSlash) {
startPart = index2 + 1;
break;
}
continue;
}
if (end < 0) {
unmatchedSlash = true;
end = index2 + 1;
}
if (code4 === 46) {
if (startDot < 0) {
startDot = index2;
} else if (preDotState !== 1) {
preDotState = 1;
}
} else if (startDot > -1) {
preDotState = -1;
}
}
if (startDot < 0 || end < 0 || // We saw a non-dot character immediately before the dot.
preDotState === 0 || // The (right-most) trimmed path component is exactly `..`.
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return "";
}
return path3.slice(startDot, end);
}
function join(...segments) {
let index2 = -1;
let joined;
while (++index2 < segments.length) {
assertPath(segments[index2]);
if (segments[index2]) {
joined = joined === void 0 ? segments[index2] : joined + "/" + segments[index2];
}
}
return joined === void 0 ? "." : normalize(joined);
}
function normalize(path3) {
assertPath(path3);
const absolute = path3.codePointAt(0) === 47;
let value = normalizeString(path3, !absolute);
if (value.length === 0 && !absolute) {
value = ".";
}
if (value.length > 0 && path3.codePointAt(path3.length - 1) === 47) {
value += "/";
}
return absolute ? "/" + value : value;
}
function normalizeString(path3, allowAboveRoot) {
let result = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let index2 = -1;
let code4;
let lastSlashIndex;
while (++index2 <= path3.length) {
if (index2 < path3.length) {
code4 = path3.codePointAt(index2);
} else if (code4 === 47) {
break;
} else {
code4 = 47;
}
if (code4 === 47) {
if (lastSlash === index2 - 1 || dots === 1) {
} else if (lastSlash !== index2 - 1 && dots === 2) {
if (result.length < 2 || lastSegmentLength !== 2 || result.codePointAt(result.length - 1) !== 46 || result.codePointAt(result.length - 2) !== 46) {
if (result.length > 2) {
lastSlashIndex = result.lastIndexOf("/");
if (lastSlashIndex !== result.length - 1) {
if (lastSlashIndex < 0) {
result = "";
lastSegmentLength = 0;
} else {
result = result.slice(0, lastSlashIndex);
lastSegmentLength = result.length - 1 - result.lastIndexOf("/");
}
lastSlash = index2;
dots = 0;
continue;
}
} else if (result.length > 0) {
result = "";
lastSegmentLength = 0;
lastSlash = index2;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
result = result.length > 0 ? result + "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (result.length > 0) {
result += "/" + path3.slice(lastSlash + 1, index2);
} else {
result = path3.slice(lastSlash + 1, index2);
}
lastSegmentLength = index2 - lastSlash - 1;
}
lastSlash = index2;
dots = 0;
} else if (code4 === 46 && dots > -1) {
dots++;
} else {
dots = -1;
}
}
return result;
}
function assertPath(path3) {
if (typeof path3 !== "string") {
throw new TypeError(
"Path must be a string. Received " + JSON.stringify(path3)
);
}
}
// node_modules/vfile/lib/minproc.browser.js
var minproc = { cwd };
function cwd() {
return "/";
}
// node_modules/vfile/lib/minurl.shared.js
function isUrl(fileUrlOrPath) {
return Boolean(
fileUrlOrPath !== null && typeof fileUrlOrPath === "object" && "href" in fileUrlOrPath && fileUrlOrPath.href && "protocol" in fileUrlOrPath && fileUrlOrPath.protocol && // @ts-expect-error: indexing is fine.
fileUrlOrPath.auth === void 0
);
}
// node_modules/vfile/lib/minurl.browser.js
function urlToPath(path3) {
if (typeof path3 === "string") {
path3 = new URL(path3);
} else if (!isUrl(path3)) {
const error = new TypeError(
'The "path" argument must be of type string or an instance of URL. Received `' + path3 + "`"
);
error.code = "ERR_INVALID_ARG_TYPE";
throw error;
}
if (path3.protocol !== "file:") {
const error = new TypeError("The URL must be of scheme file");
error.code = "ERR_INVALID_URL_SCHEME";
throw error;
}
return getPathFromURLPosix(path3);
}
function getPathFromURLPosix(url) {
if (url.hostname !== "") {
const error = new TypeError(
'File URL host must be "localhost" or empty on darwin'
);
error.code = "ERR_INVALID_FILE_URL_HOST";
throw error;
}
const pathname = url.pathname;
let index2 = -1;
while (++index2 < pathname.length) {
if (pathname.codePointAt(index2) === 37 && pathname.codePointAt(index2 + 1) === 50) {
const third = pathname.codePointAt(index2 + 2);
if (third === 70 || third === 102) {
const error = new TypeError(
"File URL path must not include encoded / characters"
);
error.code = "ERR_INVALID_FILE_URL_PATH";
throw error;
}
}
}
return decodeURIComponent(pathname);
}
// node_modules/vfile/lib/index.js
var order = (
/** @type {const} */
[
"history",
"path",
"basename",
"stem",
"extname",
"dirname"
]
);
var VFile = class {
/**
* Create a new virtual file.
*
* `options` is treated as:
*
* * `string` or `Uint8Array` — `{value: options}`
* * `URL` — `{path: options}`
* * `VFile` — shallow copies its data over to the new file
* * `object` — all fields are shallow copied over to the new file
*
* Path related fields are set in the following order (least specific to
* most specific): `history`, `path`, `basename`, `stem`, `extname`,
* `dirname`.
*
* You cannot set `dirname` or `extname` without setting either `history`,
* `path`, `basename`, or `stem` too.
*
* @param {Compatible | null | undefined} [value]
* File value.
* @returns
* New instance.
*/
constructor(value) {
let options;
if (!value) {
options = {};
} else if (isUrl(value)) {
options = { path: value };
} else if (typeof value === "string" || isUint8Array(value)) {
options = { value };
} else {
options = value;
}
this.cwd = "cwd" in options ? "" : minproc.cwd();
this.data = {};
this.history = [];
this.messages = [];
this.value;
this.map;
this.result;
this.stored;
let index2 = -1;
while (++index2 < order.length) {
const field2 = order[index2];
if (field2 in options && options[field2] !== void 0 && options[field2] !== null) {
this[field2] = field2 === "history" ? [...options[field2]] : options[field2];
}
}
let field;
for (field in options) {
if (!order.includes(field)) {
this[field] = options[field];
}
}
}
/**
* Get the basename (including extname) (example: `'index.min.js'`).
*
* @returns {string | undefined}
* Basename.
*/
get basename() {
return typeof this.path === "string" ? minpath.basename(this.path) : void 0;
}
/**
* Set basename (including extname) (`'index.min.js'`).
*
* Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
* on windows).
* Cannot be nullified (use `file.path = file.dirname` instead).
*
* @param {string} basename
* Basename.
* @returns {undefined}
* Nothing.
*/
set basename(basename2) {
assertNonEmpty(basename2, "basename");
assertPart(basename2, "basename");
this.path = minpath.join(this.dirname || "", basename2);
}
/**
* Get the parent path (example: `'~'`).
*
* @returns {string | undefined}
* Dirname.
*/
get dirname() {
return typeof this.path === "string" ? minpath.dirname(this.path) : void 0;
}
/**
* Set the parent path (example: `'~'`).
*
* Cannot be set if there’s no `path` yet.
*
* @param {string | undefined} dirname
* Dirname.
* @returns {undefined}
* Nothing.
*/
set dirname(dirname2) {
assertPath2(this.basename, "dirname");
this.path = minpath.join(dirname2 || "", this.basename);
}
/**
* Get the extname (including dot) (example: `'.js'`).
*
* @returns {string | undefined}
* Extname.
*/
get extname() {
return typeof this.path === "string" ? minpath.extname(this.path) : void 0;
}
/**
* Set the extname (including dot) (example: `'.js'`).
*
* Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
* on windows).
* Cannot be set if there’s no `path` yet.
*
* @param {string | undefined} extname
* Extname.
* @returns {undefined}
* Nothing.
*/
set extname(extname2) {
assertPart(extname2, "extname");
assertPath2(this.dirname, "extname");
if (extname2) {
if (extname2.codePointAt(0) !== 46) {
throw new Error("`extname` must start with `.`");
}
if (extname2.includes(".", 1)) {
throw new Error("`extname` cannot contain multiple dots");
}
}
this.path = minpath.join(this.dirname, this.stem + (extname2 || ""));
}
/**
* Get the full path (example: `'~/index.min.js'`).
*
* @returns {string}
* Path.
*/
get path() {
return this.history[this.history.length - 1];
}
/**
* Set the full path (example: `'~/index.min.js'`).
*
* Cannot be nullified.
* You can set a file URL (a `URL` object with a `file:` protocol) which will
* be turned into a path with `url.fileURLToPath`.
*
* @param {URL | string} path
* Path.
* @returns {undefined}
* Nothing.
*/
set path(path3) {
if (isUrl(path3)) {
path3 = urlToPath(path3);
}
assertNonEmpty(path3, "path");
if (this.path !== path3) {
this.history.push(path3);
}
}
/**
* Get the stem (basename w/o extname) (example: `'index.min'`).
*
* @returns {string | undefined}
* Stem.
*/
get stem() {
return typeof this.path === "string" ? minpath.basename(this.path, this.extname) : void 0;
}
/**
* Set the stem (basename w/o extname) (example: `'index.min'`).
*
* Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
* on windows).
* Cannot be nullified (use `file.path = file.dirname` instead).
*
* @param {string} stem
* Stem.
* @returns {undefined}
* Nothing.
*/
set stem(stem) {
assertNonEmpty(stem, "stem");
assertPart(stem, "stem");
this.path = minpath.join(this.dirname || "", stem + (this.extname || ""));
}
// Normal prototypal methods.
/**
* Create a fatal message for `reason` associated with the file.
*
* The `fatal` field of the message is set to `true` (error; file not usable)
* and the `file` field is set to the current file path.
* The message is added to the `messages` field on `file`.
*
* > 🪦 **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {MessageOptions | null | undefined} [options]
* @returns {never}
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* `'my-package:my-rule'` or `'my-rule'`).
* @returns {never}
* Never.
* @throws {VFileMessage}
* Message.
*/
fail(causeOrReason, optionsOrParentOrPlace, origin) {
const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
message.fatal = true;
throw message;
}
/**
* Create an info message for `reason` associated with the file.
*
* The `fatal` field of the message is set to `undefined` (info; change
* likely not needed) and the `file` field is set to the current file path.
* The message is added to the `messages` field on `file`.
*
* > 🪦 **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {MessageOptions | null | undefined} [options]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* `'my-package:my-rule'` or `'my-rule'`).
* @returns {VFileMessage}
* Message.
*/
info(causeOrReason, optionsOrParentOrPlace, origin) {
const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
message.fatal = void 0;
return message;
}
/**
* Create a message for `reason` associated with the file.
*
* The `fatal` field of the message is set to `false` (warning; change may be
* needed) and the `file` field is set to the current file path.
* The message is added to the `messages` field on `file`.
*
* > 🪦 **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {MessageOptions | null | undefined} [options]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* `'my-package:my-rule'` or `'my-rule'`).
* @returns {VFileMessage}
* Message.
*/
message(causeOrReason, optionsOrParentOrPlace, origin) {
const message = new VFileMessage(
// @ts-expect-error: the overloads are fine.
causeOrReason,
optionsOrParentOrPlace,
origin
);
if (this.path) {
message.name = this.path + ":" + message.name;
message.file = this.path;
}
message.fatal = false;
this.messages.push(message);
return message;
}
/**
* Serialize the file.
*
* > **Note**: which encodings are supported depends on the engine.
* > For info on Node.js, see:
* > .
*
* @param {string | null | undefined} [encoding='utf8']
* Character encoding to understand `value` as when it’s a `Uint8Array`
* (default: `'utf-8'`).
* @returns {string}
* Serialized file.
*/
toString(encoding) {
if (this.value === void 0) {
return "";
}
if (typeof this.value === "string") {
return this.value;
}
const decoder = new TextDecoder(encoding || void 0);
return decoder.decode(this.value);
}
};
function assertPart(part, name) {
if (part && part.includes(minpath.sep)) {
throw new Error(
"`" + name + "` cannot be a path: did not expect `" + minpath.sep + "`"
);
}
}
function assertNonEmpty(part, name) {
if (!part) {
throw new Error("`" + name + "` cannot be empty");
}
}
function assertPath2(path3, name) {
if (!path3) {
throw new Error("Setting `" + name + "` requires `path` to be set too");
}
}
function isUint8Array(value) {
return Boolean(
value && typeof value === "object" && "byteLength" in value && "byteOffset" in value
);
}
// node_modules/unified/lib/callable-instance.js
var CallableInstance = (
/**
* @type {new , Result>(property: string | symbol) => (...parameters: Parameters) => Result}
*/
/** @type {unknown} */
/**
* @this {Function}
* @param {string | symbol} property
* @returns {(...parameters: Array) => unknown}
*/
function(property) {
const self = this;
const constr = self.constructor;
const proto = (
/** @type {Record} */
// Prototypes do exist.
// type-coverage:ignore-next-line
constr.prototype
);
const value = proto[property];
const apply = function() {
return value.apply(apply, arguments);
};
Object.setPrototypeOf(apply, proto);
return apply;
}
);
// node_modules/unified/lib/index.js
var own = {}.hasOwnProperty;
var Processor = class _Processor extends CallableInstance {
/**
* Create a processor.
*/
constructor() {
super("copy");
this.Compiler = void 0;
this.Parser = void 0;
this.attachers = [];
this.compiler = void 0;
this.freezeIndex = -1;
this.frozen = void 0;
this.namespace = {};
this.parser = void 0;
this.transformers = trough();
}
/**
* Copy a processor.
*
* @deprecated
* This is a private internal method and should not be used.
* @returns {Processor}
* New *unfrozen* processor ({@linkcode Processor}) that is
* configured to work the same as its ancestor.
* When the descendant processor is configured in the future it does not
* affect the ancestral processor.
*/
copy() {
const destination = (
/** @type {Processor} */
new _Processor()
);
let index2 = -1;
while (++index2 < this.attachers.length) {
const attacher = this.attachers[index2];
destination.use(...attacher);
}
destination.data((0, import_extend.default)(true, {}, this.namespace));
return destination;
}
/**
* Configure the processor with info available to all plugins.
* Information is stored in an object.
*
* Typically, options can be given to a specific plugin, but sometimes it
* makes sense to have information shared with several plugins.
* For example, a list of HTML elements that are self-closing, which is
* needed during all phases.
*
* > **Note**: setting information cannot occur on *frozen* processors.
* > Call the processor first to create a new unfrozen processor.
*
* > **Note**: to register custom data in TypeScript, augment the
* > {@linkcode Data} interface.
*
* @example
* This example show how to get and set info:
*
* ```js
* import {unified} from 'unified'
*
* const processor = unified().data('alpha', 'bravo')
*
* processor.data('alpha') // => 'bravo'
*
* processor.data() // => {alpha: 'bravo'}
*
* processor.data({charlie: 'delta'})
*
* processor.data() // => {charlie: 'delta'}
* ```
*
* @template {keyof Data} Key
*
* @overload
* @returns {Data}
*
* @overload
* @param {Data} dataset
* @returns {Processor}
*
* @overload
* @param {Key} key
* @returns {Data[Key]}
*
* @overload
* @param {Key} key
* @param {Data[Key]} value
* @returns {Processor}
*
* @param {Data | Key} [key]
* Key to get or set, or entire dataset to set, or nothing to get the
* entire dataset (optional).
* @param {Data[Key]} [value]
* Value to set (optional).
* @returns {unknown}
* The current processor when setting, the value at `key` when getting, or
* the entire dataset when getting without key.
*/
data(key, value) {
if (typeof key === "string") {
if (arguments.length === 2) {
assertUnfrozen("data", this.frozen);
this.namespace[key] = value;
return this;
}
return own.call(this.namespace, key) && this.namespace[key] || void 0;
}
if (key) {
assertUnfrozen("data", this.frozen);
this.namespace = key;
return this;
}
return this.namespace;
}
/**
* Freeze a processor.
*
* Frozen processors are meant to be extended and not to be configured
* directly.
*
* When a processor is frozen it cannot be unfrozen.
* New processors working the same way can be created by calling the
* processor.
*
* It’s possible to freeze processors explicitly by calling `.freeze()`.
* Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,
* `.stringify()`, `.process()`, or `.processSync()` are called.
*
* @returns {Processor}
* The current processor.
*/
freeze() {
if (this.frozen) {
return this;
}
const self = (
/** @type {Processor} */
/** @type {unknown} */
this
);
while (++this.freezeIndex < this.attachers.length) {
const [attacher, ...options] = this.attachers[this.freezeIndex];
if (options[0] === false) {
continue;
}
if (options[0] === true) {
options[0] = void 0;
}
const transformer = attacher.call(self, ...options);
if (typeof transformer === "function") {
this.transformers.use(transformer);
}
}
this.frozen = true;
this.freezeIndex = Number.POSITIVE_INFINITY;
return this;
}
/**
* Parse text to a syntax tree.
*
* > **Note**: `parse` freezes the processor if not already *frozen*.
*
* > **Note**: `parse` performs the parse phase, not the run phase or other
* > phases.
*
* @param {Compatible | undefined} [file]
* file to parse (optional); typically `string` or `VFile`; any value
* accepted as `x` in `new VFile(x)`.
* @returns {ParseTree extends undefined ? Node : ParseTree}
* Syntax tree representing `file`.
*/
parse(file) {
this.freeze();
const realFile = vfile(file);
const parser = this.parser || this.Parser;
assertParser("parse", parser);
return parser(String(realFile), realFile);
}
/**
* Process the given file as configured on the processor.
*
* > **Note**: `process` freezes the processor if not already *frozen*.
*
* > **Note**: `process` performs the parse, run, and stringify phases.
*
* @overload
* @param {Compatible | undefined} file
* @param {ProcessCallback>} done
* @returns {undefined}
*
* @overload
* @param {Compatible | undefined} [file]
* @returns {Promise>}
*
* @param {Compatible | undefined} [file]
* File (optional); typically `string` or `VFile`]; any value accepted as
* `x` in `new VFile(x)`.
* @param {ProcessCallback> | undefined} [done]
* Callback (optional).
* @returns {Promise | undefined}
* Nothing if `done` is given.
* Otherwise a promise, rejected with a fatal error or resolved with the
* processed file.
*
* The parsed, transformed, and compiled value is available at
* `file.value` (see note).
*
* > **Note**: unified typically compiles by serializing: most
* > compilers return `string` (or `Uint8Array`).
* > Some compilers, such as the one configured with
* > [`rehype-react`][rehype-react], return other values (in this case, a
* > React tree).
* > If you’re using a compiler that doesn’t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@linkcode CompileResultMap}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
process(file, done) {
const self = this;
this.freeze();
assertParser("process", this.parser || this.Parser);
assertCompiler("process", this.compiler || this.Compiler);
return done ? executor(void 0, done) : new Promise(executor);
function executor(resolve, reject) {
const realFile = vfile(file);
const parseTree = (
/** @type {HeadTree extends undefined ? Node : HeadTree} */
/** @type {unknown} */
self.parse(realFile)
);
self.run(parseTree, realFile, function(error, tree, file2) {
if (error || !tree || !file2) {
return realDone(error);
}
const compileTree = (
/** @type {CompileTree extends undefined ? Node : CompileTree} */
/** @type {unknown} */
tree
);
const compileResult = self.stringify(compileTree, file2);
if (looksLikeAValue(compileResult)) {
file2.value = compileResult;
} else {
file2.result = compileResult;
}
realDone(
error,
/** @type {VFileWithOutput} */
file2
);
});
function realDone(error, file2) {
if (error || !file2) {
reject(error);
} else if (resolve) {
resolve(file2);
} else {
ok(done, "`done` is defined if `resolve` is not");
done(void 0, file2);
}
}
}
}
/**
* Process the given file as configured on the processor.
*
* An error is thrown if asynchronous transforms are configured.
*
* > **Note**: `processSync` freezes the processor if not already *frozen*.
*
* > **Note**: `processSync` performs the parse, run, and stringify phases.
*
* @param {Compatible | undefined} [file]
* File (optional); typically `string` or `VFile`; any value accepted as
* `x` in `new VFile(x)`.
* @returns {VFileWithOutput}
* The processed file.
*
* The parsed, transformed, and compiled value is available at
* `file.value` (see note).
*
* > **Note**: unified typically compiles by serializing: most
* > compilers return `string` (or `Uint8Array`).
* > Some compilers, such as the one configured with
* > [`rehype-react`][rehype-react], return other values (in this case, a
* > React tree).
* > If you’re using a compiler that doesn’t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@linkcode CompileResultMap}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
processSync(file) {
let complete = false;
let result;
this.freeze();
assertParser("processSync", this.parser || this.Parser);
assertCompiler("processSync", this.compiler || this.Compiler);
this.process(file, realDone);
assertDone("processSync", "process", complete);
ok(result, "we either bailed on an error or have a tree");
return result;
function realDone(error, file2) {
complete = true;
bail(error);
result = file2;
}
}
/**
* Run *transformers* on a syntax tree.
*
* > **Note**: `run` freezes the processor if not already *frozen*.
*
* > **Note**: `run` performs the run phase, not other phases.
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {RunCallback} done
* @returns {undefined}
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {Compatible | undefined} file
* @param {RunCallback} done
* @returns {undefined}
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {Compatible | undefined} [file]
* @returns {Promise}
*
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* Tree to transform and inspect.
* @param {(
* RunCallback |
* Compatible
* )} [file]
* File associated with `node` (optional); any value accepted as `x` in
* `new VFile(x)`.
* @param {RunCallback} [done]
* Callback (optional).
* @returns {Promise | undefined}
* Nothing if `done` is given.
* Otherwise, a promise rejected with a fatal error or resolved with the
* transformed tree.
*/
run(tree, file, done) {
assertNode(tree);
this.freeze();
const transformers = this.transformers;
if (!done && typeof file === "function") {
done = file;
file = void 0;
}
return done ? executor(void 0, done) : new Promise(executor);
function executor(resolve, reject) {
ok(
typeof file !== "function",
"`file` can\u2019t be a `done` anymore, we checked"
);
const realFile = vfile(file);
transformers.run(tree, realFile, realDone);
function realDone(error, outputTree, file2) {
const resultingTree = (
/** @type {TailTree extends undefined ? Node : TailTree} */
outputTree || tree
);
if (error) {
reject(error);
} else if (resolve) {
resolve(resultingTree);
} else {
ok(done, "`done` is defined if `resolve` is not");
done(void 0, resultingTree, file2);
}
}
}
}
/**
* Run *transformers* on a syntax tree.
*
* An error is thrown if asynchronous transforms are configured.
*
* > **Note**: `runSync` freezes the processor if not already *frozen*.
*
* > **Note**: `runSync` performs the run phase, not other phases.
*
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* Tree to transform and inspect.
* @param {Compatible | undefined} [file]
* File associated with `node` (optional); any value accepted as `x` in
* `new VFile(x)`.
* @returns {TailTree extends undefined ? Node : TailTree}
* Transformed tree.
*/
runSync(tree, file) {
let complete = false;
let result;
this.run(tree, file, realDone);
assertDone("runSync", "run", complete);
ok(result, "we either bailed on an error or have a tree");
return result;
function realDone(error, tree2) {
bail(error);
result = tree2;
complete = true;
}
}
/**
* Compile a syntax tree.
*
* > **Note**: `stringify` freezes the processor if not already *frozen*.
*
* > **Note**: `stringify` performs the stringify phase, not the run phase
* > or other phases.
*
* @param {CompileTree extends undefined ? Node : CompileTree} tree
* Tree to compile.
* @param {Compatible | undefined} [file]
* File associated with `node` (optional); any value accepted as `x` in
* `new VFile(x)`.
* @returns {CompileResult extends undefined ? Value : CompileResult}
* Textual representation of the tree (see note).
*
* > **Note**: unified typically compiles by serializing: most compilers
* > return `string` (or `Uint8Array`).
* > Some compilers, such as the one configured with
* > [`rehype-react`][rehype-react], return other values (in this case, a
* > React tree).
* > If you’re using a compiler that doesn’t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@linkcode CompileResultMap}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
stringify(tree, file) {
this.freeze();
const realFile = vfile(file);
const compiler2 = this.compiler || this.Compiler;
assertCompiler("stringify", compiler2);
assertNode(tree);
return compiler2(tree, realFile);
}
/**
* Configure the processor to use a plugin, a list of usable values, or a
* preset.
*
* If the processor is already using a plugin, the previous plugin
* configuration is changed based on the options that are passed in.
* In other words, the plugin is not added a second time.
*
* > **Note**: `use` cannot be called on *frozen* processors.
* > Call the processor first to create a new unfrozen processor.
*
* @example
* There are many ways to pass plugins to `.use()`.
* This example gives an overview:
*
* ```js
* import {unified} from 'unified'
*
* unified()
* // Plugin with options:
* .use(pluginA, {x: true, y: true})
* // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):
* .use(pluginA, {y: false, z: true})
* // Plugins:
* .use([pluginB, pluginC])
* // Two plugins, the second with options:
* .use([pluginD, [pluginE, {}]])
* // Preset with plugins and settings:
* .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
* // Settings only:
* .use({settings: {position: false}})
* ```
*
* @template {Array} [Parameters=[]]
* @template {Node | string | undefined} [Input=undefined]
* @template [Output=Input]
*
* @overload
* @param {Preset | null | undefined} [preset]
* @returns {Processor}
*
* @overload
* @param {PluggableList} list
* @returns {Processor}
*
* @overload
* @param {Plugin} plugin
* @param {...(Parameters | [boolean])} parameters
* @returns {UsePlugin}
*
* @param {PluggableList | Plugin | Preset | null | undefined} value
* Usable value.
* @param {...unknown} parameters
* Parameters, when a plugin is given as a usable value.
* @returns {Processor}
* Current processor.
*/
use(value, ...parameters) {
const attachers = this.attachers;
const namespace = this.namespace;
assertUnfrozen("use", this.frozen);
if (value === null || value === void 0) {
} else if (typeof value === "function") {
addPlugin(value, parameters);
} else if (typeof value === "object") {
if (Array.isArray(value)) {
addList(value);
} else {
addPreset(value);
}
} else {
throw new TypeError("Expected usable value, not `" + value + "`");
}
return this;
function add(value2) {
if (typeof value2 === "function") {
addPlugin(value2, []);
} else if (typeof value2 === "object") {
if (Array.isArray(value2)) {
const [plugin, ...parameters2] = (
/** @type {PluginTuple>} */
value2
);
addPlugin(plugin, parameters2);
} else {
addPreset(value2);
}
} else {
throw new TypeError("Expected usable value, not `" + value2 + "`");
}
}
function addPreset(result) {
if (!("plugins" in result) && !("settings" in result)) {
throw new Error(
"Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither"
);
}
addList(result.plugins);
if (result.settings) {
namespace.settings = (0, import_extend.default)(true, namespace.settings, result.settings);
}
}
function addList(plugins) {
let index2 = -1;
if (plugins === null || plugins === void 0) {
} else if (Array.isArray(plugins)) {
while (++index2 < plugins.length) {
const thing = plugins[index2];
add(thing);
}
} else {
throw new TypeError("Expected a list of plugins, not `" + plugins + "`");
}
}
function addPlugin(plugin, parameters2) {
let index2 = -1;
let entryIndex = -1;
while (++index2 < attachers.length) {
if (attachers[index2][0] === plugin) {
entryIndex = index2;
break;
}
}
if (entryIndex === -1) {
attachers.push([plugin, ...parameters2]);
} else if (parameters2.length > 0) {
let [primary, ...rest] = parameters2;
const currentPrimary = attachers[entryIndex][1];
if (isPlainObject(currentPrimary) && isPlainObject(primary)) {
primary = (0, import_extend.default)(true, currentPrimary, primary);
}
attachers[entryIndex] = [plugin, primary, ...rest];
}
}
}
};
var unified = new Processor().freeze();
function assertParser(name, value) {
if (typeof value !== "function") {
throw new TypeError("Cannot `" + name + "` without `parser`");
}
}
function assertCompiler(name, value) {
if (typeof value !== "function") {
throw new TypeError("Cannot `" + name + "` without `compiler`");
}
}
function assertUnfrozen(name, frozen) {
if (frozen) {
throw new Error(
"Cannot call `" + name + "` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`."
);
}
}
function assertNode(node2) {
if (!isPlainObject(node2) || typeof node2.type !== "string") {
throw new TypeError("Expected node, got `" + node2 + "`");
}
}
function assertDone(name, asyncName, complete) {
if (!complete) {
throw new Error(
"`" + name + "` finished async. Use `" + asyncName + "` instead"
);
}
}
function vfile(value) {
return looksLikeAVFile(value) ? value : new VFile(value);
}
function looksLikeAVFile(value) {
return Boolean(
value && typeof value === "object" && "message" in value && "messages" in value
);
}
function looksLikeAValue(value) {
return typeof value === "string" || isUint8Array2(value);
}
function isUint8Array2(value) {
return Boolean(
value && typeof value === "object" && "byteLength" in value && "byteOffset" in value
);
}
// node_modules/mdast-util-to-string/lib/index.js
var emptyOptions = {};
function toString(value, options) {
const settings = options || emptyOptions;
const includeImageAlt = typeof settings.includeImageAlt === "boolean" ? settings.includeImageAlt : true;
const includeHtml = typeof settings.includeHtml === "boolean" ? settings.includeHtml : true;
return one(value, includeImageAlt, includeHtml);
}
function one(value, includeImageAlt, includeHtml) {
if (node(value)) {
if ("value" in value) {
return value.type === "html" && !includeHtml ? "" : value.value;
}
if (includeImageAlt && "alt" in value && value.alt) {
return value.alt;
}
if ("children" in value) {
return all(value.children, includeImageAlt, includeHtml);
}
}
if (Array.isArray(value)) {
return all(value, includeImageAlt, includeHtml);
}
return "";
}
function all(values, includeImageAlt, includeHtml) {
const result = [];
let index2 = -1;
while (++index2 < values.length) {
result[index2] = one(values[index2], includeImageAlt, includeHtml);
}
return result.join("");
}
function node(value) {
return Boolean(value && typeof value === "object");
}
// node_modules/decode-named-character-reference/index.dom.js
var element = document.createElement("i");
function decodeNamedCharacterReference(value) {
const characterReference2 = "&" + value + ";";
element.innerHTML = characterReference2;
const character = element.textContent;
if (character.charCodeAt(character.length - 1) === 59 && value !== "semi") {
return false;
}
return character === characterReference2 ? false : character;
}
// node_modules/micromark-util-chunked/index.js
function splice(list3, start, remove, items) {
const end = list3.length;
let chunkStart = 0;
let parameters;
if (start < 0) {
start = -start > end ? 0 : end + start;
} else {
start = start > end ? end : start;
}
remove = remove > 0 ? remove : 0;
if (items.length < 1e4) {
parameters = Array.from(items);
parameters.unshift(start, remove);
list3.splice(...parameters);
} else {
if (remove)
list3.splice(start, remove);
while (chunkStart < items.length) {
parameters = items.slice(chunkStart, chunkStart + 1e4);
parameters.unshift(start, 0);
list3.splice(...parameters);
chunkStart += 1e4;
start += 1e4;
}
}
}
function push(list3, items) {
if (list3.length > 0) {
splice(list3, list3.length, 0, items);
return list3;
}
return items;
}
// node_modules/micromark-util-combine-extensions/index.js
var hasOwnProperty = {}.hasOwnProperty;
function combineExtensions(extensions) {
const all2 = {};
let index2 = -1;
while (++index2 < extensions.length) {
syntaxExtension(all2, extensions[index2]);
}
return all2;
}
function syntaxExtension(all2, extension2) {
let hook;
for (hook in extension2) {
const maybe = hasOwnProperty.call(all2, hook) ? all2[hook] : void 0;
const left = maybe || (all2[hook] = {});
const right = extension2[hook];
let code4;
if (right) {
for (code4 in right) {
if (!hasOwnProperty.call(left, code4))
left[code4] = [];
const value = right[code4];
constructs(
// @ts-expect-error Looks like a list.
left[code4],
Array.isArray(value) ? value : value ? [value] : []
);
}
}
}
}
function constructs(existing, list3) {
let index2 = -1;
const before = [];
while (++index2 < list3.length) {
;
(list3[index2].add === "after" ? existing : before).push(list3[index2]);
}
splice(existing, 0, 0, before);
}
// node_modules/micromark-util-decode-numeric-character-reference/index.js
function decodeNumericCharacterReference(value, base) {
const code4 = Number.parseInt(value, base);
if (
// C0 except for HT, LF, FF, CR, space.
code4 < 9 || code4 === 11 || code4 > 13 && code4 < 32 || // Control character (DEL) of C0, and C1 controls.
code4 > 126 && code4 < 160 || // Lone high surrogates and low surrogates.
code4 > 55295 && code4 < 57344 || // Noncharacters.
code4 > 64975 && code4 < 65008 || /* eslint-disable no-bitwise */
(code4 & 65535) === 65535 || (code4 & 65535) === 65534 || /* eslint-enable no-bitwise */
// Out of range
code4 > 1114111
) {
return "\uFFFD";
}
return String.fromCodePoint(code4);
}
// node_modules/micromark-util-normalize-identifier/index.js
function normalizeIdentifier(value) {
return value.replace(/[\t\n\r ]+/g, " ").replace(/^ | $/g, "").toLowerCase().toUpperCase();
}
// node_modules/micromark-util-character/index.js
var asciiAlpha = regexCheck(/[A-Za-z]/);
var asciiAlphanumeric = regexCheck(/[\dA-Za-z]/);
var asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/);
function asciiControl(code4) {
return (
// Special whitespace codes (which have negative values), C0 and Control
// character DEL
code4 !== null && (code4 < 32 || code4 === 127)
);
}
var asciiDigit = regexCheck(/\d/);
var asciiHexDigit = regexCheck(/[\dA-Fa-f]/);
var asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);
function markdownLineEnding(code4) {
return code4 !== null && code4 < -2;
}
function markdownLineEndingOrSpace(code4) {
return code4 !== null && (code4 < 0 || code4 === 32);
}
function markdownSpace(code4) {
return code4 === -2 || code4 === -1 || code4 === 32;
}
var unicodePunctuation = regexCheck(new RegExp("\\p{P}|\\p{S}", "u"));
var unicodeWhitespace = regexCheck(/\s/);
function regexCheck(regex) {
return check;
function check(code4) {
return code4 !== null && code4 > -1 && regex.test(String.fromCharCode(code4));
}
}
// node_modules/micromark-factory-space/index.js
function factorySpace(effects, ok3, type, max) {
const limit = max ? max - 1 : Number.POSITIVE_INFINITY;
let size = 0;
return start;
function start(code4) {
if (markdownSpace(code4)) {
effects.enter(type);
return prefix(code4);
}
return ok3(code4);
}
function prefix(code4) {
if (markdownSpace(code4) && size++ < limit) {
effects.consume(code4);
return prefix;
}
effects.exit(type);
return ok3(code4);
}
}
// node_modules/micromark/lib/initialize/content.js
var content = {
tokenize: initializeContent
};
function initializeContent(effects) {
const contentStart = effects.attempt(this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial);
let previous4;
return contentStart;
function afterContentStartConstruct(code4) {
if (code4 === null) {
effects.consume(code4);
return;
}
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return factorySpace(effects, contentStart, "linePrefix");
}
function paragraphInitial(code4) {
effects.enter("paragraph");
return lineStart(code4);
}
function lineStart(code4) {
const token = effects.enter("chunkText", {
contentType: "text",
previous: previous4
});
if (previous4) {
previous4.next = token;
}
previous4 = token;
return data(code4);
}
function data(code4) {
if (code4 === null) {
effects.exit("chunkText");
effects.exit("paragraph");
effects.consume(code4);
return;
}
if (markdownLineEnding(code4)) {
effects.consume(code4);
effects.exit("chunkText");
return lineStart;
}
effects.consume(code4);
return data;
}
}
// node_modules/micromark/lib/initialize/document.js
var document2 = {
tokenize: initializeDocument
};
var containerConstruct = {
tokenize: tokenizeContainer
};
function initializeDocument(effects) {
const self = this;
const stack = [];
let continued = 0;
let childFlow;
let childToken;
let lineStartOffset;
return start;
function start(code4) {
if (continued < stack.length) {
const item = stack[continued];
self.containerState = item[1];
return effects.attempt(item[0].continuation, documentContinue, checkNewContainers)(code4);
}
return checkNewContainers(code4);
}
function documentContinue(code4) {
continued++;
if (self.containerState._closeFlow) {
self.containerState._closeFlow = void 0;
if (childFlow) {
closeFlow();
}
const indexBeforeExits = self.events.length;
let indexBeforeFlow = indexBeforeExits;
let point3;
while (indexBeforeFlow--) {
if (self.events[indexBeforeFlow][0] === "exit" && self.events[indexBeforeFlow][1].type === "chunkFlow") {
point3 = self.events[indexBeforeFlow][1].end;
break;
}
}
exitContainers(continued);
let index2 = indexBeforeExits;
while (index2 < self.events.length) {
self.events[index2][1].end = __spreadValues({}, point3);
index2++;
}
splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));
self.events.length = index2;
return checkNewContainers(code4);
}
return start(code4);
}
function checkNewContainers(code4) {
if (continued === stack.length) {
if (!childFlow) {
return documentContinued(code4);
}
if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {
return flowStart(code4);
}
self.interrupt = Boolean(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack);
}
self.containerState = {};
return effects.check(containerConstruct, thereIsANewContainer, thereIsNoNewContainer)(code4);
}
function thereIsANewContainer(code4) {
if (childFlow)
closeFlow();
exitContainers(continued);
return documentContinued(code4);
}
function thereIsNoNewContainer(code4) {
self.parser.lazy[self.now().line] = continued !== stack.length;
lineStartOffset = self.now().offset;
return flowStart(code4);
}
function documentContinued(code4) {
self.containerState = {};
return effects.attempt(containerConstruct, containerContinue, flowStart)(code4);
}
function containerContinue(code4) {
continued++;
stack.push([self.currentConstruct, self.containerState]);
return documentContinued(code4);
}
function flowStart(code4) {
if (code4 === null) {
if (childFlow)
closeFlow();
exitContainers(0);
effects.consume(code4);
return;
}
childFlow = childFlow || self.parser.flow(self.now());
effects.enter("chunkFlow", {
_tokenizer: childFlow,
contentType: "flow",
previous: childToken
});
return flowContinue(code4);
}
function flowContinue(code4) {
if (code4 === null) {
writeToChild(effects.exit("chunkFlow"), true);
exitContainers(0);
effects.consume(code4);
return;
}
if (markdownLineEnding(code4)) {
effects.consume(code4);
writeToChild(effects.exit("chunkFlow"));
continued = 0;
self.interrupt = void 0;
return start;
}
effects.consume(code4);
return flowContinue;
}
function writeToChild(token, endOfFile) {
const stream = self.sliceStream(token);
if (endOfFile)
stream.push(null);
token.previous = childToken;
if (childToken)
childToken.next = token;
childToken = token;
childFlow.defineSkip(token.start);
childFlow.write(stream);
if (self.parser.lazy[token.start.line]) {
let index2 = childFlow.events.length;
while (index2--) {
if (
// The token starts before the line ending…
childFlow.events[index2][1].start.offset < lineStartOffset && // …and either is not ended yet…
(!childFlow.events[index2][1].end || // …or ends after it.
childFlow.events[index2][1].end.offset > lineStartOffset)
) {
return;
}
}
const indexBeforeExits = self.events.length;
let indexBeforeFlow = indexBeforeExits;
let seen;
let point3;
while (indexBeforeFlow--) {
if (self.events[indexBeforeFlow][0] === "exit" && self.events[indexBeforeFlow][1].type === "chunkFlow") {
if (seen) {
point3 = self.events[indexBeforeFlow][1].end;
break;
}
seen = true;
}
}
exitContainers(continued);
index2 = indexBeforeExits;
while (index2 < self.events.length) {
self.events[index2][1].end = __spreadValues({}, point3);
index2++;
}
splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));
self.events.length = index2;
}
}
function exitContainers(size) {
let index2 = stack.length;
while (index2-- > size) {
const entry = stack[index2];
self.containerState = entry[1];
entry[0].exit.call(self, effects);
}
stack.length = size;
}
function closeFlow() {
childFlow.write([null]);
childToken = void 0;
childFlow = void 0;
self.containerState._closeFlow = void 0;
}
}
function tokenizeContainer(effects, ok3, nok) {
return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok3, nok), "linePrefix", this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4);
}
// node_modules/micromark-util-classify-character/index.js
function classifyCharacter(code4) {
if (code4 === null || markdownLineEndingOrSpace(code4) || unicodeWhitespace(code4)) {
return 1;
}
if (unicodePunctuation(code4)) {
return 2;
}
}
// node_modules/micromark-util-resolve-all/index.js
function resolveAll(constructs2, events, context) {
const called = [];
let index2 = -1;
while (++index2 < constructs2.length) {
const resolve = constructs2[index2].resolveAll;
if (resolve && !called.includes(resolve)) {
events = resolve(events, context);
called.push(resolve);
}
}
return events;
}
// node_modules/micromark-core-commonmark/lib/attention.js
var attention = {
name: "attention",
resolveAll: resolveAllAttention,
tokenize: tokenizeAttention
};
function resolveAllAttention(events, context) {
let index2 = -1;
let open;
let group;
let text5;
let openingSequence;
let closingSequence;
let use;
let nextEvents;
let offset;
while (++index2 < events.length) {
if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
open = index2;
while (open--) {
if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && // If the markers are the same:
context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
if ((events[open][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
continue;
}
use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
const start = __spreadValues({}, events[open][1].end);
const end = __spreadValues({}, events[index2][1].start);
movePoint(start, -use);
movePoint(end, use);
openingSequence = {
type: use > 1 ? "strongSequence" : "emphasisSequence",
start,
end: __spreadValues({}, events[open][1].end)
};
closingSequence = {
type: use > 1 ? "strongSequence" : "emphasisSequence",
start: __spreadValues({}, events[index2][1].start),
end
};
text5 = {
type: use > 1 ? "strongText" : "emphasisText",
start: __spreadValues({}, events[open][1].end),
end: __spreadValues({}, events[index2][1].start)
};
group = {
type: use > 1 ? "strong" : "emphasis",
start: __spreadValues({}, openingSequence.start),
end: __spreadValues({}, closingSequence.end)
};
events[open][1].end = __spreadValues({}, openingSequence.start);
events[index2][1].start = __spreadValues({}, closingSequence.end);
nextEvents = [];
if (events[open][1].end.offset - events[open][1].start.offset) {
nextEvents = push(nextEvents, [["enter", events[open][1], context], ["exit", events[open][1], context]]);
}
nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text5, context]]);
nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index2), context));
nextEvents = push(nextEvents, [["exit", text5, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
if (events[index2][1].end.offset - events[index2][1].start.offset) {
offset = 2;
nextEvents = push(nextEvents, [["enter", events[index2][1], context], ["exit", events[index2][1], context]]);
} else {
offset = 0;
}
splice(events, open - 1, index2 - open + 3, nextEvents);
index2 = open + nextEvents.length - offset - 2;
break;
}
}
}
}
index2 = -1;
while (++index2 < events.length) {
if (events[index2][1].type === "attentionSequence") {
events[index2][1].type = "data";
}
}
return events;
}
function tokenizeAttention(effects, ok3) {
const attentionMarkers2 = this.parser.constructs.attentionMarkers.null;
const previous4 = this.previous;
const before = classifyCharacter(previous4);
let marker;
return start;
function start(code4) {
marker = code4;
effects.enter("attentionSequence");
return inside(code4);
}
function inside(code4) {
if (code4 === marker) {
effects.consume(code4);
return inside;
}
const token = effects.exit("attentionSequence");
const after = classifyCharacter(code4);
const open = !after || after === 2 && before || attentionMarkers2.includes(code4);
const close = !before || before === 2 && after || attentionMarkers2.includes(previous4);
token._open = Boolean(marker === 42 ? open : open && (before || !close));
token._close = Boolean(marker === 42 ? close : close && (after || !open));
return ok3(code4);
}
}
function movePoint(point3, offset) {
point3.column += offset;
point3.offset += offset;
point3._bufferIndex += offset;
}
// node_modules/micromark-core-commonmark/lib/autolink.js
var autolink = {
name: "autolink",
tokenize: tokenizeAutolink
};
function tokenizeAutolink(effects, ok3, nok) {
let size = 0;
return start;
function start(code4) {
effects.enter("autolink");
effects.enter("autolinkMarker");
effects.consume(code4);
effects.exit("autolinkMarker");
effects.enter("autolinkProtocol");
return open;
}
function open(code4) {
if (asciiAlpha(code4)) {
effects.consume(code4);
return schemeOrEmailAtext;
}
if (code4 === 64) {
return nok(code4);
}
return emailAtext(code4);
}
function schemeOrEmailAtext(code4) {
if (code4 === 43 || code4 === 45 || code4 === 46 || asciiAlphanumeric(code4)) {
size = 1;
return schemeInsideOrEmailAtext(code4);
}
return emailAtext(code4);
}
function schemeInsideOrEmailAtext(code4) {
if (code4 === 58) {
effects.consume(code4);
size = 0;
return urlInside;
}
if ((code4 === 43 || code4 === 45 || code4 === 46 || asciiAlphanumeric(code4)) && size++ < 32) {
effects.consume(code4);
return schemeInsideOrEmailAtext;
}
size = 0;
return emailAtext(code4);
}
function urlInside(code4) {
if (code4 === 62) {
effects.exit("autolinkProtocol");
effects.enter("autolinkMarker");
effects.consume(code4);
effects.exit("autolinkMarker");
effects.exit("autolink");
return ok3;
}
if (code4 === null || code4 === 32 || code4 === 60 || asciiControl(code4)) {
return nok(code4);
}
effects.consume(code4);
return urlInside;
}
function emailAtext(code4) {
if (code4 === 64) {
effects.consume(code4);
return emailAtSignOrDot;
}
if (asciiAtext(code4)) {
effects.consume(code4);
return emailAtext;
}
return nok(code4);
}
function emailAtSignOrDot(code4) {
return asciiAlphanumeric(code4) ? emailLabel(code4) : nok(code4);
}
function emailLabel(code4) {
if (code4 === 46) {
effects.consume(code4);
size = 0;
return emailAtSignOrDot;
}
if (code4 === 62) {
effects.exit("autolinkProtocol").type = "autolinkEmail";
effects.enter("autolinkMarker");
effects.consume(code4);
effects.exit("autolinkMarker");
effects.exit("autolink");
return ok3;
}
return emailValue(code4);
}
function emailValue(code4) {
if ((code4 === 45 || asciiAlphanumeric(code4)) && size++ < 63) {
const next = code4 === 45 ? emailValue : emailLabel;
effects.consume(code4);
return next;
}
return nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/blank-line.js
var blankLine = {
partial: true,
tokenize: tokenizeBlankLine
};
function tokenizeBlankLine(effects, ok3, nok) {
return start;
function start(code4) {
return markdownSpace(code4) ? factorySpace(effects, after, "linePrefix")(code4) : after(code4);
}
function after(code4) {
return code4 === null || markdownLineEnding(code4) ? ok3(code4) : nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/block-quote.js
var blockQuote = {
continuation: {
tokenize: tokenizeBlockQuoteContinuation
},
exit,
name: "blockQuote",
tokenize: tokenizeBlockQuoteStart
};
function tokenizeBlockQuoteStart(effects, ok3, nok) {
const self = this;
return start;
function start(code4) {
if (code4 === 62) {
const state = self.containerState;
if (!state.open) {
effects.enter("blockQuote", {
_container: true
});
state.open = true;
}
effects.enter("blockQuotePrefix");
effects.enter("blockQuoteMarker");
effects.consume(code4);
effects.exit("blockQuoteMarker");
return after;
}
return nok(code4);
}
function after(code4) {
if (markdownSpace(code4)) {
effects.enter("blockQuotePrefixWhitespace");
effects.consume(code4);
effects.exit("blockQuotePrefixWhitespace");
effects.exit("blockQuotePrefix");
return ok3;
}
effects.exit("blockQuotePrefix");
return ok3(code4);
}
}
function tokenizeBlockQuoteContinuation(effects, ok3, nok) {
const self = this;
return contStart;
function contStart(code4) {
if (markdownSpace(code4)) {
return factorySpace(effects, contBefore, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code4);
}
return contBefore(code4);
}
function contBefore(code4) {
return effects.attempt(blockQuote, ok3, nok)(code4);
}
}
function exit(effects) {
effects.exit("blockQuote");
}
// node_modules/micromark-core-commonmark/lib/character-escape.js
var characterEscape = {
name: "characterEscape",
tokenize: tokenizeCharacterEscape
};
function tokenizeCharacterEscape(effects, ok3, nok) {
return start;
function start(code4) {
effects.enter("characterEscape");
effects.enter("escapeMarker");
effects.consume(code4);
effects.exit("escapeMarker");
return inside;
}
function inside(code4) {
if (asciiPunctuation(code4)) {
effects.enter("characterEscapeValue");
effects.consume(code4);
effects.exit("characterEscapeValue");
effects.exit("characterEscape");
return ok3;
}
return nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/character-reference.js
var characterReference = {
name: "characterReference",
tokenize: tokenizeCharacterReference
};
function tokenizeCharacterReference(effects, ok3, nok) {
const self = this;
let size = 0;
let max;
let test;
return start;
function start(code4) {
effects.enter("characterReference");
effects.enter("characterReferenceMarker");
effects.consume(code4);
effects.exit("characterReferenceMarker");
return open;
}
function open(code4) {
if (code4 === 35) {
effects.enter("characterReferenceMarkerNumeric");
effects.consume(code4);
effects.exit("characterReferenceMarkerNumeric");
return numeric;
}
effects.enter("characterReferenceValue");
max = 31;
test = asciiAlphanumeric;
return value(code4);
}
function numeric(code4) {
if (code4 === 88 || code4 === 120) {
effects.enter("characterReferenceMarkerHexadecimal");
effects.consume(code4);
effects.exit("characterReferenceMarkerHexadecimal");
effects.enter("characterReferenceValue");
max = 6;
test = asciiHexDigit;
return value;
}
effects.enter("characterReferenceValue");
max = 7;
test = asciiDigit;
return value(code4);
}
function value(code4) {
if (code4 === 59 && size) {
const token = effects.exit("characterReferenceValue");
if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self.sliceSerialize(token))) {
return nok(code4);
}
effects.enter("characterReferenceMarker");
effects.consume(code4);
effects.exit("characterReferenceMarker");
effects.exit("characterReference");
return ok3;
}
if (test(code4) && size++ < max) {
effects.consume(code4);
return value;
}
return nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/code-fenced.js
var nonLazyContinuation = {
partial: true,
tokenize: tokenizeNonLazyContinuation
};
var codeFenced = {
concrete: true,
name: "codeFenced",
tokenize: tokenizeCodeFenced
};
function tokenizeCodeFenced(effects, ok3, nok) {
const self = this;
const closeStart = {
partial: true,
tokenize: tokenizeCloseStart
};
let initialPrefix = 0;
let sizeOpen = 0;
let marker;
return start;
function start(code4) {
return beforeSequenceOpen(code4);
}
function beforeSequenceOpen(code4) {
const tail = self.events[self.events.length - 1];
initialPrefix = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0;
marker = code4;
effects.enter("codeFenced");
effects.enter("codeFencedFence");
effects.enter("codeFencedFenceSequence");
return sequenceOpen(code4);
}
function sequenceOpen(code4) {
if (code4 === marker) {
sizeOpen++;
effects.consume(code4);
return sequenceOpen;
}
if (sizeOpen < 3) {
return nok(code4);
}
effects.exit("codeFencedFenceSequence");
return markdownSpace(code4) ? factorySpace(effects, infoBefore, "whitespace")(code4) : infoBefore(code4);
}
function infoBefore(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("codeFencedFence");
return self.interrupt ? ok3(code4) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code4);
}
effects.enter("codeFencedFenceInfo");
effects.enter("chunkString", {
contentType: "string"
});
return info(code4);
}
function info(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("chunkString");
effects.exit("codeFencedFenceInfo");
return infoBefore(code4);
}
if (markdownSpace(code4)) {
effects.exit("chunkString");
effects.exit("codeFencedFenceInfo");
return factorySpace(effects, metaBefore, "whitespace")(code4);
}
if (code4 === 96 && code4 === marker) {
return nok(code4);
}
effects.consume(code4);
return info;
}
function metaBefore(code4) {
if (code4 === null || markdownLineEnding(code4)) {
return infoBefore(code4);
}
effects.enter("codeFencedFenceMeta");
effects.enter("chunkString", {
contentType: "string"
});
return meta(code4);
}
function meta(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("chunkString");
effects.exit("codeFencedFenceMeta");
return infoBefore(code4);
}
if (code4 === 96 && code4 === marker) {
return nok(code4);
}
effects.consume(code4);
return meta;
}
function atNonLazyBreak(code4) {
return effects.attempt(closeStart, after, contentBefore)(code4);
}
function contentBefore(code4) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return contentStart;
}
function contentStart(code4) {
return initialPrefix > 0 && markdownSpace(code4) ? factorySpace(effects, beforeContentChunk, "linePrefix", initialPrefix + 1)(code4) : beforeContentChunk(code4);
}
function beforeContentChunk(code4) {
if (code4 === null || markdownLineEnding(code4)) {
return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code4);
}
effects.enter("codeFlowValue");
return contentChunk(code4);
}
function contentChunk(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("codeFlowValue");
return beforeContentChunk(code4);
}
effects.consume(code4);
return contentChunk;
}
function after(code4) {
effects.exit("codeFenced");
return ok3(code4);
}
function tokenizeCloseStart(effects2, ok4, nok2) {
let size = 0;
return startBefore;
function startBefore(code4) {
effects2.enter("lineEnding");
effects2.consume(code4);
effects2.exit("lineEnding");
return start2;
}
function start2(code4) {
effects2.enter("codeFencedFence");
return markdownSpace(code4) ? factorySpace(effects2, beforeSequenceClose, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code4) : beforeSequenceClose(code4);
}
function beforeSequenceClose(code4) {
if (code4 === marker) {
effects2.enter("codeFencedFenceSequence");
return sequenceClose(code4);
}
return nok2(code4);
}
function sequenceClose(code4) {
if (code4 === marker) {
size++;
effects2.consume(code4);
return sequenceClose;
}
if (size >= sizeOpen) {
effects2.exit("codeFencedFenceSequence");
return markdownSpace(code4) ? factorySpace(effects2, sequenceCloseAfter, "whitespace")(code4) : sequenceCloseAfter(code4);
}
return nok2(code4);
}
function sequenceCloseAfter(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects2.exit("codeFencedFence");
return ok4(code4);
}
return nok2(code4);
}
}
}
function tokenizeNonLazyContinuation(effects, ok3, nok) {
const self = this;
return start;
function start(code4) {
if (code4 === null) {
return nok(code4);
}
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return lineStart;
}
function lineStart(code4) {
return self.parser.lazy[self.now().line] ? nok(code4) : ok3(code4);
}
}
// node_modules/micromark-core-commonmark/lib/code-indented.js
var codeIndented = {
name: "codeIndented",
tokenize: tokenizeCodeIndented
};
var furtherStart = {
partial: true,
tokenize: tokenizeFurtherStart
};
function tokenizeCodeIndented(effects, ok3, nok) {
const self = this;
return start;
function start(code4) {
effects.enter("codeIndented");
return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code4);
}
function afterPrefix(code4) {
const tail = self.events[self.events.length - 1];
return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? atBreak(code4) : nok(code4);
}
function atBreak(code4) {
if (code4 === null) {
return after(code4);
}
if (markdownLineEnding(code4)) {
return effects.attempt(furtherStart, atBreak, after)(code4);
}
effects.enter("codeFlowValue");
return inside(code4);
}
function inside(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("codeFlowValue");
return atBreak(code4);
}
effects.consume(code4);
return inside;
}
function after(code4) {
effects.exit("codeIndented");
return ok3(code4);
}
}
function tokenizeFurtherStart(effects, ok3, nok) {
const self = this;
return furtherStart2;
function furtherStart2(code4) {
if (self.parser.lazy[self.now().line]) {
return nok(code4);
}
if (markdownLineEnding(code4)) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return furtherStart2;
}
return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code4);
}
function afterPrefix(code4) {
const tail = self.events[self.events.length - 1];
return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? ok3(code4) : markdownLineEnding(code4) ? furtherStart2(code4) : nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/code-text.js
var codeText = {
name: "codeText",
previous,
resolve: resolveCodeText,
tokenize: tokenizeCodeText
};
function resolveCodeText(events) {
let tailExitIndex = events.length - 4;
let headEnterIndex = 3;
let index2;
let enter;
if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) {
index2 = headEnterIndex;
while (++index2 < tailExitIndex) {
if (events[index2][1].type === "codeTextData") {
events[headEnterIndex][1].type = "codeTextPadding";
events[tailExitIndex][1].type = "codeTextPadding";
headEnterIndex += 2;
tailExitIndex -= 2;
break;
}
}
}
index2 = headEnterIndex - 1;
tailExitIndex++;
while (++index2 <= tailExitIndex) {
if (enter === void 0) {
if (index2 !== tailExitIndex && events[index2][1].type !== "lineEnding") {
enter = index2;
}
} else if (index2 === tailExitIndex || events[index2][1].type === "lineEnding") {
events[enter][1].type = "codeTextData";
if (index2 !== enter + 2) {
events[enter][1].end = events[index2 - 1][1].end;
events.splice(enter + 2, index2 - enter - 2);
tailExitIndex -= index2 - enter - 2;
index2 = enter + 2;
}
enter = void 0;
}
}
return events;
}
function previous(code4) {
return code4 !== 96 || this.events[this.events.length - 1][1].type === "characterEscape";
}
function tokenizeCodeText(effects, ok3, nok) {
const self = this;
let sizeOpen = 0;
let size;
let token;
return start;
function start(code4) {
effects.enter("codeText");
effects.enter("codeTextSequence");
return sequenceOpen(code4);
}
function sequenceOpen(code4) {
if (code4 === 96) {
effects.consume(code4);
sizeOpen++;
return sequenceOpen;
}
effects.exit("codeTextSequence");
return between(code4);
}
function between(code4) {
if (code4 === null) {
return nok(code4);
}
if (code4 === 32) {
effects.enter("space");
effects.consume(code4);
effects.exit("space");
return between;
}
if (code4 === 96) {
token = effects.enter("codeTextSequence");
size = 0;
return sequenceClose(code4);
}
if (markdownLineEnding(code4)) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return between;
}
effects.enter("codeTextData");
return data(code4);
}
function data(code4) {
if (code4 === null || code4 === 32 || code4 === 96 || markdownLineEnding(code4)) {
effects.exit("codeTextData");
return between(code4);
}
effects.consume(code4);
return data;
}
function sequenceClose(code4) {
if (code4 === 96) {
effects.consume(code4);
size++;
return sequenceClose;
}
if (size === sizeOpen) {
effects.exit("codeTextSequence");
effects.exit("codeText");
return ok3(code4);
}
token.type = "codeTextData";
return data(code4);
}
}
// node_modules/micromark-util-subtokenize/lib/splice-buffer.js
var SpliceBuffer = class {
/**
* @param {ReadonlyArray | null | undefined} [initial]
* Initial items (optional).
* @returns
* Splice buffer.
*/
constructor(initial) {
this.left = initial ? [...initial] : [];
this.right = [];
}
/**
* Array access;
* does not move the cursor.
*
* @param {number} index
* Index.
* @return {T}
* Item.
*/
get(index2) {
if (index2 < 0 || index2 >= this.left.length + this.right.length) {
throw new RangeError("Cannot access index `" + index2 + "` in a splice buffer of size `" + (this.left.length + this.right.length) + "`");
}
if (index2 < this.left.length)
return this.left[index2];
return this.right[this.right.length - index2 + this.left.length - 1];
}
/**
* The length of the splice buffer, one greater than the largest index in the
* array.
*/
get length() {
return this.left.length + this.right.length;
}
/**
* Remove and return `list[0]`;
* moves the cursor to `0`.
*
* @returns {T | undefined}
* Item, optional.
*/
shift() {
this.setCursor(0);
return this.right.pop();
}
/**
* Slice the buffer to get an array;
* does not move the cursor.
*
* @param {number} start
* Start.
* @param {number | null | undefined} [end]
* End (optional).
* @returns {Array}
* Array of items.
*/
slice(start, end) {
const stop = end === null || end === void 0 ? Number.POSITIVE_INFINITY : end;
if (stop < this.left.length) {
return this.left.slice(start, stop);
}
if (start > this.left.length) {
return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse();
}
return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());
}
/**
* Mimics the behavior of Array.prototype.splice() except for the change of
* interface necessary to avoid segfaults when patching in very large arrays.
*
* This operation moves cursor is moved to `start` and results in the cursor
* placed after any inserted items.
*
* @param {number} start
* Start;
* zero-based index at which to start changing the array;
* negative numbers count backwards from the end of the array and values
* that are out-of bounds are clamped to the appropriate end of the array.
* @param {number | null | undefined} [deleteCount=0]
* Delete count (default: `0`);
* maximum number of elements to delete, starting from start.
* @param {Array | null | undefined} [items=[]]
* Items to include in place of the deleted items (default: `[]`).
* @return {Array}
* Any removed items.
*/
splice(start, deleteCount, items) {
const count = deleteCount || 0;
this.setCursor(Math.trunc(start));
const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY);
if (items)
chunkedPush(this.left, items);
return removed.reverse();
}
/**
* Remove and return the highest-numbered item in the array, so
* `list[list.length - 1]`;
* Moves the cursor to `length`.
*
* @returns {T | undefined}
* Item, optional.
*/
pop() {
this.setCursor(Number.POSITIVE_INFINITY);
return this.left.pop();
}
/**
* Inserts a single item to the high-numbered side of the array;
* moves the cursor to `length`.
*
* @param {T} item
* Item.
* @returns {undefined}
* Nothing.
*/
push(item) {
this.setCursor(Number.POSITIVE_INFINITY);
this.left.push(item);
}
/**
* Inserts many items to the high-numbered side of the array.
* Moves the cursor to `length`.
*
* @param {Array} items
* Items.
* @returns {undefined}
* Nothing.
*/
pushMany(items) {
this.setCursor(Number.POSITIVE_INFINITY);
chunkedPush(this.left, items);
}
/**
* Inserts a single item to the low-numbered side of the array;
* Moves the cursor to `0`.
*
* @param {T} item
* Item.
* @returns {undefined}
* Nothing.
*/
unshift(item) {
this.setCursor(0);
this.right.push(item);
}
/**
* Inserts many items to the low-numbered side of the array;
* moves the cursor to `0`.
*
* @param {Array} items
* Items.
* @returns {undefined}
* Nothing.
*/
unshiftMany(items) {
this.setCursor(0);
chunkedPush(this.right, items.reverse());
}
/**
* Move the cursor to a specific position in the array. Requires
* time proportional to the distance moved.
*
* If `n < 0`, the cursor will end up at the beginning.
* If `n > length`, the cursor will end up at the end.
*
* @param {number} n
* Position.
* @return {undefined}
* Nothing.
*/
setCursor(n) {
if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0)
return;
if (n < this.left.length) {
const removed = this.left.splice(n, Number.POSITIVE_INFINITY);
chunkedPush(this.right, removed.reverse());
} else {
const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY);
chunkedPush(this.left, removed.reverse());
}
}
};
function chunkedPush(list3, right) {
let chunkStart = 0;
if (right.length < 1e4) {
list3.push(...right);
} else {
while (chunkStart < right.length) {
list3.push(...right.slice(chunkStart, chunkStart + 1e4));
chunkStart += 1e4;
}
}
}
// node_modules/micromark-util-subtokenize/index.js
function subtokenize(eventsArray) {
const jumps = {};
let index2 = -1;
let event;
let lineIndex;
let otherIndex;
let otherEvent;
let parameters;
let subevents;
let more;
const events = new SpliceBuffer(eventsArray);
while (++index2 < events.length) {
while (index2 in jumps) {
index2 = jumps[index2];
}
event = events.get(index2);
if (index2 && event[1].type === "chunkFlow" && events.get(index2 - 1)[1].type === "listItemPrefix") {
subevents = event[1]._tokenizer.events;
otherIndex = 0;
if (otherIndex < subevents.length && subevents[otherIndex][1].type === "lineEndingBlank") {
otherIndex += 2;
}
if (otherIndex < subevents.length && subevents[otherIndex][1].type === "content") {
while (++otherIndex < subevents.length) {
if (subevents[otherIndex][1].type === "content") {
break;
}
if (subevents[otherIndex][1].type === "chunkText") {
subevents[otherIndex][1]._isInFirstContentOfListItem = true;
otherIndex++;
}
}
}
}
if (event[0] === "enter") {
if (event[1].contentType) {
Object.assign(jumps, subcontent(events, index2));
index2 = jumps[index2];
more = true;
}
} else if (event[1]._container) {
otherIndex = index2;
lineIndex = void 0;
while (otherIndex--) {
otherEvent = events.get(otherIndex);
if (otherEvent[1].type === "lineEnding" || otherEvent[1].type === "lineEndingBlank") {
if (otherEvent[0] === "enter") {
if (lineIndex) {
events.get(lineIndex)[1].type = "lineEndingBlank";
}
otherEvent[1].type = "lineEnding";
lineIndex = otherIndex;
}
} else if (otherEvent[1].type === "linePrefix" || otherEvent[1].type === "listItemIndent") {
} else {
break;
}
}
if (lineIndex) {
event[1].end = __spreadValues({}, events.get(lineIndex)[1].start);
parameters = events.slice(lineIndex, index2);
parameters.unshift(event);
events.splice(lineIndex, index2 - lineIndex + 1, parameters);
}
}
}
splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0));
return !more;
}
function subcontent(events, eventIndex) {
const token = events.get(eventIndex)[1];
const context = events.get(eventIndex)[2];
let startPosition = eventIndex - 1;
const startPositions = [];
let tokenizer = token._tokenizer;
if (!tokenizer) {
tokenizer = context.parser[token.contentType](token.start);
if (token._contentTypeTextTrailing) {
tokenizer._contentTypeTextTrailing = true;
}
}
const childEvents = tokenizer.events;
const jumps = [];
const gaps = {};
let stream;
let previous4;
let index2 = -1;
let current = token;
let adjust = 0;
let start = 0;
const breaks = [start];
while (current) {
while (events.get(++startPosition)[1] !== current) {
}
startPositions.push(startPosition);
if (!current._tokenizer) {
stream = context.sliceStream(current);
if (!current.next) {
stream.push(null);
}
if (previous4) {
tokenizer.defineSkip(current.start);
}
if (current._isInFirstContentOfListItem) {
tokenizer._gfmTasklistFirstContentOfListItem = true;
}
tokenizer.write(stream);
if (current._isInFirstContentOfListItem) {
tokenizer._gfmTasklistFirstContentOfListItem = void 0;
}
}
previous4 = current;
current = current.next;
}
current = token;
while (++index2 < childEvents.length) {
if (
// Find a void token that includes a break.
childEvents[index2][0] === "exit" && childEvents[index2 - 1][0] === "enter" && childEvents[index2][1].type === childEvents[index2 - 1][1].type && childEvents[index2][1].start.line !== childEvents[index2][1].end.line
) {
start = index2 + 1;
breaks.push(start);
current._tokenizer = void 0;
current.previous = void 0;
current = current.next;
}
}
tokenizer.events = [];
if (current) {
current._tokenizer = void 0;
current.previous = void 0;
} else {
breaks.pop();
}
index2 = breaks.length;
while (index2--) {
const slice = childEvents.slice(breaks[index2], breaks[index2 + 1]);
const start2 = startPositions.pop();
jumps.push([start2, start2 + slice.length - 1]);
events.splice(start2, 2, slice);
}
jumps.reverse();
index2 = -1;
while (++index2 < jumps.length) {
gaps[adjust + jumps[index2][0]] = adjust + jumps[index2][1];
adjust += jumps[index2][1] - jumps[index2][0] - 1;
}
return gaps;
}
// node_modules/micromark-core-commonmark/lib/content.js
var content2 = {
resolve: resolveContent,
tokenize: tokenizeContent
};
var continuationConstruct = {
partial: true,
tokenize: tokenizeContinuation
};
function resolveContent(events) {
subtokenize(events);
return events;
}
function tokenizeContent(effects, ok3) {
let previous4;
return chunkStart;
function chunkStart(code4) {
effects.enter("content");
previous4 = effects.enter("chunkContent", {
contentType: "content"
});
return chunkInside(code4);
}
function chunkInside(code4) {
if (code4 === null) {
return contentEnd(code4);
}
if (markdownLineEnding(code4)) {
return effects.check(continuationConstruct, contentContinue, contentEnd)(code4);
}
effects.consume(code4);
return chunkInside;
}
function contentEnd(code4) {
effects.exit("chunkContent");
effects.exit("content");
return ok3(code4);
}
function contentContinue(code4) {
effects.consume(code4);
effects.exit("chunkContent");
previous4.next = effects.enter("chunkContent", {
contentType: "content",
previous: previous4
});
previous4 = previous4.next;
return chunkInside;
}
}
function tokenizeContinuation(effects, ok3, nok) {
const self = this;
return startLookahead;
function startLookahead(code4) {
effects.exit("chunkContent");
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return factorySpace(effects, prefixed, "linePrefix");
}
function prefixed(code4) {
if (code4 === null || markdownLineEnding(code4)) {
return nok(code4);
}
const tail = self.events[self.events.length - 1];
if (!self.parser.constructs.disable.null.includes("codeIndented") && tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4) {
return ok3(code4);
}
return effects.interrupt(self.parser.constructs.flow, nok, ok3)(code4);
}
}
// node_modules/micromark-factory-destination/index.js
function factoryDestination(effects, ok3, nok, type, literalType, literalMarkerType, rawType, stringType, max) {
const limit = max || Number.POSITIVE_INFINITY;
let balance = 0;
return start;
function start(code4) {
if (code4 === 60) {
effects.enter(type);
effects.enter(literalType);
effects.enter(literalMarkerType);
effects.consume(code4);
effects.exit(literalMarkerType);
return enclosedBefore;
}
if (code4 === null || code4 === 32 || code4 === 41 || asciiControl(code4)) {
return nok(code4);
}
effects.enter(type);
effects.enter(rawType);
effects.enter(stringType);
effects.enter("chunkString", {
contentType: "string"
});
return raw(code4);
}
function enclosedBefore(code4) {
if (code4 === 62) {
effects.enter(literalMarkerType);
effects.consume(code4);
effects.exit(literalMarkerType);
effects.exit(literalType);
effects.exit(type);
return ok3;
}
effects.enter(stringType);
effects.enter("chunkString", {
contentType: "string"
});
return enclosed(code4);
}
function enclosed(code4) {
if (code4 === 62) {
effects.exit("chunkString");
effects.exit(stringType);
return enclosedBefore(code4);
}
if (code4 === null || code4 === 60 || markdownLineEnding(code4)) {
return nok(code4);
}
effects.consume(code4);
return code4 === 92 ? enclosedEscape : enclosed;
}
function enclosedEscape(code4) {
if (code4 === 60 || code4 === 62 || code4 === 92) {
effects.consume(code4);
return enclosed;
}
return enclosed(code4);
}
function raw(code4) {
if (!balance && (code4 === null || code4 === 41 || markdownLineEndingOrSpace(code4))) {
effects.exit("chunkString");
effects.exit(stringType);
effects.exit(rawType);
effects.exit(type);
return ok3(code4);
}
if (balance < limit && code4 === 40) {
effects.consume(code4);
balance++;
return raw;
}
if (code4 === 41) {
effects.consume(code4);
balance--;
return raw;
}
if (code4 === null || code4 === 32 || code4 === 40 || asciiControl(code4)) {
return nok(code4);
}
effects.consume(code4);
return code4 === 92 ? rawEscape : raw;
}
function rawEscape(code4) {
if (code4 === 40 || code4 === 41 || code4 === 92) {
effects.consume(code4);
return raw;
}
return raw(code4);
}
}
// node_modules/micromark-factory-label/index.js
function factoryLabel(effects, ok3, nok, type, markerType, stringType) {
const self = this;
let size = 0;
let seen;
return start;
function start(code4) {
effects.enter(type);
effects.enter(markerType);
effects.consume(code4);
effects.exit(markerType);
effects.enter(stringType);
return atBreak;
}
function atBreak(code4) {
if (size > 999 || code4 === null || code4 === 91 || code4 === 93 && !seen || // To do: remove in the future once we’ve switched from
// `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,
// which doesn’t need this.
// Hidden footnotes hook.
/* c8 ignore next 3 */
code4 === 94 && !size && "_hiddenFootnoteSupport" in self.parser.constructs) {
return nok(code4);
}
if (code4 === 93) {
effects.exit(stringType);
effects.enter(markerType);
effects.consume(code4);
effects.exit(markerType);
effects.exit(type);
return ok3;
}
if (markdownLineEnding(code4)) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return atBreak;
}
effects.enter("chunkString", {
contentType: "string"
});
return labelInside(code4);
}
function labelInside(code4) {
if (code4 === null || code4 === 91 || code4 === 93 || markdownLineEnding(code4) || size++ > 999) {
effects.exit("chunkString");
return atBreak(code4);
}
effects.consume(code4);
if (!seen)
seen = !markdownSpace(code4);
return code4 === 92 ? labelEscape : labelInside;
}
function labelEscape(code4) {
if (code4 === 91 || code4 === 92 || code4 === 93) {
effects.consume(code4);
size++;
return labelInside;
}
return labelInside(code4);
}
}
// node_modules/micromark-factory-title/index.js
function factoryTitle(effects, ok3, nok, type, markerType, stringType) {
let marker;
return start;
function start(code4) {
if (code4 === 34 || code4 === 39 || code4 === 40) {
effects.enter(type);
effects.enter(markerType);
effects.consume(code4);
effects.exit(markerType);
marker = code4 === 40 ? 41 : code4;
return begin;
}
return nok(code4);
}
function begin(code4) {
if (code4 === marker) {
effects.enter(markerType);
effects.consume(code4);
effects.exit(markerType);
effects.exit(type);
return ok3;
}
effects.enter(stringType);
return atBreak(code4);
}
function atBreak(code4) {
if (code4 === marker) {
effects.exit(stringType);
return begin(marker);
}
if (code4 === null) {
return nok(code4);
}
if (markdownLineEnding(code4)) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return factorySpace(effects, atBreak, "linePrefix");
}
effects.enter("chunkString", {
contentType: "string"
});
return inside(code4);
}
function inside(code4) {
if (code4 === marker || code4 === null || markdownLineEnding(code4)) {
effects.exit("chunkString");
return atBreak(code4);
}
effects.consume(code4);
return code4 === 92 ? escape : inside;
}
function escape(code4) {
if (code4 === marker || code4 === 92) {
effects.consume(code4);
return inside;
}
return inside(code4);
}
}
// node_modules/micromark-factory-whitespace/index.js
function factoryWhitespace(effects, ok3) {
let seen;
return start;
function start(code4) {
if (markdownLineEnding(code4)) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
seen = true;
return start;
}
if (markdownSpace(code4)) {
return factorySpace(effects, start, seen ? "linePrefix" : "lineSuffix")(code4);
}
return ok3(code4);
}
}
// node_modules/micromark-core-commonmark/lib/definition.js
var definition = {
name: "definition",
tokenize: tokenizeDefinition
};
var titleBefore = {
partial: true,
tokenize: tokenizeTitleBefore
};
function tokenizeDefinition(effects, ok3, nok) {
const self = this;
let identifier;
return start;
function start(code4) {
effects.enter("definition");
return before(code4);
}
function before(code4) {
return factoryLabel.call(
self,
effects,
labelAfter,
// Note: we don’t need to reset the way `markdown-rs` does.
nok,
"definitionLabel",
"definitionLabelMarker",
"definitionLabelString"
)(code4);
}
function labelAfter(code4) {
identifier = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
if (code4 === 58) {
effects.enter("definitionMarker");
effects.consume(code4);
effects.exit("definitionMarker");
return markerAfter;
}
return nok(code4);
}
function markerAfter(code4) {
return markdownLineEndingOrSpace(code4) ? factoryWhitespace(effects, destinationBefore)(code4) : destinationBefore(code4);
}
function destinationBefore(code4) {
return factoryDestination(
effects,
destinationAfter,
// Note: we don’t need to reset the way `markdown-rs` does.
nok,
"definitionDestination",
"definitionDestinationLiteral",
"definitionDestinationLiteralMarker",
"definitionDestinationRaw",
"definitionDestinationString"
)(code4);
}
function destinationAfter(code4) {
return effects.attempt(titleBefore, after, after)(code4);
}
function after(code4) {
return markdownSpace(code4) ? factorySpace(effects, afterWhitespace, "whitespace")(code4) : afterWhitespace(code4);
}
function afterWhitespace(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("definition");
self.parser.defined.push(identifier);
return ok3(code4);
}
return nok(code4);
}
}
function tokenizeTitleBefore(effects, ok3, nok) {
return titleBefore2;
function titleBefore2(code4) {
return markdownLineEndingOrSpace(code4) ? factoryWhitespace(effects, beforeMarker)(code4) : nok(code4);
}
function beforeMarker(code4) {
return factoryTitle(effects, titleAfter, nok, "definitionTitle", "definitionTitleMarker", "definitionTitleString")(code4);
}
function titleAfter(code4) {
return markdownSpace(code4) ? factorySpace(effects, titleAfterOptionalWhitespace, "whitespace")(code4) : titleAfterOptionalWhitespace(code4);
}
function titleAfterOptionalWhitespace(code4) {
return code4 === null || markdownLineEnding(code4) ? ok3(code4) : nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/hard-break-escape.js
var hardBreakEscape = {
name: "hardBreakEscape",
tokenize: tokenizeHardBreakEscape
};
function tokenizeHardBreakEscape(effects, ok3, nok) {
return start;
function start(code4) {
effects.enter("hardBreakEscape");
effects.consume(code4);
return after;
}
function after(code4) {
if (markdownLineEnding(code4)) {
effects.exit("hardBreakEscape");
return ok3(code4);
}
return nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/heading-atx.js
var headingAtx = {
name: "headingAtx",
resolve: resolveHeadingAtx,
tokenize: tokenizeHeadingAtx
};
function resolveHeadingAtx(events, context) {
let contentEnd = events.length - 2;
let contentStart = 3;
let content3;
let text5;
if (events[contentStart][1].type === "whitespace") {
contentStart += 2;
}
if (contentEnd - 2 > contentStart && events[contentEnd][1].type === "whitespace") {
contentEnd -= 2;
}
if (events[contentEnd][1].type === "atxHeadingSequence" && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === "whitespace")) {
contentEnd -= contentStart + 1 === contentEnd ? 2 : 4;
}
if (contentEnd > contentStart) {
content3 = {
type: "atxHeadingText",
start: events[contentStart][1].start,
end: events[contentEnd][1].end
};
text5 = {
type: "chunkText",
start: events[contentStart][1].start,
end: events[contentEnd][1].end,
contentType: "text"
};
splice(events, contentStart, contentEnd - contentStart + 1, [["enter", content3, context], ["enter", text5, context], ["exit", text5, context], ["exit", content3, context]]);
}
return events;
}
function tokenizeHeadingAtx(effects, ok3, nok) {
let size = 0;
return start;
function start(code4) {
effects.enter("atxHeading");
return before(code4);
}
function before(code4) {
effects.enter("atxHeadingSequence");
return sequenceOpen(code4);
}
function sequenceOpen(code4) {
if (code4 === 35 && size++ < 6) {
effects.consume(code4);
return sequenceOpen;
}
if (code4 === null || markdownLineEndingOrSpace(code4)) {
effects.exit("atxHeadingSequence");
return atBreak(code4);
}
return nok(code4);
}
function atBreak(code4) {
if (code4 === 35) {
effects.enter("atxHeadingSequence");
return sequenceFurther(code4);
}
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("atxHeading");
return ok3(code4);
}
if (markdownSpace(code4)) {
return factorySpace(effects, atBreak, "whitespace")(code4);
}
effects.enter("atxHeadingText");
return data(code4);
}
function sequenceFurther(code4) {
if (code4 === 35) {
effects.consume(code4);
return sequenceFurther;
}
effects.exit("atxHeadingSequence");
return atBreak(code4);
}
function data(code4) {
if (code4 === null || code4 === 35 || markdownLineEndingOrSpace(code4)) {
effects.exit("atxHeadingText");
return atBreak(code4);
}
effects.consume(code4);
return data;
}
}
// node_modules/micromark-util-html-tag-name/index.js
var htmlBlockNames = [
"address",
"article",
"aside",
"base",
"basefont",
"blockquote",
"body",
"caption",
"center",
"col",
"colgroup",
"dd",
"details",
"dialog",
"dir",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"frame",
"frameset",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hr",
"html",
"iframe",
"legend",
"li",
"link",
"main",
"menu",
"menuitem",
"nav",
"noframes",
"ol",
"optgroup",
"option",
"p",
"param",
"search",
"section",
"summary",
"table",
"tbody",
"td",
"tfoot",
"th",
"thead",
"title",
"tr",
"track",
"ul"
];
var htmlRawNames = ["pre", "script", "style", "textarea"];
// node_modules/micromark-core-commonmark/lib/html-flow.js
var htmlFlow = {
concrete: true,
name: "htmlFlow",
resolveTo: resolveToHtmlFlow,
tokenize: tokenizeHtmlFlow
};
var blankLineBefore = {
partial: true,
tokenize: tokenizeBlankLineBefore
};
var nonLazyContinuationStart = {
partial: true,
tokenize: tokenizeNonLazyContinuationStart
};
function resolveToHtmlFlow(events) {
let index2 = events.length;
while (index2--) {
if (events[index2][0] === "enter" && events[index2][1].type === "htmlFlow") {
break;
}
}
if (index2 > 1 && events[index2 - 2][1].type === "linePrefix") {
events[index2][1].start = events[index2 - 2][1].start;
events[index2 + 1][1].start = events[index2 - 2][1].start;
events.splice(index2 - 2, 2);
}
return events;
}
function tokenizeHtmlFlow(effects, ok3, nok) {
const self = this;
let marker;
let closingTag;
let buffer;
let index2;
let markerB;
return start;
function start(code4) {
return before(code4);
}
function before(code4) {
effects.enter("htmlFlow");
effects.enter("htmlFlowData");
effects.consume(code4);
return open;
}
function open(code4) {
if (code4 === 33) {
effects.consume(code4);
return declarationOpen;
}
if (code4 === 47) {
effects.consume(code4);
closingTag = true;
return tagCloseStart;
}
if (code4 === 63) {
effects.consume(code4);
marker = 3;
return self.interrupt ? ok3 : continuationDeclarationInside;
}
if (asciiAlpha(code4)) {
effects.consume(code4);
buffer = String.fromCharCode(code4);
return tagName;
}
return nok(code4);
}
function declarationOpen(code4) {
if (code4 === 45) {
effects.consume(code4);
marker = 2;
return commentOpenInside;
}
if (code4 === 91) {
effects.consume(code4);
marker = 5;
index2 = 0;
return cdataOpenInside;
}
if (asciiAlpha(code4)) {
effects.consume(code4);
marker = 4;
return self.interrupt ? ok3 : continuationDeclarationInside;
}
return nok(code4);
}
function commentOpenInside(code4) {
if (code4 === 45) {
effects.consume(code4);
return self.interrupt ? ok3 : continuationDeclarationInside;
}
return nok(code4);
}
function cdataOpenInside(code4) {
const value = "CDATA[";
if (code4 === value.charCodeAt(index2++)) {
effects.consume(code4);
if (index2 === value.length) {
return self.interrupt ? ok3 : continuation;
}
return cdataOpenInside;
}
return nok(code4);
}
function tagCloseStart(code4) {
if (asciiAlpha(code4)) {
effects.consume(code4);
buffer = String.fromCharCode(code4);
return tagName;
}
return nok(code4);
}
function tagName(code4) {
if (code4 === null || code4 === 47 || code4 === 62 || markdownLineEndingOrSpace(code4)) {
const slash = code4 === 47;
const name = buffer.toLowerCase();
if (!slash && !closingTag && htmlRawNames.includes(name)) {
marker = 1;
return self.interrupt ? ok3(code4) : continuation(code4);
}
if (htmlBlockNames.includes(buffer.toLowerCase())) {
marker = 6;
if (slash) {
effects.consume(code4);
return basicSelfClosing;
}
return self.interrupt ? ok3(code4) : continuation(code4);
}
marker = 7;
return self.interrupt && !self.parser.lazy[self.now().line] ? nok(code4) : closingTag ? completeClosingTagAfter(code4) : completeAttributeNameBefore(code4);
}
if (code4 === 45 || asciiAlphanumeric(code4)) {
effects.consume(code4);
buffer += String.fromCharCode(code4);
return tagName;
}
return nok(code4);
}
function basicSelfClosing(code4) {
if (code4 === 62) {
effects.consume(code4);
return self.interrupt ? ok3 : continuation;
}
return nok(code4);
}
function completeClosingTagAfter(code4) {
if (markdownSpace(code4)) {
effects.consume(code4);
return completeClosingTagAfter;
}
return completeEnd(code4);
}
function completeAttributeNameBefore(code4) {
if (code4 === 47) {
effects.consume(code4);
return completeEnd;
}
if (code4 === 58 || code4 === 95 || asciiAlpha(code4)) {
effects.consume(code4);
return completeAttributeName;
}
if (markdownSpace(code4)) {
effects.consume(code4);
return completeAttributeNameBefore;
}
return completeEnd(code4);
}
function completeAttributeName(code4) {
if (code4 === 45 || code4 === 46 || code4 === 58 || code4 === 95 || asciiAlphanumeric(code4)) {
effects.consume(code4);
return completeAttributeName;
}
return completeAttributeNameAfter(code4);
}
function completeAttributeNameAfter(code4) {
if (code4 === 61) {
effects.consume(code4);
return completeAttributeValueBefore;
}
if (markdownSpace(code4)) {
effects.consume(code4);
return completeAttributeNameAfter;
}
return completeAttributeNameBefore(code4);
}
function completeAttributeValueBefore(code4) {
if (code4 === null || code4 === 60 || code4 === 61 || code4 === 62 || code4 === 96) {
return nok(code4);
}
if (code4 === 34 || code4 === 39) {
effects.consume(code4);
markerB = code4;
return completeAttributeValueQuoted;
}
if (markdownSpace(code4)) {
effects.consume(code4);
return completeAttributeValueBefore;
}
return completeAttributeValueUnquoted(code4);
}
function completeAttributeValueQuoted(code4) {
if (code4 === markerB) {
effects.consume(code4);
markerB = null;
return completeAttributeValueQuotedAfter;
}
if (code4 === null || markdownLineEnding(code4)) {
return nok(code4);
}
effects.consume(code4);
return completeAttributeValueQuoted;
}
function completeAttributeValueUnquoted(code4) {
if (code4 === null || code4 === 34 || code4 === 39 || code4 === 47 || code4 === 60 || code4 === 61 || code4 === 62 || code4 === 96 || markdownLineEndingOrSpace(code4)) {
return completeAttributeNameAfter(code4);
}
effects.consume(code4);
return completeAttributeValueUnquoted;
}
function completeAttributeValueQuotedAfter(code4) {
if (code4 === 47 || code4 === 62 || markdownSpace(code4)) {
return completeAttributeNameBefore(code4);
}
return nok(code4);
}
function completeEnd(code4) {
if (code4 === 62) {
effects.consume(code4);
return completeAfter;
}
return nok(code4);
}
function completeAfter(code4) {
if (code4 === null || markdownLineEnding(code4)) {
return continuation(code4);
}
if (markdownSpace(code4)) {
effects.consume(code4);
return completeAfter;
}
return nok(code4);
}
function continuation(code4) {
if (code4 === 45 && marker === 2) {
effects.consume(code4);
return continuationCommentInside;
}
if (code4 === 60 && marker === 1) {
effects.consume(code4);
return continuationRawTagOpen;
}
if (code4 === 62 && marker === 4) {
effects.consume(code4);
return continuationClose;
}
if (code4 === 63 && marker === 3) {
effects.consume(code4);
return continuationDeclarationInside;
}
if (code4 === 93 && marker === 5) {
effects.consume(code4);
return continuationCdataInside;
}
if (markdownLineEnding(code4) && (marker === 6 || marker === 7)) {
effects.exit("htmlFlowData");
return effects.check(blankLineBefore, continuationAfter, continuationStart)(code4);
}
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("htmlFlowData");
return continuationStart(code4);
}
effects.consume(code4);
return continuation;
}
function continuationStart(code4) {
return effects.check(nonLazyContinuationStart, continuationStartNonLazy, continuationAfter)(code4);
}
function continuationStartNonLazy(code4) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return continuationBefore;
}
function continuationBefore(code4) {
if (code4 === null || markdownLineEnding(code4)) {
return continuationStart(code4);
}
effects.enter("htmlFlowData");
return continuation(code4);
}
function continuationCommentInside(code4) {
if (code4 === 45) {
effects.consume(code4);
return continuationDeclarationInside;
}
return continuation(code4);
}
function continuationRawTagOpen(code4) {
if (code4 === 47) {
effects.consume(code4);
buffer = "";
return continuationRawEndTag;
}
return continuation(code4);
}
function continuationRawEndTag(code4) {
if (code4 === 62) {
const name = buffer.toLowerCase();
if (htmlRawNames.includes(name)) {
effects.consume(code4);
return continuationClose;
}
return continuation(code4);
}
if (asciiAlpha(code4) && buffer.length < 8) {
effects.consume(code4);
buffer += String.fromCharCode(code4);
return continuationRawEndTag;
}
return continuation(code4);
}
function continuationCdataInside(code4) {
if (code4 === 93) {
effects.consume(code4);
return continuationDeclarationInside;
}
return continuation(code4);
}
function continuationDeclarationInside(code4) {
if (code4 === 62) {
effects.consume(code4);
return continuationClose;
}
if (code4 === 45 && marker === 2) {
effects.consume(code4);
return continuationDeclarationInside;
}
return continuation(code4);
}
function continuationClose(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("htmlFlowData");
return continuationAfter(code4);
}
effects.consume(code4);
return continuationClose;
}
function continuationAfter(code4) {
effects.exit("htmlFlow");
return ok3(code4);
}
}
function tokenizeNonLazyContinuationStart(effects, ok3, nok) {
const self = this;
return start;
function start(code4) {
if (markdownLineEnding(code4)) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return after;
}
return nok(code4);
}
function after(code4) {
return self.parser.lazy[self.now().line] ? nok(code4) : ok3(code4);
}
}
function tokenizeBlankLineBefore(effects, ok3, nok) {
return start;
function start(code4) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return effects.attempt(blankLine, ok3, nok);
}
}
// node_modules/micromark-core-commonmark/lib/html-text.js
var htmlText = {
name: "htmlText",
tokenize: tokenizeHtmlText
};
function tokenizeHtmlText(effects, ok3, nok) {
const self = this;
let marker;
let index2;
let returnState;
return start;
function start(code4) {
effects.enter("htmlText");
effects.enter("htmlTextData");
effects.consume(code4);
return open;
}
function open(code4) {
if (code4 === 33) {
effects.consume(code4);
return declarationOpen;
}
if (code4 === 47) {
effects.consume(code4);
return tagCloseStart;
}
if (code4 === 63) {
effects.consume(code4);
return instruction;
}
if (asciiAlpha(code4)) {
effects.consume(code4);
return tagOpen;
}
return nok(code4);
}
function declarationOpen(code4) {
if (code4 === 45) {
effects.consume(code4);
return commentOpenInside;
}
if (code4 === 91) {
effects.consume(code4);
index2 = 0;
return cdataOpenInside;
}
if (asciiAlpha(code4)) {
effects.consume(code4);
return declaration;
}
return nok(code4);
}
function commentOpenInside(code4) {
if (code4 === 45) {
effects.consume(code4);
return commentEnd;
}
return nok(code4);
}
function comment(code4) {
if (code4 === null) {
return nok(code4);
}
if (code4 === 45) {
effects.consume(code4);
return commentClose;
}
if (markdownLineEnding(code4)) {
returnState = comment;
return lineEndingBefore(code4);
}
effects.consume(code4);
return comment;
}
function commentClose(code4) {
if (code4 === 45) {
effects.consume(code4);
return commentEnd;
}
return comment(code4);
}
function commentEnd(code4) {
return code4 === 62 ? end(code4) : code4 === 45 ? commentClose(code4) : comment(code4);
}
function cdataOpenInside(code4) {
const value = "CDATA[";
if (code4 === value.charCodeAt(index2++)) {
effects.consume(code4);
return index2 === value.length ? cdata : cdataOpenInside;
}
return nok(code4);
}
function cdata(code4) {
if (code4 === null) {
return nok(code4);
}
if (code4 === 93) {
effects.consume(code4);
return cdataClose;
}
if (markdownLineEnding(code4)) {
returnState = cdata;
return lineEndingBefore(code4);
}
effects.consume(code4);
return cdata;
}
function cdataClose(code4) {
if (code4 === 93) {
effects.consume(code4);
return cdataEnd;
}
return cdata(code4);
}
function cdataEnd(code4) {
if (code4 === 62) {
return end(code4);
}
if (code4 === 93) {
effects.consume(code4);
return cdataEnd;
}
return cdata(code4);
}
function declaration(code4) {
if (code4 === null || code4 === 62) {
return end(code4);
}
if (markdownLineEnding(code4)) {
returnState = declaration;
return lineEndingBefore(code4);
}
effects.consume(code4);
return declaration;
}
function instruction(code4) {
if (code4 === null) {
return nok(code4);
}
if (code4 === 63) {
effects.consume(code4);
return instructionClose;
}
if (markdownLineEnding(code4)) {
returnState = instruction;
return lineEndingBefore(code4);
}
effects.consume(code4);
return instruction;
}
function instructionClose(code4) {
return code4 === 62 ? end(code4) : instruction(code4);
}
function tagCloseStart(code4) {
if (asciiAlpha(code4)) {
effects.consume(code4);
return tagClose;
}
return nok(code4);
}
function tagClose(code4) {
if (code4 === 45 || asciiAlphanumeric(code4)) {
effects.consume(code4);
return tagClose;
}
return tagCloseBetween(code4);
}
function tagCloseBetween(code4) {
if (markdownLineEnding(code4)) {
returnState = tagCloseBetween;
return lineEndingBefore(code4);
}
if (markdownSpace(code4)) {
effects.consume(code4);
return tagCloseBetween;
}
return end(code4);
}
function tagOpen(code4) {
if (code4 === 45 || asciiAlphanumeric(code4)) {
effects.consume(code4);
return tagOpen;
}
if (code4 === 47 || code4 === 62 || markdownLineEndingOrSpace(code4)) {
return tagOpenBetween(code4);
}
return nok(code4);
}
function tagOpenBetween(code4) {
if (code4 === 47) {
effects.consume(code4);
return end;
}
if (code4 === 58 || code4 === 95 || asciiAlpha(code4)) {
effects.consume(code4);
return tagOpenAttributeName;
}
if (markdownLineEnding(code4)) {
returnState = tagOpenBetween;
return lineEndingBefore(code4);
}
if (markdownSpace(code4)) {
effects.consume(code4);
return tagOpenBetween;
}
return end(code4);
}
function tagOpenAttributeName(code4) {
if (code4 === 45 || code4 === 46 || code4 === 58 || code4 === 95 || asciiAlphanumeric(code4)) {
effects.consume(code4);
return tagOpenAttributeName;
}
return tagOpenAttributeNameAfter(code4);
}
function tagOpenAttributeNameAfter(code4) {
if (code4 === 61) {
effects.consume(code4);
return tagOpenAttributeValueBefore;
}
if (markdownLineEnding(code4)) {
returnState = tagOpenAttributeNameAfter;
return lineEndingBefore(code4);
}
if (markdownSpace(code4)) {
effects.consume(code4);
return tagOpenAttributeNameAfter;
}
return tagOpenBetween(code4);
}
function tagOpenAttributeValueBefore(code4) {
if (code4 === null || code4 === 60 || code4 === 61 || code4 === 62 || code4 === 96) {
return nok(code4);
}
if (code4 === 34 || code4 === 39) {
effects.consume(code4);
marker = code4;
return tagOpenAttributeValueQuoted;
}
if (markdownLineEnding(code4)) {
returnState = tagOpenAttributeValueBefore;
return lineEndingBefore(code4);
}
if (markdownSpace(code4)) {
effects.consume(code4);
return tagOpenAttributeValueBefore;
}
effects.consume(code4);
return tagOpenAttributeValueUnquoted;
}
function tagOpenAttributeValueQuoted(code4) {
if (code4 === marker) {
effects.consume(code4);
marker = void 0;
return tagOpenAttributeValueQuotedAfter;
}
if (code4 === null) {
return nok(code4);
}
if (markdownLineEnding(code4)) {
returnState = tagOpenAttributeValueQuoted;
return lineEndingBefore(code4);
}
effects.consume(code4);
return tagOpenAttributeValueQuoted;
}
function tagOpenAttributeValueUnquoted(code4) {
if (code4 === null || code4 === 34 || code4 === 39 || code4 === 60 || code4 === 61 || code4 === 96) {
return nok(code4);
}
if (code4 === 47 || code4 === 62 || markdownLineEndingOrSpace(code4)) {
return tagOpenBetween(code4);
}
effects.consume(code4);
return tagOpenAttributeValueUnquoted;
}
function tagOpenAttributeValueQuotedAfter(code4) {
if (code4 === 47 || code4 === 62 || markdownLineEndingOrSpace(code4)) {
return tagOpenBetween(code4);
}
return nok(code4);
}
function end(code4) {
if (code4 === 62) {
effects.consume(code4);
effects.exit("htmlTextData");
effects.exit("htmlText");
return ok3;
}
return nok(code4);
}
function lineEndingBefore(code4) {
effects.exit("htmlTextData");
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return lineEndingAfter;
}
function lineEndingAfter(code4) {
return markdownSpace(code4) ? factorySpace(effects, lineEndingAfterPrefix, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code4) : lineEndingAfterPrefix(code4);
}
function lineEndingAfterPrefix(code4) {
effects.enter("htmlTextData");
return returnState(code4);
}
}
// node_modules/micromark-core-commonmark/lib/label-end.js
var labelEnd = {
name: "labelEnd",
resolveAll: resolveAllLabelEnd,
resolveTo: resolveToLabelEnd,
tokenize: tokenizeLabelEnd
};
var resourceConstruct = {
tokenize: tokenizeResource
};
var referenceFullConstruct = {
tokenize: tokenizeReferenceFull
};
var referenceCollapsedConstruct = {
tokenize: tokenizeReferenceCollapsed
};
function resolveAllLabelEnd(events) {
let index2 = -1;
const newEvents = [];
while (++index2 < events.length) {
const token = events[index2][1];
newEvents.push(events[index2]);
if (token.type === "labelImage" || token.type === "labelLink" || token.type === "labelEnd") {
const offset = token.type === "labelImage" ? 4 : 2;
token.type = "data";
index2 += offset;
}
}
if (events.length !== newEvents.length) {
splice(events, 0, events.length, newEvents);
}
return events;
}
function resolveToLabelEnd(events, context) {
let index2 = events.length;
let offset = 0;
let token;
let open;
let close;
let media;
while (index2--) {
token = events[index2][1];
if (open) {
if (token.type === "link" || token.type === "labelLink" && token._inactive) {
break;
}
if (events[index2][0] === "enter" && token.type === "labelLink") {
token._inactive = true;
}
} else if (close) {
if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
open = index2;
if (token.type !== "labelLink") {
offset = 2;
break;
}
}
} else if (token.type === "labelEnd") {
close = index2;
}
}
const group = {
type: events[open][1].type === "labelLink" ? "link" : "image",
start: __spreadValues({}, events[open][1].start),
end: __spreadValues({}, events[events.length - 1][1].end)
};
const label = {
type: "label",
start: __spreadValues({}, events[open][1].start),
end: __spreadValues({}, events[close][1].end)
};
const text5 = {
type: "labelText",
start: __spreadValues({}, events[open + offset + 2][1].end),
end: __spreadValues({}, events[close - 2][1].start)
};
media = [["enter", group, context], ["enter", label, context]];
media = push(media, events.slice(open + 1, open + offset + 3));
media = push(media, [["enter", text5, context]]);
media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context));
media = push(media, [["exit", text5, context], events[close - 2], events[close - 1], ["exit", label, context]]);
media = push(media, events.slice(close + 1));
media = push(media, [["exit", group, context]]);
splice(events, open, events.length, media);
return events;
}
function tokenizeLabelEnd(effects, ok3, nok) {
const self = this;
let index2 = self.events.length;
let labelStart;
let defined;
while (index2--) {
if ((self.events[index2][1].type === "labelImage" || self.events[index2][1].type === "labelLink") && !self.events[index2][1]._balanced) {
labelStart = self.events[index2][1];
break;
}
}
return start;
function start(code4) {
if (!labelStart) {
return nok(code4);
}
if (labelStart._inactive) {
return labelEndNok(code4);
}
defined = self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize({
start: labelStart.end,
end: self.now()
})));
effects.enter("labelEnd");
effects.enter("labelMarker");
effects.consume(code4);
effects.exit("labelMarker");
effects.exit("labelEnd");
return after;
}
function after(code4) {
if (code4 === 40) {
return effects.attempt(resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok)(code4);
}
if (code4 === 91) {
return effects.attempt(referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok)(code4);
}
return defined ? labelEndOk(code4) : labelEndNok(code4);
}
function referenceNotFull(code4) {
return effects.attempt(referenceCollapsedConstruct, labelEndOk, labelEndNok)(code4);
}
function labelEndOk(code4) {
return ok3(code4);
}
function labelEndNok(code4) {
labelStart._balanced = true;
return nok(code4);
}
}
function tokenizeResource(effects, ok3, nok) {
return resourceStart;
function resourceStart(code4) {
effects.enter("resource");
effects.enter("resourceMarker");
effects.consume(code4);
effects.exit("resourceMarker");
return resourceBefore;
}
function resourceBefore(code4) {
return markdownLineEndingOrSpace(code4) ? factoryWhitespace(effects, resourceOpen)(code4) : resourceOpen(code4);
}
function resourceOpen(code4) {
if (code4 === 41) {
return resourceEnd(code4);
}
return factoryDestination(effects, resourceDestinationAfter, resourceDestinationMissing, "resourceDestination", "resourceDestinationLiteral", "resourceDestinationLiteralMarker", "resourceDestinationRaw", "resourceDestinationString", 32)(code4);
}
function resourceDestinationAfter(code4) {
return markdownLineEndingOrSpace(code4) ? factoryWhitespace(effects, resourceBetween)(code4) : resourceEnd(code4);
}
function resourceDestinationMissing(code4) {
return nok(code4);
}
function resourceBetween(code4) {
if (code4 === 34 || code4 === 39 || code4 === 40) {
return factoryTitle(effects, resourceTitleAfter, nok, "resourceTitle", "resourceTitleMarker", "resourceTitleString")(code4);
}
return resourceEnd(code4);
}
function resourceTitleAfter(code4) {
return markdownLineEndingOrSpace(code4) ? factoryWhitespace(effects, resourceEnd)(code4) : resourceEnd(code4);
}
function resourceEnd(code4) {
if (code4 === 41) {
effects.enter("resourceMarker");
effects.consume(code4);
effects.exit("resourceMarker");
effects.exit("resource");
return ok3;
}
return nok(code4);
}
}
function tokenizeReferenceFull(effects, ok3, nok) {
const self = this;
return referenceFull;
function referenceFull(code4) {
return factoryLabel.call(self, effects, referenceFullAfter, referenceFullMissing, "reference", "referenceMarker", "referenceString")(code4);
}
function referenceFullAfter(code4) {
return self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1))) ? ok3(code4) : nok(code4);
}
function referenceFullMissing(code4) {
return nok(code4);
}
}
function tokenizeReferenceCollapsed(effects, ok3, nok) {
return referenceCollapsedStart;
function referenceCollapsedStart(code4) {
effects.enter("reference");
effects.enter("referenceMarker");
effects.consume(code4);
effects.exit("referenceMarker");
return referenceCollapsedOpen;
}
function referenceCollapsedOpen(code4) {
if (code4 === 93) {
effects.enter("referenceMarker");
effects.consume(code4);
effects.exit("referenceMarker");
effects.exit("reference");
return ok3;
}
return nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/label-start-image.js
var labelStartImage = {
name: "labelStartImage",
resolveAll: labelEnd.resolveAll,
tokenize: tokenizeLabelStartImage
};
function tokenizeLabelStartImage(effects, ok3, nok) {
const self = this;
return start;
function start(code4) {
effects.enter("labelImage");
effects.enter("labelImageMarker");
effects.consume(code4);
effects.exit("labelImageMarker");
return open;
}
function open(code4) {
if (code4 === 91) {
effects.enter("labelMarker");
effects.consume(code4);
effects.exit("labelMarker");
effects.exit("labelImage");
return after;
}
return nok(code4);
}
function after(code4) {
return code4 === 94 && "_hiddenFootnoteSupport" in self.parser.constructs ? nok(code4) : ok3(code4);
}
}
// node_modules/micromark-core-commonmark/lib/label-start-link.js
var labelStartLink = {
name: "labelStartLink",
resolveAll: labelEnd.resolveAll,
tokenize: tokenizeLabelStartLink
};
function tokenizeLabelStartLink(effects, ok3, nok) {
const self = this;
return start;
function start(code4) {
effects.enter("labelLink");
effects.enter("labelMarker");
effects.consume(code4);
effects.exit("labelMarker");
effects.exit("labelLink");
return after;
}
function after(code4) {
return code4 === 94 && "_hiddenFootnoteSupport" in self.parser.constructs ? nok(code4) : ok3(code4);
}
}
// node_modules/micromark-core-commonmark/lib/line-ending.js
var lineEnding = {
name: "lineEnding",
tokenize: tokenizeLineEnding
};
function tokenizeLineEnding(effects, ok3) {
return start;
function start(code4) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return factorySpace(effects, ok3, "linePrefix");
}
}
// node_modules/micromark-core-commonmark/lib/thematic-break.js
var thematicBreak = {
name: "thematicBreak",
tokenize: tokenizeThematicBreak
};
function tokenizeThematicBreak(effects, ok3, nok) {
let size = 0;
let marker;
return start;
function start(code4) {
effects.enter("thematicBreak");
return before(code4);
}
function before(code4) {
marker = code4;
return atBreak(code4);
}
function atBreak(code4) {
if (code4 === marker) {
effects.enter("thematicBreakSequence");
return sequence(code4);
}
if (size >= 3 && (code4 === null || markdownLineEnding(code4))) {
effects.exit("thematicBreak");
return ok3(code4);
}
return nok(code4);
}
function sequence(code4) {
if (code4 === marker) {
effects.consume(code4);
size++;
return sequence;
}
effects.exit("thematicBreakSequence");
return markdownSpace(code4) ? factorySpace(effects, atBreak, "whitespace")(code4) : atBreak(code4);
}
}
// node_modules/micromark-core-commonmark/lib/list.js
var list = {
continuation: {
tokenize: tokenizeListContinuation
},
exit: tokenizeListEnd,
name: "list",
tokenize: tokenizeListStart
};
var listItemPrefixWhitespaceConstruct = {
partial: true,
tokenize: tokenizeListItemPrefixWhitespace
};
var indentConstruct = {
partial: true,
tokenize: tokenizeIndent
};
function tokenizeListStart(effects, ok3, nok) {
const self = this;
const tail = self.events[self.events.length - 1];
let initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0;
let size = 0;
return start;
function start(code4) {
const kind = self.containerState.type || (code4 === 42 || code4 === 43 || code4 === 45 ? "listUnordered" : "listOrdered");
if (kind === "listUnordered" ? !self.containerState.marker || code4 === self.containerState.marker : asciiDigit(code4)) {
if (!self.containerState.type) {
self.containerState.type = kind;
effects.enter(kind, {
_container: true
});
}
if (kind === "listUnordered") {
effects.enter("listItemPrefix");
return code4 === 42 || code4 === 45 ? effects.check(thematicBreak, nok, atMarker)(code4) : atMarker(code4);
}
if (!self.interrupt || code4 === 49) {
effects.enter("listItemPrefix");
effects.enter("listItemValue");
return inside(code4);
}
}
return nok(code4);
}
function inside(code4) {
if (asciiDigit(code4) && ++size < 10) {
effects.consume(code4);
return inside;
}
if ((!self.interrupt || size < 2) && (self.containerState.marker ? code4 === self.containerState.marker : code4 === 41 || code4 === 46)) {
effects.exit("listItemValue");
return atMarker(code4);
}
return nok(code4);
}
function atMarker(code4) {
effects.enter("listItemMarker");
effects.consume(code4);
effects.exit("listItemMarker");
self.containerState.marker = self.containerState.marker || code4;
return effects.check(
blankLine,
// Can’t be empty when interrupting.
self.interrupt ? nok : onBlank,
effects.attempt(listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix)
);
}
function onBlank(code4) {
self.containerState.initialBlankLine = true;
initialSize++;
return endOfPrefix(code4);
}
function otherPrefix(code4) {
if (markdownSpace(code4)) {
effects.enter("listItemPrefixWhitespace");
effects.consume(code4);
effects.exit("listItemPrefixWhitespace");
return endOfPrefix;
}
return nok(code4);
}
function endOfPrefix(code4) {
self.containerState.size = initialSize + self.sliceSerialize(effects.exit("listItemPrefix"), true).length;
return ok3(code4);
}
}
function tokenizeListContinuation(effects, ok3, nok) {
const self = this;
self.containerState._closeFlow = void 0;
return effects.check(blankLine, onBlank, notBlank);
function onBlank(code4) {
self.containerState.furtherBlankLines = self.containerState.furtherBlankLines || self.containerState.initialBlankLine;
return factorySpace(effects, ok3, "listItemIndent", self.containerState.size + 1)(code4);
}
function notBlank(code4) {
if (self.containerState.furtherBlankLines || !markdownSpace(code4)) {
self.containerState.furtherBlankLines = void 0;
self.containerState.initialBlankLine = void 0;
return notInCurrentItem(code4);
}
self.containerState.furtherBlankLines = void 0;
self.containerState.initialBlankLine = void 0;
return effects.attempt(indentConstruct, ok3, notInCurrentItem)(code4);
}
function notInCurrentItem(code4) {
self.containerState._closeFlow = true;
self.interrupt = void 0;
return factorySpace(effects, effects.attempt(list, ok3, nok), "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code4);
}
}
function tokenizeIndent(effects, ok3, nok) {
const self = this;
return factorySpace(effects, afterPrefix, "listItemIndent", self.containerState.size + 1);
function afterPrefix(code4) {
const tail = self.events[self.events.length - 1];
return tail && tail[1].type === "listItemIndent" && tail[2].sliceSerialize(tail[1], true).length === self.containerState.size ? ok3(code4) : nok(code4);
}
}
function tokenizeListEnd(effects) {
effects.exit(this.containerState.type);
}
function tokenizeListItemPrefixWhitespace(effects, ok3, nok) {
const self = this;
return factorySpace(effects, afterPrefix, "listItemPrefixWhitespace", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 + 1);
function afterPrefix(code4) {
const tail = self.events[self.events.length - 1];
return !markdownSpace(code4) && tail && tail[1].type === "listItemPrefixWhitespace" ? ok3(code4) : nok(code4);
}
}
// node_modules/micromark-core-commonmark/lib/setext-underline.js
var setextUnderline = {
name: "setextUnderline",
resolveTo: resolveToSetextUnderline,
tokenize: tokenizeSetextUnderline
};
function resolveToSetextUnderline(events, context) {
let index2 = events.length;
let content3;
let text5;
let definition3;
while (index2--) {
if (events[index2][0] === "enter") {
if (events[index2][1].type === "content") {
content3 = index2;
break;
}
if (events[index2][1].type === "paragraph") {
text5 = index2;
}
} else {
if (events[index2][1].type === "content") {
events.splice(index2, 1);
}
if (!definition3 && events[index2][1].type === "definition") {
definition3 = index2;
}
}
}
const heading2 = {
type: "setextHeading",
start: __spreadValues({}, events[content3][1].start),
end: __spreadValues({}, events[events.length - 1][1].end)
};
events[text5][1].type = "setextHeadingText";
if (definition3) {
events.splice(text5, 0, ["enter", heading2, context]);
events.splice(definition3 + 1, 0, ["exit", events[content3][1], context]);
events[content3][1].end = __spreadValues({}, events[definition3][1].end);
} else {
events[content3][1] = heading2;
}
events.push(["exit", heading2, context]);
return events;
}
function tokenizeSetextUnderline(effects, ok3, nok) {
const self = this;
let marker;
return start;
function start(code4) {
let index2 = self.events.length;
let paragraph3;
while (index2--) {
if (self.events[index2][1].type !== "lineEnding" && self.events[index2][1].type !== "linePrefix" && self.events[index2][1].type !== "content") {
paragraph3 = self.events[index2][1].type === "paragraph";
break;
}
}
if (!self.parser.lazy[self.now().line] && (self.interrupt || paragraph3)) {
effects.enter("setextHeadingLine");
marker = code4;
return before(code4);
}
return nok(code4);
}
function before(code4) {
effects.enter("setextHeadingLineSequence");
return inside(code4);
}
function inside(code4) {
if (code4 === marker) {
effects.consume(code4);
return inside;
}
effects.exit("setextHeadingLineSequence");
return markdownSpace(code4) ? factorySpace(effects, after, "lineSuffix")(code4) : after(code4);
}
function after(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("setextHeadingLine");
return ok3(code4);
}
return nok(code4);
}
}
// node_modules/micromark/lib/initialize/flow.js
var flow = {
tokenize: initializeFlow
};
function initializeFlow(effects) {
const self = this;
const initial = effects.attempt(
// Try to parse a blank line.
blankLine,
atBlankEnding,
// Try to parse initial flow (essentially, only code).
effects.attempt(this.parser.constructs.flowInitial, afterConstruct, factorySpace(effects, effects.attempt(this.parser.constructs.flow, afterConstruct, effects.attempt(content2, afterConstruct)), "linePrefix"))
);
return initial;
function atBlankEnding(code4) {
if (code4 === null) {
effects.consume(code4);
return;
}
effects.enter("lineEndingBlank");
effects.consume(code4);
effects.exit("lineEndingBlank");
self.currentConstruct = void 0;
return initial;
}
function afterConstruct(code4) {
if (code4 === null) {
effects.consume(code4);
return;
}
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
self.currentConstruct = void 0;
return initial;
}
}
// node_modules/micromark/lib/initialize/text.js
var resolver = {
resolveAll: createResolver()
};
var string = initializeFactory("string");
var text = initializeFactory("text");
function initializeFactory(field) {
return {
resolveAll: createResolver(field === "text" ? resolveAllLineSuffixes : void 0),
tokenize: initializeText
};
function initializeText(effects) {
const self = this;
const constructs2 = this.parser.constructs[field];
const text5 = effects.attempt(constructs2, start, notText);
return start;
function start(code4) {
return atBreak(code4) ? text5(code4) : notText(code4);
}
function notText(code4) {
if (code4 === null) {
effects.consume(code4);
return;
}
effects.enter("data");
effects.consume(code4);
return data;
}
function data(code4) {
if (atBreak(code4)) {
effects.exit("data");
return text5(code4);
}
effects.consume(code4);
return data;
}
function atBreak(code4) {
if (code4 === null) {
return true;
}
const list3 = constructs2[code4];
let index2 = -1;
if (list3) {
while (++index2 < list3.length) {
const item = list3[index2];
if (!item.previous || item.previous.call(self, self.previous)) {
return true;
}
}
}
return false;
}
}
}
function createResolver(extraResolver) {
return resolveAllText;
function resolveAllText(events, context) {
let index2 = -1;
let enter;
while (++index2 <= events.length) {
if (enter === void 0) {
if (events[index2] && events[index2][1].type === "data") {
enter = index2;
index2++;
}
} else if (!events[index2] || events[index2][1].type !== "data") {
if (index2 !== enter + 2) {
events[enter][1].end = events[index2 - 1][1].end;
events.splice(enter + 2, index2 - enter - 2);
index2 = enter + 2;
}
enter = void 0;
}
}
return extraResolver ? extraResolver(events, context) : events;
}
}
function resolveAllLineSuffixes(events, context) {
let eventIndex = 0;
while (++eventIndex <= events.length) {
if ((eventIndex === events.length || events[eventIndex][1].type === "lineEnding") && events[eventIndex - 1][1].type === "data") {
const data = events[eventIndex - 1][1];
const chunks = context.sliceStream(data);
let index2 = chunks.length;
let bufferIndex = -1;
let size = 0;
let tabs;
while (index2--) {
const chunk = chunks[index2];
if (typeof chunk === "string") {
bufferIndex = chunk.length;
while (chunk.charCodeAt(bufferIndex - 1) === 32) {
size++;
bufferIndex--;
}
if (bufferIndex)
break;
bufferIndex = -1;
} else if (chunk === -2) {
tabs = true;
size++;
} else if (chunk === -1) {
} else {
index2++;
break;
}
}
if (context._contentTypeTextTrailing && eventIndex === events.length) {
size = 0;
}
if (size) {
const token = {
type: eventIndex === events.length || tabs || size < 2 ? "lineSuffix" : "hardBreakTrailing",
start: {
_bufferIndex: index2 ? bufferIndex : data.start._bufferIndex + bufferIndex,
_index: data.start._index + index2,
line: data.end.line,
column: data.end.column - size,
offset: data.end.offset - size
},
end: __spreadValues({}, data.end)
};
data.end = __spreadValues({}, token.start);
if (data.start.offset === data.end.offset) {
Object.assign(data, token);
} else {
events.splice(eventIndex, 0, ["enter", token, context], ["exit", token, context]);
eventIndex += 2;
}
}
eventIndex++;
}
}
return events;
}
// node_modules/micromark/lib/constructs.js
var constructs_exports = {};
__export(constructs_exports, {
attentionMarkers: () => attentionMarkers,
contentInitial: () => contentInitial,
disable: () => disable,
document: () => document3,
flow: () => flow2,
flowInitial: () => flowInitial,
insideSpan: () => insideSpan,
string: () => string2,
text: () => text2
});
var document3 = {
[42]: list,
[43]: list,
[45]: list,
[48]: list,
[49]: list,
[50]: list,
[51]: list,
[52]: list,
[53]: list,
[54]: list,
[55]: list,
[56]: list,
[57]: list,
[62]: blockQuote
};
var contentInitial = {
[91]: definition
};
var flowInitial = {
[-2]: codeIndented,
[-1]: codeIndented,
[32]: codeIndented
};
var flow2 = {
[35]: headingAtx,
[42]: thematicBreak,
[45]: [setextUnderline, thematicBreak],
[60]: htmlFlow,
[61]: setextUnderline,
[95]: thematicBreak,
[96]: codeFenced,
[126]: codeFenced
};
var string2 = {
[38]: characterReference,
[92]: characterEscape
};
var text2 = {
[-5]: lineEnding,
[-4]: lineEnding,
[-3]: lineEnding,
[33]: labelStartImage,
[38]: characterReference,
[42]: attention,
[60]: [autolink, htmlText],
[91]: labelStartLink,
[92]: [hardBreakEscape, characterEscape],
[93]: labelEnd,
[95]: attention,
[96]: codeText
};
var insideSpan = {
null: [attention, resolver]
};
var attentionMarkers = {
null: [42, 95]
};
var disable = {
null: []
};
// node_modules/micromark/lib/create-tokenizer.js
function createTokenizer(parser, initialize, from) {
let point3 = {
_bufferIndex: -1,
_index: 0,
line: from && from.line || 1,
column: from && from.column || 1,
offset: from && from.offset || 0
};
const columnStart = {};
const resolveAllConstructs = [];
let chunks = [];
let stack = [];
let consumed = true;
const effects = {
attempt: constructFactory(onsuccessfulconstruct),
check: constructFactory(onsuccessfulcheck),
consume,
enter,
exit: exit3,
interrupt: constructFactory(onsuccessfulcheck, {
interrupt: true
})
};
const context = {
code: null,
containerState: {},
defineSkip,
events: [],
now,
parser,
previous: null,
sliceSerialize,
sliceStream,
write
};
let state = initialize.tokenize.call(context, effects);
let expectedCode;
if (initialize.resolveAll) {
resolveAllConstructs.push(initialize);
}
return context;
function write(slice) {
chunks = push(chunks, slice);
main();
if (chunks[chunks.length - 1] !== null) {
return [];
}
addResult(initialize, 0);
context.events = resolveAll(resolveAllConstructs, context.events, context);
return context.events;
}
function sliceSerialize(token, expandTabs) {
return serializeChunks(sliceStream(token), expandTabs);
}
function sliceStream(token) {
return sliceChunks(chunks, token);
}
function now() {
const {
_bufferIndex,
_index,
line,
column,
offset
} = point3;
return {
_bufferIndex,
_index,
line,
column,
offset
};
}
function defineSkip(value) {
columnStart[value.line] = value.column;
accountForPotentialSkip();
}
function main() {
let chunkIndex;
while (point3._index < chunks.length) {
const chunk = chunks[point3._index];
if (typeof chunk === "string") {
chunkIndex = point3._index;
if (point3._bufferIndex < 0) {
point3._bufferIndex = 0;
}
while (point3._index === chunkIndex && point3._bufferIndex < chunk.length) {
go(chunk.charCodeAt(point3._bufferIndex));
}
} else {
go(chunk);
}
}
}
function go(code4) {
consumed = void 0;
expectedCode = code4;
state = state(code4);
}
function consume(code4) {
if (markdownLineEnding(code4)) {
point3.line++;
point3.column = 1;
point3.offset += code4 === -3 ? 2 : 1;
accountForPotentialSkip();
} else if (code4 !== -1) {
point3.column++;
point3.offset++;
}
if (point3._bufferIndex < 0) {
point3._index++;
} else {
point3._bufferIndex++;
if (point3._bufferIndex === // Points w/ non-negative `_bufferIndex` reference
// strings.
/** @type {string} */
chunks[point3._index].length) {
point3._bufferIndex = -1;
point3._index++;
}
}
context.previous = code4;
consumed = true;
}
function enter(type, fields) {
const token = fields || {};
token.type = type;
token.start = now();
context.events.push(["enter", token, context]);
stack.push(token);
return token;
}
function exit3(type) {
const token = stack.pop();
token.end = now();
context.events.push(["exit", token, context]);
return token;
}
function onsuccessfulconstruct(construct, info) {
addResult(construct, info.from);
}
function onsuccessfulcheck(_, info) {
info.restore();
}
function constructFactory(onreturn, fields) {
return hook;
function hook(constructs2, returnState, bogusState) {
let listOfConstructs;
let constructIndex;
let currentConstruct;
let info;
return Array.isArray(constructs2) ? (
/* c8 ignore next 1 */
handleListOfConstructs(constructs2)
) : "tokenize" in constructs2 ? (
// Looks like a construct.
handleListOfConstructs([
/** @type {Construct} */
constructs2
])
) : handleMapOfConstructs(constructs2);
function handleMapOfConstructs(map3) {
return start;
function start(code4) {
const left = code4 !== null && map3[code4];
const all2 = code4 !== null && map3.null;
const list3 = [
// To do: add more extension tests.
/* c8 ignore next 2 */
...Array.isArray(left) ? left : left ? [left] : [],
...Array.isArray(all2) ? all2 : all2 ? [all2] : []
];
return handleListOfConstructs(list3)(code4);
}
}
function handleListOfConstructs(list3) {
listOfConstructs = list3;
constructIndex = 0;
if (list3.length === 0) {
return bogusState;
}
return handleConstruct(list3[constructIndex]);
}
function handleConstruct(construct) {
return start;
function start(code4) {
info = store();
currentConstruct = construct;
if (!construct.partial) {
context.currentConstruct = construct;
}
if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) {
return nok(code4);
}
return construct.tokenize.call(
// If we do have fields, create an object w/ `context` as its
// prototype.
// This allows a “live binding”, which is needed for `interrupt`.
fields ? Object.assign(Object.create(context), fields) : context,
effects,
ok3,
nok
)(code4);
}
}
function ok3(code4) {
consumed = true;
onreturn(currentConstruct, info);
return returnState;
}
function nok(code4) {
consumed = true;
info.restore();
if (++constructIndex < listOfConstructs.length) {
return handleConstruct(listOfConstructs[constructIndex]);
}
return bogusState;
}
}
}
function addResult(construct, from2) {
if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {
resolveAllConstructs.push(construct);
}
if (construct.resolve) {
splice(context.events, from2, context.events.length - from2, construct.resolve(context.events.slice(from2), context));
}
if (construct.resolveTo) {
context.events = construct.resolveTo(context.events, context);
}
}
function store() {
const startPoint = now();
const startPrevious = context.previous;
const startCurrentConstruct = context.currentConstruct;
const startEventsIndex = context.events.length;
const startStack = Array.from(stack);
return {
from: startEventsIndex,
restore
};
function restore() {
point3 = startPoint;
context.previous = startPrevious;
context.currentConstruct = startCurrentConstruct;
context.events.length = startEventsIndex;
stack = startStack;
accountForPotentialSkip();
}
}
function accountForPotentialSkip() {
if (point3.line in columnStart && point3.column < 2) {
point3.column = columnStart[point3.line];
point3.offset += columnStart[point3.line] - 1;
}
}
}
function sliceChunks(chunks, token) {
const startIndex = token.start._index;
const startBufferIndex = token.start._bufferIndex;
const endIndex = token.end._index;
const endBufferIndex = token.end._bufferIndex;
let view;
if (startIndex === endIndex) {
view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];
} else {
view = chunks.slice(startIndex, endIndex);
if (startBufferIndex > -1) {
const head = view[0];
if (typeof head === "string") {
view[0] = head.slice(startBufferIndex);
} else {
view.shift();
}
}
if (endBufferIndex > 0) {
view.push(chunks[endIndex].slice(0, endBufferIndex));
}
}
return view;
}
function serializeChunks(chunks, expandTabs) {
let index2 = -1;
const result = [];
let atTab;
while (++index2 < chunks.length) {
const chunk = chunks[index2];
let value;
if (typeof chunk === "string") {
value = chunk;
} else
switch (chunk) {
case -5: {
value = "\r";
break;
}
case -4: {
value = "\n";
break;
}
case -3: {
value = "\r\n";
break;
}
case -2: {
value = expandTabs ? " " : " ";
break;
}
case -1: {
if (!expandTabs && atTab)
continue;
value = " ";
break;
}
default: {
value = String.fromCharCode(chunk);
}
}
atTab = chunk === -2;
result.push(value);
}
return result.join("");
}
// node_modules/micromark/lib/parse.js
function parse(options) {
const settings = options || {};
const constructs2 = (
/** @type {FullNormalizedExtension} */
combineExtensions([constructs_exports, ...settings.extensions || []])
);
const parser = {
constructs: constructs2,
content: create(content),
defined: [],
document: create(document2),
flow: create(flow),
lazy: {},
string: create(string),
text: create(text)
};
return parser;
function create(initial) {
return creator;
function creator(from) {
return createTokenizer(parser, initial, from);
}
}
}
// node_modules/micromark/lib/postprocess.js
function postprocess(events) {
while (!subtokenize(events)) {
}
return events;
}
// node_modules/micromark/lib/preprocess.js
var search = /[\0\t\n\r]/g;
function preprocess() {
let column = 1;
let buffer = "";
let start = true;
let atCarriageReturn;
return preprocessor;
function preprocessor(value, encoding, end) {
const chunks = [];
let match;
let next;
let startPosition;
let endPosition;
let code4;
value = buffer + (typeof value === "string" ? value.toString() : new TextDecoder(encoding || void 0).decode(value));
startPosition = 0;
buffer = "";
if (start) {
if (value.charCodeAt(0) === 65279) {
startPosition++;
}
start = void 0;
}
while (startPosition < value.length) {
search.lastIndex = startPosition;
match = search.exec(value);
endPosition = match && match.index !== void 0 ? match.index : value.length;
code4 = value.charCodeAt(endPosition);
if (!match) {
buffer = value.slice(startPosition);
break;
}
if (code4 === 10 && startPosition === endPosition && atCarriageReturn) {
chunks.push(-3);
atCarriageReturn = void 0;
} else {
if (atCarriageReturn) {
chunks.push(-5);
atCarriageReturn = void 0;
}
if (startPosition < endPosition) {
chunks.push(value.slice(startPosition, endPosition));
column += endPosition - startPosition;
}
switch (code4) {
case 0: {
chunks.push(65533);
column++;
break;
}
case 9: {
next = Math.ceil(column / 4) * 4;
chunks.push(-2);
while (column++ < next)
chunks.push(-1);
break;
}
case 10: {
chunks.push(-4);
column = 1;
break;
}
default: {
atCarriageReturn = true;
column = 1;
}
}
}
startPosition = endPosition + 1;
}
if (end) {
if (atCarriageReturn)
chunks.push(-5);
if (buffer)
chunks.push(buffer);
chunks.push(null);
}
return chunks;
}
}
// node_modules/micromark-util-decode-string/index.js
var characterEscapeOrReference = /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;
function decodeString(value) {
return value.replace(characterEscapeOrReference, decode);
}
function decode($0, $1, $2) {
if ($1) {
return $1;
}
const head = $2.charCodeAt(0);
if (head === 35) {
const head2 = $2.charCodeAt(1);
const hex = head2 === 120 || head2 === 88;
return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10);
}
return decodeNamedCharacterReference($2) || $0;
}
// node_modules/mdast-util-from-markdown/lib/index.js
var own2 = {}.hasOwnProperty;
function fromMarkdown(value, encoding, options) {
if (encoding && typeof encoding === "object") {
options = encoding;
encoding = void 0;
}
return compiler(options)(postprocess(parse(options).document().write(preprocess()(value, encoding, true))));
}
function compiler(options) {
const config = {
transforms: [],
canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"],
enter: {
autolink: opener(link2),
autolinkProtocol: onenterdata,
autolinkEmail: onenterdata,
atxHeading: opener(heading2),
blockQuote: opener(blockQuote2),
characterEscape: onenterdata,
characterReference: onenterdata,
codeFenced: opener(codeFlow),
codeFencedFenceInfo: buffer,
codeFencedFenceMeta: buffer,
codeIndented: opener(codeFlow, buffer),
codeText: opener(codeText2, buffer),
codeTextData: onenterdata,
data: onenterdata,
codeFlowValue: onenterdata,
definition: opener(definition3),
definitionDestinationString: buffer,
definitionLabelString: buffer,
definitionTitleString: buffer,
emphasis: opener(emphasis2),
hardBreakEscape: opener(hardBreak2),
hardBreakTrailing: opener(hardBreak2),
htmlFlow: opener(html2, buffer),
htmlFlowData: onenterdata,
htmlText: opener(html2, buffer),
htmlTextData: onenterdata,
image: opener(image3),
label: buffer,
link: opener(link2),
listItem: opener(listItem2),
listItemValue: onenterlistitemvalue,
listOrdered: opener(list3, onenterlistordered),
listUnordered: opener(list3),
paragraph: opener(paragraph3),
reference: onenterreference,
referenceString: buffer,
resourceDestinationString: buffer,
resourceTitleString: buffer,
setextHeading: opener(heading2),
strong: opener(strong2),
thematicBreak: opener(thematicBreak3)
},
exit: {
atxHeading: closer(),
atxHeadingSequence: onexitatxheadingsequence,
autolink: closer(),
autolinkEmail: onexitautolinkemail,
autolinkProtocol: onexitautolinkprotocol,
blockQuote: closer(),
characterEscapeValue: onexitdata,
characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,
characterReferenceMarkerNumeric: onexitcharacterreferencemarker,
characterReferenceValue: onexitcharacterreferencevalue,
characterReference: onexitcharacterreference,
codeFenced: closer(onexitcodefenced),
codeFencedFence: onexitcodefencedfence,
codeFencedFenceInfo: onexitcodefencedfenceinfo,
codeFencedFenceMeta: onexitcodefencedfencemeta,
codeFlowValue: onexitdata,
codeIndented: closer(onexitcodeindented),
codeText: closer(onexitcodetext),
codeTextData: onexitdata,
data: onexitdata,
definition: closer(),
definitionDestinationString: onexitdefinitiondestinationstring,
definitionLabelString: onexitdefinitionlabelstring,
definitionTitleString: onexitdefinitiontitlestring,
emphasis: closer(),
hardBreakEscape: closer(onexithardbreak),
hardBreakTrailing: closer(onexithardbreak),
htmlFlow: closer(onexithtmlflow),
htmlFlowData: onexitdata,
htmlText: closer(onexithtmltext),
htmlTextData: onexitdata,
image: closer(onexitimage),
label: onexitlabel,
labelText: onexitlabeltext,
lineEnding: onexitlineending,
link: closer(onexitlink),
listItem: closer(),
listOrdered: closer(),
listUnordered: closer(),
paragraph: closer(),
referenceString: onexitreferencestring,
resourceDestinationString: onexitresourcedestinationstring,
resourceTitleString: onexitresourcetitlestring,
resource: onexitresource,
setextHeading: closer(onexitsetextheading),
setextHeadingLineSequence: onexitsetextheadinglinesequence,
setextHeadingText: onexitsetextheadingtext,
strong: closer(),
thematicBreak: closer()
}
};
configure(config, (options || {}).mdastExtensions || []);
const data = {};
return compile;
function compile(events) {
let tree = {
type: "root",
children: []
};
const context = {
stack: [tree],
tokenStack: [],
config,
enter,
exit: exit3,
buffer,
resume,
data
};
const listStack = [];
let index2 = -1;
while (++index2 < events.length) {
if (events[index2][1].type === "listOrdered" || events[index2][1].type === "listUnordered") {
if (events[index2][0] === "enter") {
listStack.push(index2);
} else {
const tail = listStack.pop();
index2 = prepareList(events, tail, index2);
}
}
}
index2 = -1;
while (++index2 < events.length) {
const handler = config[events[index2][0]];
if (own2.call(handler, events[index2][1].type)) {
handler[events[index2][1].type].call(Object.assign({
sliceSerialize: events[index2][2].sliceSerialize
}, context), events[index2][1]);
}
}
if (context.tokenStack.length > 0) {
const tail = context.tokenStack[context.tokenStack.length - 1];
const handler = tail[1] || defaultOnError;
handler.call(context, void 0, tail[0]);
}
tree.position = {
start: point2(events.length > 0 ? events[0][1].start : {
line: 1,
column: 1,
offset: 0
}),
end: point2(events.length > 0 ? events[events.length - 2][1].end : {
line: 1,
column: 1,
offset: 0
})
};
index2 = -1;
while (++index2 < config.transforms.length) {
tree = config.transforms[index2](tree) || tree;
}
return tree;
}
function prepareList(events, start, length) {
let index2 = start - 1;
let containerBalance = -1;
let listSpread = false;
let listItem3;
let lineIndex;
let firstBlankLineIndex;
let atMarker;
while (++index2 <= length) {
const event = events[index2];
switch (event[1].type) {
case "listUnordered":
case "listOrdered":
case "blockQuote": {
if (event[0] === "enter") {
containerBalance++;
} else {
containerBalance--;
}
atMarker = void 0;
break;
}
case "lineEndingBlank": {
if (event[0] === "enter") {
if (listItem3 && !atMarker && !containerBalance && !firstBlankLineIndex) {
firstBlankLineIndex = index2;
}
atMarker = void 0;
}
break;
}
case "linePrefix":
case "listItemValue":
case "listItemMarker":
case "listItemPrefix":
case "listItemPrefixWhitespace": {
break;
}
default: {
atMarker = void 0;
}
}
if (!containerBalance && event[0] === "enter" && event[1].type === "listItemPrefix" || containerBalance === -1 && event[0] === "exit" && (event[1].type === "listUnordered" || event[1].type === "listOrdered")) {
if (listItem3) {
let tailIndex = index2;
lineIndex = void 0;
while (tailIndex--) {
const tailEvent = events[tailIndex];
if (tailEvent[1].type === "lineEnding" || tailEvent[1].type === "lineEndingBlank") {
if (tailEvent[0] === "exit")
continue;
if (lineIndex) {
events[lineIndex][1].type = "lineEndingBlank";
listSpread = true;
}
tailEvent[1].type = "lineEnding";
lineIndex = tailIndex;
} else if (tailEvent[1].type === "linePrefix" || tailEvent[1].type === "blockQuotePrefix" || tailEvent[1].type === "blockQuotePrefixWhitespace" || tailEvent[1].type === "blockQuoteMarker" || tailEvent[1].type === "listItemIndent") {
} else {
break;
}
}
if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) {
listItem3._spread = true;
}
listItem3.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event[1].end);
events.splice(lineIndex || index2, 0, ["exit", listItem3, event[2]]);
index2++;
length++;
}
if (event[1].type === "listItemPrefix") {
const item = {
type: "listItem",
_spread: false,
start: Object.assign({}, event[1].start),
// @ts-expect-error: we’ll add `end` in a second.
end: void 0
};
listItem3 = item;
events.splice(index2, 0, ["enter", item, event[2]]);
index2++;
length++;
firstBlankLineIndex = void 0;
atMarker = true;
}
}
}
events[start][1]._spread = listSpread;
return length;
}
function opener(create, and) {
return open;
function open(token) {
enter.call(this, create(token), token);
if (and)
and.call(this, token);
}
}
function buffer() {
this.stack.push({
type: "fragment",
children: []
});
}
function enter(node2, token, errorHandler) {
const parent = this.stack[this.stack.length - 1];
const siblings = parent.children;
siblings.push(node2);
this.stack.push(node2);
this.tokenStack.push([token, errorHandler || void 0]);
node2.position = {
start: point2(token.start),
// @ts-expect-error: `end` will be patched later.
end: void 0
};
}
function closer(and) {
return close;
function close(token) {
if (and)
and.call(this, token);
exit3.call(this, token);
}
}
function exit3(token, onExitError) {
const node2 = this.stack.pop();
const open = this.tokenStack.pop();
if (!open) {
throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
start: token.start,
end: token.end
}) + "): it\u2019s not open");
} else if (open[0].type !== token.type) {
if (onExitError) {
onExitError.call(this, token, open[0]);
} else {
const handler = open[1] || defaultOnError;
handler.call(this, token, open[0]);
}
}
node2.position.end = point2(token.end);
}
function resume() {
return toString(this.stack.pop());
}
function onenterlistordered() {
this.data.expectingFirstListItemValue = true;
}
function onenterlistitemvalue(token) {
if (this.data.expectingFirstListItemValue) {
const ancestor = this.stack[this.stack.length - 2];
ancestor.start = Number.parseInt(this.sliceSerialize(token), 10);
this.data.expectingFirstListItemValue = void 0;
}
}
function onexitcodefencedfenceinfo() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.lang = data2;
}
function onexitcodefencedfencemeta() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.meta = data2;
}
function onexitcodefencedfence() {
if (this.data.flowCodeInside)
return;
this.buffer();
this.data.flowCodeInside = true;
}
function onexitcodefenced() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.value = data2.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, "");
this.data.flowCodeInside = void 0;
}
function onexitcodeindented() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.value = data2.replace(/(\r?\n|\r)$/g, "");
}
function onexitdefinitionlabelstring(token) {
const label = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.label = label;
node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
}
function onexitdefinitiontitlestring() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.title = data2;
}
function onexitdefinitiondestinationstring() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.url = data2;
}
function onexitatxheadingsequence(token) {
const node2 = this.stack[this.stack.length - 1];
if (!node2.depth) {
const depth = this.sliceSerialize(token).length;
node2.depth = depth;
}
}
function onexitsetextheadingtext() {
this.data.setextHeadingSlurpLineEnding = true;
}
function onexitsetextheadinglinesequence(token) {
const node2 = this.stack[this.stack.length - 1];
node2.depth = this.sliceSerialize(token).codePointAt(0) === 61 ? 1 : 2;
}
function onexitsetextheading() {
this.data.setextHeadingSlurpLineEnding = void 0;
}
function onenterdata(token) {
const node2 = this.stack[this.stack.length - 1];
const siblings = node2.children;
let tail = siblings[siblings.length - 1];
if (!tail || tail.type !== "text") {
tail = text5();
tail.position = {
start: point2(token.start),
// @ts-expect-error: we’ll add `end` later.
end: void 0
};
siblings.push(tail);
}
this.stack.push(tail);
}
function onexitdata(token) {
const tail = this.stack.pop();
tail.value += this.sliceSerialize(token);
tail.position.end = point2(token.end);
}
function onexitlineending(token) {
const context = this.stack[this.stack.length - 1];
if (this.data.atHardBreak) {
const tail = context.children[context.children.length - 1];
tail.position.end = point2(token.end);
this.data.atHardBreak = void 0;
return;
}
if (!this.data.setextHeadingSlurpLineEnding && config.canContainEols.includes(context.type)) {
onenterdata.call(this, token);
onexitdata.call(this, token);
}
}
function onexithardbreak() {
this.data.atHardBreak = true;
}
function onexithtmlflow() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.value = data2;
}
function onexithtmltext() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.value = data2;
}
function onexitcodetext() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.value = data2;
}
function onexitlink() {
const node2 = this.stack[this.stack.length - 1];
if (this.data.inReference) {
const referenceType = this.data.referenceType || "shortcut";
node2.type += "Reference";
node2.referenceType = referenceType;
delete node2.url;
delete node2.title;
} else {
delete node2.identifier;
delete node2.label;
}
this.data.referenceType = void 0;
}
function onexitimage() {
const node2 = this.stack[this.stack.length - 1];
if (this.data.inReference) {
const referenceType = this.data.referenceType || "shortcut";
node2.type += "Reference";
node2.referenceType = referenceType;
delete node2.url;
delete node2.title;
} else {
delete node2.identifier;
delete node2.label;
}
this.data.referenceType = void 0;
}
function onexitlabeltext(token) {
const string3 = this.sliceSerialize(token);
const ancestor = this.stack[this.stack.length - 2];
ancestor.label = decodeString(string3);
ancestor.identifier = normalizeIdentifier(string3).toLowerCase();
}
function onexitlabel() {
const fragment = this.stack[this.stack.length - 1];
const value = this.resume();
const node2 = this.stack[this.stack.length - 1];
this.data.inReference = true;
if (node2.type === "link") {
const children = fragment.children;
node2.children = children;
} else {
node2.alt = value;
}
}
function onexitresourcedestinationstring() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.url = data2;
}
function onexitresourcetitlestring() {
const data2 = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.title = data2;
}
function onexitresource() {
this.data.inReference = void 0;
}
function onenterreference() {
this.data.referenceType = "collapsed";
}
function onexitreferencestring(token) {
const label = this.resume();
const node2 = this.stack[this.stack.length - 1];
node2.label = label;
node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
this.data.referenceType = "full";
}
function onexitcharacterreferencemarker(token) {
this.data.characterReferenceType = token.type;
}
function onexitcharacterreferencevalue(token) {
const data2 = this.sliceSerialize(token);
const type = this.data.characterReferenceType;
let value;
if (type) {
value = decodeNumericCharacterReference(data2, type === "characterReferenceMarkerNumeric" ? 10 : 16);
this.data.characterReferenceType = void 0;
} else {
const result = decodeNamedCharacterReference(data2);
value = result;
}
const tail = this.stack[this.stack.length - 1];
tail.value += value;
}
function onexitcharacterreference(token) {
const tail = this.stack.pop();
tail.position.end = point2(token.end);
}
function onexitautolinkprotocol(token) {
onexitdata.call(this, token);
const node2 = this.stack[this.stack.length - 1];
node2.url = this.sliceSerialize(token);
}
function onexitautolinkemail(token) {
onexitdata.call(this, token);
const node2 = this.stack[this.stack.length - 1];
node2.url = "mailto:" + this.sliceSerialize(token);
}
function blockQuote2() {
return {
type: "blockquote",
children: []
};
}
function codeFlow() {
return {
type: "code",
lang: null,
meta: null,
value: ""
};
}
function codeText2() {
return {
type: "inlineCode",
value: ""
};
}
function definition3() {
return {
type: "definition",
identifier: "",
label: null,
title: null,
url: ""
};
}
function emphasis2() {
return {
type: "emphasis",
children: []
};
}
function heading2() {
return {
type: "heading",
// @ts-expect-error `depth` will be set later.
depth: 0,
children: []
};
}
function hardBreak2() {
return {
type: "break"
};
}
function html2() {
return {
type: "html",
value: ""
};
}
function image3() {
return {
type: "image",
title: null,
url: "",
alt: null
};
}
function link2() {
return {
type: "link",
title: null,
url: "",
children: []
};
}
function list3(token) {
return {
type: "list",
ordered: token.type === "listOrdered",
start: null,
spread: token._spread,
children: []
};
}
function listItem2(token) {
return {
type: "listItem",
spread: token._spread,
checked: null,
children: []
};
}
function paragraph3() {
return {
type: "paragraph",
children: []
};
}
function strong2() {
return {
type: "strong",
children: []
};
}
function text5() {
return {
type: "text",
value: ""
};
}
function thematicBreak3() {
return {
type: "thematicBreak"
};
}
}
function point2(d) {
return {
line: d.line,
column: d.column,
offset: d.offset
};
}
function configure(combined, extensions) {
let index2 = -1;
while (++index2 < extensions.length) {
const value = extensions[index2];
if (Array.isArray(value)) {
configure(combined, value);
} else {
extension(combined, value);
}
}
}
function extension(combined, extension2) {
let key;
for (key in extension2) {
if (own2.call(extension2, key)) {
switch (key) {
case "canContainEols": {
const right = extension2[key];
if (right) {
combined[key].push(...right);
}
break;
}
case "transforms": {
const right = extension2[key];
if (right) {
combined[key].push(...right);
}
break;
}
case "enter":
case "exit": {
const right = extension2[key];
if (right) {
Object.assign(combined[key], right);
}
break;
}
}
}
}
}
function defaultOnError(left, right) {
if (left) {
throw new Error("Cannot close `" + left.type + "` (" + stringifyPosition({
start: left.start,
end: left.end
}) + "): a different token (`" + right.type + "`, " + stringifyPosition({
start: right.start,
end: right.end
}) + ") is open");
} else {
throw new Error("Cannot close document, a token (`" + right.type + "`, " + stringifyPosition({
start: right.start,
end: right.end
}) + ") is still open");
}
}
// node_modules/remark-parse/lib/index.js
function remarkParse(options) {
const self = this;
self.parser = parser;
function parser(doc) {
return fromMarkdown(doc, __spreadProps(__spreadValues(__spreadValues({}, self.data("settings")), options), {
// Note: these options are not in the readme.
// The goal is for them to be set by plugins on `data` instead of being
// passed by users.
extensions: self.data("micromarkExtensions") || [],
mdastExtensions: self.data("fromMarkdownExtensions") || []
}));
}
}
// node_modules/@jxpeng98/martian/build/src/notion/common.js
var LIMITS = {
PAYLOAD_BLOCKS: 1e3,
RICH_TEXT_ARRAYS: 100,
RICH_TEXT: {
TEXT_CONTENT: 2e3,
LINK_URL: 1e3,
EQUATION_EXPRESSION: 1e3
}
};
function isValidURL(url) {
if (!url || url === "") {
return false;
}
const urlRegex = /^https?:\/\/.+/i;
return urlRegex.test(url);
}
function richText(content3, options = {}) {
const annotations = __spreadValues({
bold: false,
strikethrough: false,
underline: false,
italic: false,
code: false,
color: "default"
}, options.annotations || {});
if (options.type === "equation")
return {
type: "equation",
annotations,
equation: {
expression: content3
}
};
else
return {
type: "text",
annotations,
text: {
content: content3,
link: isValidURL(options.url) ? {
type: "url",
url: options.url
} : void 0
}
};
}
var SUPPORTED_CODE_BLOCK_LANGUAGES = [
"abap",
"arduino",
"bash",
"basic",
"c",
"clojure",
"coffeescript",
"c++",
"c#",
"css",
"dart",
"diff",
"docker",
"elixir",
"elm",
"erlang",
"flow",
"fortran",
"f#",
"gherkin",
"glsl",
"go",
"graphql",
"groovy",
"haskell",
"html",
"java",
"javascript",
"json",
"julia",
"kotlin",
"latex",
"less",
"lisp",
"livescript",
"lua",
"makefile",
"markdown",
"markup",
"matlab",
"mermaid",
"nix",
"objective-c",
"ocaml",
"pascal",
"perl",
"php",
"plain text",
"powershell",
"prolog",
"protobuf",
"python",
"r",
"reason",
"ruby",
"rust",
"sass",
"scala",
"scheme",
"scss",
"shell",
"sql",
"swift",
"typescript",
"vb.net",
"verilog",
"vhdl",
"visual basic",
"webassembly",
"xml",
"yaml",
"java/c/c++/c#"
];
function isSupportedCodeLang(lang) {
return SUPPORTED_CODE_BLOCK_LANGUAGES.includes(lang);
}
var SUPPORTED_GFM_ALERT_TYPES = [
"NOTE",
"TIP",
"IMPORTANT",
"WARNING",
"CAUTION",
"INFO",
"TODO",
"SUCCESS",
"QUESTION",
"FAILURE",
"DANGER",
"BUG",
"EXAMPLE",
"QUOTE"
];
function isGfmAlertType(type) {
return SUPPORTED_GFM_ALERT_TYPES.includes(type);
}
var GFM_ALERT_MAP = {
NOTE: { emoji: "\u{1F4D8}", color: "blue_background", title: "Note" },
TIP: { emoji: "\u{1F4A1}", color: "green_background", title: "Tip" },
IMPORTANT: { emoji: "\u261D\uFE0F", color: "purple_background", title: "Important" },
WARNING: { emoji: "\u26A0\uFE0F", color: "yellow_background", title: "Warning" },
CAUTION: { emoji: "\u2757", color: "red_background", title: "Caution" },
INFO: { emoji: "\u{1F4D8}", color: "blue_background", title: "Info" },
TODO: { emoji: "\u{1F4DD}", color: "gray_background", title: "To-do" },
SUCCESS: { emoji: "\u2705", color: "green_background", title: "Success" },
QUESTION: { emoji: "\u2753", color: "purple_background", title: "Question" },
FAILURE: { emoji: "\u274C", color: "red_background", title: "Failure" },
DANGER: { emoji: "\u2620\uFE0F", color: "red_background", title: "Danger" },
BUG: { emoji: "\u{1F41B}", color: "orange_background", title: "Bug" },
EXAMPLE: { emoji: "\u{1F9EA}", color: "blue_background", title: "Example" },
QUOTE: { emoji: "\u{1F4AC}", color: "gray_background", title: "Quote" }
};
var SUPPORTED_EMOJI_COLOR_MAP = {
"\u{1F44D}": "green_background",
"\u{1F4D8}": "blue_background",
"\u{1F6A7}": "yellow_background",
"\u2757": "red_background",
"\u{1F4A1}": "green_background",
"\u261D\uFE0F": "purple_background",
"\u{1F4DD}": "gray_background",
"\u2705": "green_background",
"\u2753": "purple_background",
"\u26A0\uFE0F": "yellow_background",
"\u274C": "red_background",
"\u2620\uFE0F": "red_background",
"\u{1F41B}": "orange_background",
"\u{1F9EA}": "blue_background",
"\u{1F4AC}": "gray_background"
};
// node_modules/@jxpeng98/martian/build/src/notion/languageMap.json
var languageMap_default = {
abap: "abap",
sh: "shell",
"shell-script": "shell",
bash: "shell",
zsh: "shell",
envrc: "shell",
basic: "basic",
c_cpp: "c++",
clojure: "clojure",
coffee: "coffeescript",
"coffee-script": "coffeescript",
cpp: "c++",
csharp: "c#",
cake: "c#",
cakescript: "c#",
css: "css",
dart: "dart",
diff: "diff",
udiff: "diff",
dockerfile: "docker",
containerfile: "docker",
elixir: "elixir",
elm: "elm",
erlang: "erlang",
fortran: "fortran",
fsharp: "f#",
gherkin: "gherkin",
cucumber: "gherkin",
glsl: "glsl",
golang: "go",
graphqlschema: "graphql",
groovy: "groovy",
haskell: "haskell",
html: "html",
xhtml: "html",
java: "java/c/c++/c#",
javascript: "javascript",
js: "javascript",
node: "javascript",
json: "json",
geojson: "json",
jsonl: "json",
sarif: "json",
topojson: "json",
julia: "julia",
kotlin: "kotlin",
tex: "latex",
latex: "latex",
less: "less",
"less-css": "less",
lisp: "webassembly",
livescript: "livescript",
"live-script": "livescript",
ls: "livescript",
lua: "lua",
makefile: "makefile",
bsdmake: "makefile",
make: "makefile",
mf: "makefile",
markdown: "markdown",
md: "markdown",
pandoc: "markdown",
matlab: "matlab",
octave: "matlab",
nix: "nix",
nixos: "nix",
objectivec: "objective-c",
"obj-c": "objective-c",
objc: "objective-c",
ocaml: "ocaml",
pascal: "pascal",
delphi: "pascal",
objectpascal: "pascal",
perl: "perl",
cperl: "perl",
php: "php",
inc: "php",
powershell: "powershell",
posh: "powershell",
pwsh: "powershell",
prolog: "prolog",
protobuf: "protobuf",
proto: "protobuf",
"protocol buffers": "protobuf",
python: "python",
python3: "python",
rusthon: "python",
r: "r",
rscript: "r",
splus: "r",
rust: "rust",
ruby: "ruby",
jruby: "ruby",
macruby: "ruby",
rake: "ruby",
rb: "ruby",
rbx: "ruby",
rs: "rust",
sass: "sass",
scala: "scala",
scheme: "scheme",
scss: "scss",
sql: "sql",
swift: "swift",
typescript: "typescript",
ts: "typescript",
text: "vb.net",
"visual basic": "vb.net",
vbnet: "vb.net",
"vb .net": "vb.net",
"vb.net": "vb.net",
verilog: "verilog",
vhdl: "vhdl",
wast: "webassembly",
wasm: "webassembly",
xml: "xml",
rss: "xml",
xsd: "xml",
wsdl: "xml",
yaml: "yaml",
yml: "yaml"
};
// node_modules/@jxpeng98/martian/build/src/notion/blocks.js
function divider() {
return {
object: "block",
type: "divider",
divider: {}
};
}
function paragraph(text5) {
return {
object: "block",
type: "paragraph",
paragraph: {
rich_text: text5
}
};
}
function code(text5, lang = "plain text") {
text5.forEach((item) => {
if (item.type === "text" && item.annotations) {
delete item.annotations;
}
});
return {
object: "block",
type: "code",
code: {
rich_text: text5,
language: lang
}
};
}
function blockquote(text5 = [], children = []) {
return {
object: "block",
type: "quote",
quote: {
// By setting an empty rich text we prevent the "Empty quote" line from showing up at all
rich_text: text5.length ? text5 : [richText("")],
// @ts-expect-error Typings are not perfect
children
}
};
}
function image(url) {
return {
object: "block",
type: "image",
image: {
type: "external",
external: {
url
}
}
};
}
function table_of_contents() {
return {
object: "block",
type: "table_of_contents",
table_of_contents: {}
};
}
function headingOne(text5) {
return {
object: "block",
type: "heading_1",
heading_1: {
rich_text: text5
}
};
}
function headingTwo(text5) {
return {
object: "block",
type: "heading_2",
heading_2: {
rich_text: text5
}
};
}
function headingThree(text5) {
return {
object: "block",
type: "heading_3",
heading_3: {
rich_text: text5
}
};
}
function bulletedListItem(text5, children = []) {
return {
object: "block",
type: "bulleted_list_item",
bulleted_list_item: {
rich_text: text5,
children: children.length ? children : void 0
}
};
}
function numberedListItem(text5, children = []) {
return {
object: "block",
type: "numbered_list_item",
numbered_list_item: {
rich_text: text5,
children: children.length ? children : void 0
}
};
}
function toDo(checked, text5, children = []) {
return {
object: "block",
type: "to_do",
to_do: {
rich_text: text5,
checked,
children: children.length ? children : void 0
}
};
}
function table(children, tableWidth) {
return {
object: "block",
type: "table",
table: {
table_width: tableWidth,
has_column_header: true,
children: (children == null ? void 0 : children.length) ? children : []
}
};
}
function tableRow(cells = []) {
return {
object: "block",
type: "table_row",
table_row: {
cells: cells.length ? cells : []
}
};
}
function equation(value) {
return {
type: "equation",
equation: {
expression: value
}
};
}
function callout(text5 = [], emoji = "\u{1F44D}", color2 = "default", children = []) {
return {
object: "block",
type: "callout",
callout: {
rich_text: text5.length ? text5 : [richText("")],
icon: {
type: "emoji",
emoji
},
// @ts-expect-error See https://github.com/makenotion/notion-sdk-js/issues/575
children,
color: color2
}
};
}
// node_modules/@jxpeng98/martian/build/src/notion/index.js
function parseCodeLanguage(lang) {
return lang ? languageMap_default[lang.toLowerCase()] : void 0;
}
function parseCalloutEmoji(text5) {
if (!text5)
return null;
const firstLine = text5.split("\n")[0];
const match = firstLine.match(/^([\p{Emoji_Presentation}\p{Extended_Pictographic}][\u{FE0F}\u{FE0E}]?).*$/u);
if (!match)
return null;
const emoji = match[1];
return {
emoji,
color: SUPPORTED_EMOJI_COLOR_MAP[emoji] || "default"
};
}
// node_modules/@jxpeng98/martian/build/src/parser/internal.js
var import_path = __toESM(require("path"), 1);
var import_url = require("url");
function ensureLength(text5, copy) {
const chunks = text5.match(/[^]{1,2000}/g) || [];
return chunks.flatMap((item) => richText(item, copy));
}
function ensureCodeBlockLanguage(lang) {
if (lang) {
lang = lang.toLowerCase();
return isSupportedCodeLang(lang) ? lang : parseCodeLanguage(lang);
}
return void 0;
}
function parseInline(element2, options) {
var _a;
const copy = {
annotations: __spreadValues({}, (_a = options == null ? void 0 : options.annotations) != null ? _a : {}),
url: options == null ? void 0 : options.url
};
switch (element2.type) {
case "text":
return ensureLength(element2.value, copy);
case "delete":
copy.annotations.strikethrough = true;
return element2.children.flatMap((child) => parseInline(child, copy));
case "emphasis":
copy.annotations.italic = true;
return element2.children.flatMap((child) => parseInline(child, copy));
case "strong":
copy.annotations.bold = true;
return element2.children.flatMap((child) => parseInline(child, copy));
case "link":
copy.url = element2.url;
return element2.children.flatMap((child) => parseInline(child, copy));
case "inlineCode":
copy.annotations.code = true;
return [richText(element2.value, copy)];
case "inlineMath":
return [richText(element2.value, __spreadProps(__spreadValues({}, copy), { type: "equation" }))];
default:
return [];
}
}
function parseImage(image3, options) {
var _a;
const allowedTypes = [
".png",
".jpg",
".jpeg",
".gif",
".tif",
".tiff",
".bmp",
".svg",
".heic",
".webp"
];
function dealWithError() {
return paragraph([richText(image3.url)]);
}
try {
if ((_a = options.strictImageUrls) != null ? _a : true) {
const parsedUrl = new import_url.URL(image3.url);
const fileType = import_path.default.extname(parsedUrl.pathname);
if (allowedTypes.includes(fileType)) {
return image(image3.url);
} else {
return dealWithError();
}
} else {
return image(image3.url);
}
} catch (error) {
return dealWithError();
}
}
function parseParagraph(element2, options) {
const mightBeToc = element2.children.length > 2 && element2.children[0].type === "text" && element2.children[0].value === "[[" && element2.children[1].type === "emphasis";
if (mightBeToc) {
const emphasisItem = element2.children[1];
const emphasisTextItem = emphasisItem.children[0];
if (emphasisTextItem.value === "TOC") {
return [table_of_contents()];
}
}
const images = [];
const paragraphs = [];
let currentParagraph = [];
const pushParagraph = () => {
if (currentParagraph.length > 0) {
paragraphs.push(currentParagraph);
currentParagraph = [];
}
};
element2.children.forEach((item) => {
if (item.type === "image") {
images.push(parseImage(item, options));
return;
}
if (item.type === "break") {
pushParagraph();
return;
}
const richText2 = parseInline(item);
currentParagraph.push(...richText2);
});
pushParagraph();
return [...paragraphs.map(paragraph), ...images];
}
function parseBlockquote(element2, options) {
const firstChild = element2.children[0];
const firstTextNode = (firstChild == null ? void 0 : firstChild.type) === "paragraph" ? firstChild.children[0] : null;
if ((firstTextNode == null ? void 0 : firstTextNode.type) === "text") {
const parseSubsequentBlocks = () => element2.children.length > 1 ? element2.children.slice(1).flatMap((child) => parseNode(child, options)) : [];
const firstLine = firstTextNode.value.split("\n")[0];
const gfmMatch = firstLine.match(/^(?:\\\[|\[)!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]$/);
if (gfmMatch) {
const alertType = gfmMatch[1].toUpperCase();
if (isGfmAlertType(alertType)) {
const alertConfig = GFM_ALERT_MAP[alertType];
const displayType = alertConfig.title;
const children2 = [];
const contentLines = firstTextNode.value.split("\n").slice(1);
if (contentLines.length > 0) {
children2.push(paragraph(parseInline({
type: "text",
value: contentLines.join("\n")
})));
}
children2.push(...parseSubsequentBlocks());
return callout([richText(displayType)], alertConfig.emoji, alertConfig.color, children2);
}
}
const obsidianMatch = firstTextNode.value.match(/^\[!([a-z]+)\](?:[+-])?\s*/i);
if (obsidianMatch) {
const calloutType = obsidianMatch[1].toUpperCase();
if (isGfmAlertType(calloutType)) {
const calloutConfig = GFM_ALERT_MAP[calloutType];
const paragraph3 = firstChild;
const remainingFirstText = firstTextNode.value.slice(obsidianMatch[0].length);
const richText2 = paragraph3.children.flatMap((child) => child === firstTextNode ? remainingFirstText ? parseInline({ type: "text", value: remainingFirstText }) : [] : parseInline(child));
if (richText2.length === 0) {
richText2.push(richText(calloutConfig.title));
}
return callout(richText2, calloutConfig.emoji, calloutConfig.color, parseSubsequentBlocks());
}
}
if (options.enableEmojiCallouts) {
const emojiData = parseCalloutEmoji(firstTextNode.value);
if (emojiData) {
const paragraph3 = firstChild;
const textWithoutEmoji = firstTextNode.value.slice(emojiData.emoji.length).trimStart();
const richText2 = paragraph3.children.flatMap((child) => child === firstTextNode ? textWithoutEmoji ? parseInline({ type: "text", value: textWithoutEmoji }) : [] : parseInline(child));
return callout(richText2, emojiData.emoji, emojiData.color, parseSubsequentBlocks());
}
}
}
const children = element2.children.flatMap((child) => parseNode(child, options));
return blockquote([], children);
}
function parseHeading(element2) {
const text5 = element2.children.flatMap((child) => parseInline(child));
switch (element2.depth) {
case 1:
return headingOne(text5);
case 2:
return headingTwo(text5);
default:
return headingThree(text5);
}
}
function parseCode(element2) {
const text5 = ensureLength(element2.value);
const lang = ensureCodeBlockLanguage(element2.lang);
return code(text5, lang);
}
function parseList(element2, options) {
return element2.children.flatMap((item) => {
const paragraph3 = item.children.shift();
if (paragraph3 === void 0 || paragraph3.type !== "paragraph") {
return [];
}
const text5 = paragraph3.children.flatMap((child) => parseInline(child));
const parsedChildren = item.children.flatMap((child) => parseNode(child, options));
if (element2.start !== null && element2.start !== void 0) {
return [numberedListItem(text5, parsedChildren)];
} else if (item.checked !== null && item.checked !== void 0) {
return [toDo(item.checked, text5, parsedChildren)];
} else {
return [bulletedListItem(text5, parsedChildren)];
}
});
}
function parseTableCell(node2) {
return node2.children.flatMap((child) => parseInline(child));
}
function parseTableRow(node2) {
const cells = node2.children.map((child) => parseTableCell(child));
return tableRow(cells);
}
function parseTable(node2) {
var _a;
const tableWidth = ((_a = node2.children) == null ? void 0 : _a.length) ? node2.children[0].children.length : 0;
const tableRows = node2.children.map((child) => parseTableRow(child));
return [table(tableRows, tableWidth)];
}
function parseMath(node2) {
const textWithKatexNewlines = node2.value.split("\n").join("\n");
return equation(textWithKatexNewlines);
}
function parseNode(node2, options) {
switch (node2.type) {
case "heading":
return [parseHeading(node2)];
case "paragraph":
return parseParagraph(node2, options);
case "code":
return [parseCode(node2)];
case "blockquote":
return [parseBlockquote(node2, options)];
case "list":
return parseList(node2, options);
case "table":
return parseTable(node2);
case "math":
return [parseMath(node2)];
case "thematicBreak":
return [divider()];
default:
return [];
}
}
function parseBlocks(root2, options) {
var _a, _b, _c, _d;
const parsed = root2.children.flatMap((item) => parseNode(item, options || {}));
const truncate = !!((_b = (_a = options == null ? void 0 : options.notionLimits) == null ? void 0 : _a.truncate) != null ? _b : true), limitCallback = (_d = (_c = options == null ? void 0 : options.notionLimits) == null ? void 0 : _c.onError) != null ? _d : () => {
};
if (parsed.length > LIMITS.PAYLOAD_BLOCKS)
limitCallback(new Error(`Resulting blocks array exceeds Notion limit (${LIMITS.PAYLOAD_BLOCKS})`));
return truncate ? parsed.slice(0, LIMITS.PAYLOAD_BLOCKS) : parsed;
}
// node_modules/ccount/index.js
function ccount(value, character) {
const source = String(value);
if (typeof character !== "string") {
throw new TypeError("Expected character");
}
let count = 0;
let index2 = source.indexOf(character);
while (index2 !== -1) {
count++;
index2 = source.indexOf(character, index2 + character.length);
}
return count;
}
// node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp/index.js
function escapeStringRegexp(string3) {
if (typeof string3 !== "string") {
throw new TypeError("Expected a string");
}
return string3.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}
// node_modules/unist-util-is/lib/index.js
var convert = (
// Note: overloads in JSDoc can’t yet use different `@template`s.
/**
* @type {(
* ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &
* ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &
* ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate) &
* ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &
* ((test?: Test) => Check)
* )}
*/
/**
* @param {Test} [test]
* @returns {Check}
*/
function(test) {
if (test === null || test === void 0) {
return ok2;
}
if (typeof test === "function") {
return castFactory(test);
}
if (typeof test === "object") {
return Array.isArray(test) ? anyFactory(test) : (
// Cast because `ReadonlyArray` goes into the above but `isArray`
// narrows to `Array`.
propertiesFactory(
/** @type {Props} */
test
)
);
}
if (typeof test === "string") {
return typeFactory(test);
}
throw new Error("Expected function, string, or object as test");
}
);
function anyFactory(tests) {
const checks = [];
let index2 = -1;
while (++index2 < tests.length) {
checks[index2] = convert(tests[index2]);
}
return castFactory(any);
function any(...parameters) {
let index3 = -1;
while (++index3 < checks.length) {
if (checks[index3].apply(this, parameters))
return true;
}
return false;
}
}
function propertiesFactory(check) {
const checkAsRecord = (
/** @type {Record} */
check
);
return castFactory(all2);
function all2(node2) {
const nodeAsRecord = (
/** @type {Record} */
/** @type {unknown} */
node2
);
let key;
for (key in check) {
if (nodeAsRecord[key] !== checkAsRecord[key])
return false;
}
return true;
}
}
function typeFactory(check) {
return castFactory(type);
function type(node2) {
return node2 && node2.type === check;
}
}
function castFactory(testFunction) {
return check;
function check(value, index2, parent) {
return Boolean(
looksLikeANode(value) && testFunction.call(
this,
value,
typeof index2 === "number" ? index2 : void 0,
parent || void 0
)
);
}
}
function ok2() {
return true;
}
function looksLikeANode(value) {
return value !== null && typeof value === "object" && "type" in value;
}
// node_modules/unist-util-visit-parents/lib/color.js
function color(d) {
return d;
}
// node_modules/unist-util-visit-parents/lib/index.js
var empty = [];
var CONTINUE = true;
var EXIT = false;
var SKIP = "skip";
function visitParents(tree, test, visitor, reverse) {
let check;
if (typeof test === "function" && typeof visitor !== "function") {
reverse = visitor;
visitor = test;
} else {
check = test;
}
const is2 = convert(check);
const step = reverse ? -1 : 1;
factory(tree, void 0, [])();
function factory(node2, index2, parents) {
const value = (
/** @type {Record} */
node2 && typeof node2 === "object" ? node2 : {}
);
if (typeof value.type === "string") {
const name = (
// `hast`
typeof value.tagName === "string" ? value.tagName : (
// `xast`
typeof value.name === "string" ? value.name : void 0
)
);
Object.defineProperty(visit2, "name", {
value: "node (" + color(node2.type + (name ? "<" + name + ">" : "")) + ")"
});
}
return visit2;
function visit2() {
let result = empty;
let subresult;
let offset;
let grandparents;
if (!test || is2(node2, index2, parents[parents.length - 1] || void 0)) {
result = toResult(visitor(node2, parents));
if (result[0] === EXIT) {
return result;
}
}
if ("children" in node2 && node2.children) {
const nodeAsParent = (
/** @type {UnistParent} */
node2
);
if (nodeAsParent.children && result[0] !== SKIP) {
offset = (reverse ? nodeAsParent.children.length : -1) + step;
grandparents = parents.concat(nodeAsParent);
while (offset > -1 && offset < nodeAsParent.children.length) {
const child = nodeAsParent.children[offset];
subresult = factory(child, offset, grandparents)();
if (subresult[0] === EXIT) {
return subresult;
}
offset = typeof subresult[1] === "number" ? subresult[1] : offset + step;
}
}
}
return result;
}
}
}
function toResult(value) {
if (Array.isArray(value)) {
return value;
}
if (typeof value === "number") {
return [CONTINUE, value];
}
return value === null || value === void 0 ? empty : [value];
}
// node_modules/mdast-util-find-and-replace/lib/index.js
function findAndReplace(tree, list3, options) {
const settings = options || {};
const ignored = convert(settings.ignore || []);
const pairs = toPairs(list3);
let pairIndex = -1;
while (++pairIndex < pairs.length) {
visitParents(tree, "text", visitor);
}
function visitor(node2, parents) {
let index2 = -1;
let grandparent;
while (++index2 < parents.length) {
const parent = parents[index2];
const siblings = grandparent ? grandparent.children : void 0;
if (ignored(
parent,
siblings ? siblings.indexOf(parent) : void 0,
grandparent
)) {
return;
}
grandparent = parent;
}
if (grandparent) {
return handler(node2, parents);
}
}
function handler(node2, parents) {
const parent = parents[parents.length - 1];
const find = pairs[pairIndex][0];
const replace2 = pairs[pairIndex][1];
let start = 0;
const siblings = parent.children;
const index2 = siblings.indexOf(node2);
let change = false;
let nodes = [];
find.lastIndex = 0;
let match = find.exec(node2.value);
while (match) {
const position2 = match.index;
const matchObject = {
index: match.index,
input: match.input,
stack: [...parents, node2]
};
let value = replace2(...match, matchObject);
if (typeof value === "string") {
value = value.length > 0 ? { type: "text", value } : void 0;
}
if (value === false) {
find.lastIndex = position2 + 1;
} else {
if (start !== position2) {
nodes.push({
type: "text",
value: node2.value.slice(start, position2)
});
}
if (Array.isArray(value)) {
nodes.push(...value);
} else if (value) {
nodes.push(value);
}
start = position2 + match[0].length;
change = true;
}
if (!find.global) {
break;
}
match = find.exec(node2.value);
}
if (change) {
if (start < node2.value.length) {
nodes.push({ type: "text", value: node2.value.slice(start) });
}
parent.children.splice(index2, 1, ...nodes);
} else {
nodes = [node2];
}
return index2 + nodes.length;
}
}
function toPairs(tupleOrList) {
const result = [];
if (!Array.isArray(tupleOrList)) {
throw new TypeError("Expected find and replace tuple or list of tuples");
}
const list3 = !tupleOrList[0] || Array.isArray(tupleOrList[0]) ? tupleOrList : [tupleOrList];
let index2 = -1;
while (++index2 < list3.length) {
const tuple = list3[index2];
result.push([toExpression(tuple[0]), toFunction(tuple[1])]);
}
return result;
}
function toExpression(find) {
return typeof find === "string" ? new RegExp(escapeStringRegexp(find), "g") : find;
}
function toFunction(replace2) {
return typeof replace2 === "function" ? replace2 : function() {
return replace2;
};
}
// node_modules/mdast-util-gfm-autolink-literal/lib/index.js
var inConstruct = "phrasing";
var notInConstruct = ["autolink", "link", "image", "label"];
function gfmAutolinkLiteralFromMarkdown() {
return {
transforms: [transformGfmAutolinkLiterals],
enter: {
literalAutolink: enterLiteralAutolink,
literalAutolinkEmail: enterLiteralAutolinkValue,
literalAutolinkHttp: enterLiteralAutolinkValue,
literalAutolinkWww: enterLiteralAutolinkValue
},
exit: {
literalAutolink: exitLiteralAutolink,
literalAutolinkEmail: exitLiteralAutolinkEmail,
literalAutolinkHttp: exitLiteralAutolinkHttp,
literalAutolinkWww: exitLiteralAutolinkWww
}
};
}
function gfmAutolinkLiteralToMarkdown() {
return {
unsafe: [
{
character: "@",
before: "[+\\-.\\w]",
after: "[\\-.\\w]",
inConstruct,
notInConstruct
},
{
character: ".",
before: "[Ww]",
after: "[\\-.\\w]",
inConstruct,
notInConstruct
},
{
character: ":",
before: "[ps]",
after: "\\/",
inConstruct,
notInConstruct
}
]
};
}
function enterLiteralAutolink(token) {
this.enter({ type: "link", title: null, url: "", children: [] }, token);
}
function enterLiteralAutolinkValue(token) {
this.config.enter.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkHttp(token) {
this.config.exit.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkWww(token) {
this.config.exit.data.call(this, token);
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "link");
node2.url = "http://" + this.sliceSerialize(token);
}
function exitLiteralAutolinkEmail(token) {
this.config.exit.autolinkEmail.call(this, token);
}
function exitLiteralAutolink(token) {
this.exit(token);
}
function transformGfmAutolinkLiterals(tree) {
findAndReplace(
tree,
[
[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)", "gu"), findEmail]
],
{ ignore: ["link", "linkReference"] }
);
}
function findUrl(_, protocol, domain2, path3, match) {
let prefix = "";
if (!previous2(match)) {
return false;
}
if (/^w/i.test(protocol)) {
domain2 = protocol + domain2;
protocol = "";
prefix = "http://";
}
if (!isCorrectDomain(domain2)) {
return false;
}
const parts = splitUrl(domain2 + path3);
if (!parts[0])
return false;
const result = {
type: "link",
title: null,
url: prefix + protocol + parts[0],
children: [{ type: "text", value: protocol + parts[0] }]
};
if (parts[1]) {
return [result, { type: "text", value: parts[1] }];
}
return result;
}
function findEmail(_, atext, label, match) {
if (
// Not an expected previous character.
!previous2(match, true) || // Label ends in not allowed character.
/[-\d_]$/.test(label)
) {
return false;
}
return {
type: "link",
title: null,
url: "mailto:" + atext + "@" + label,
children: [{ type: "text", value: atext + "@" + label }]
};
}
function isCorrectDomain(domain2) {
const parts = domain2.split(".");
if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[a-zA-Z\d]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[a-zA-Z\d]/.test(parts[parts.length - 2]))) {
return false;
}
return true;
}
function splitUrl(url) {
const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url);
if (!trailExec) {
return [url, void 0];
}
url = url.slice(0, trailExec.index);
let trail2 = trailExec[0];
let closingParenIndex = trail2.indexOf(")");
const openingParens = ccount(url, "(");
let closingParens = ccount(url, ")");
while (closingParenIndex !== -1 && openingParens > closingParens) {
url += trail2.slice(0, closingParenIndex + 1);
trail2 = trail2.slice(closingParenIndex + 1);
closingParenIndex = trail2.indexOf(")");
closingParens++;
}
return [url, trail2];
}
function previous2(match, email) {
const code4 = match.input.charCodeAt(match.index - 1);
return (match.index === 0 || unicodeWhitespace(code4) || unicodePunctuation(code4)) && // If it’s an email, the previous character should not be a slash.
(!email || code4 !== 47);
}
// node_modules/mdast-util-gfm-footnote/lib/index.js
footnoteReference.peek = footnoteReferencePeek;
function enterFootnoteCallString() {
this.buffer();
}
function enterFootnoteCall(token) {
this.enter({ type: "footnoteReference", identifier: "", label: "" }, token);
}
function enterFootnoteDefinitionLabelString() {
this.buffer();
}
function enterFootnoteDefinition(token) {
this.enter(
{ type: "footnoteDefinition", identifier: "", label: "", children: [] },
token
);
}
function exitFootnoteCallString(token) {
const label = this.resume();
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "footnoteReference");
node2.identifier = normalizeIdentifier(
this.sliceSerialize(token)
).toLowerCase();
node2.label = label;
}
function exitFootnoteCall(token) {
this.exit(token);
}
function exitFootnoteDefinitionLabelString(token) {
const label = this.resume();
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "footnoteDefinition");
node2.identifier = normalizeIdentifier(
this.sliceSerialize(token)
).toLowerCase();
node2.label = label;
}
function exitFootnoteDefinition(token) {
this.exit(token);
}
function footnoteReferencePeek() {
return "[";
}
function footnoteReference(node2, _, state, info) {
const tracker = state.createTracker(info);
let value = tracker.move("[^");
const exit3 = state.enter("footnoteReference");
const subexit = state.enter("reference");
value += tracker.move(
state.safe(state.associationId(node2), { after: "]", before: value })
);
subexit();
exit3();
value += tracker.move("]");
return value;
}
function gfmFootnoteFromMarkdown() {
return {
enter: {
gfmFootnoteCallString: enterFootnoteCallString,
gfmFootnoteCall: enterFootnoteCall,
gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,
gfmFootnoteDefinition: enterFootnoteDefinition
},
exit: {
gfmFootnoteCallString: exitFootnoteCallString,
gfmFootnoteCall: exitFootnoteCall,
gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,
gfmFootnoteDefinition: exitFootnoteDefinition
}
};
}
function gfmFootnoteToMarkdown(options) {
let firstLineBlank = false;
if (options && options.firstLineBlank) {
firstLineBlank = true;
}
return {
handlers: { footnoteDefinition, footnoteReference },
// This is on by default already.
unsafe: [{ character: "[", inConstruct: ["label", "phrasing", "reference"] }]
};
function footnoteDefinition(node2, _, state, info) {
const tracker = state.createTracker(info);
let value = tracker.move("[^");
const exit3 = state.enter("footnoteDefinition");
const subexit = state.enter("label");
value += tracker.move(
state.safe(state.associationId(node2), { before: value, after: "]" })
);
subexit();
value += tracker.move("]:");
if (node2.children && node2.children.length > 0) {
tracker.shift(4);
value += tracker.move(
(firstLineBlank ? "\n" : " ") + state.indentLines(
state.containerFlow(node2, tracker.current()),
firstLineBlank ? mapAll : mapExceptFirst
)
);
}
exit3();
return value;
}
}
function mapExceptFirst(line, index2, blank) {
return index2 === 0 ? line : mapAll(line, index2, blank);
}
function mapAll(line, index2, blank) {
return (blank ? "" : " ") + line;
}
// node_modules/mdast-util-gfm-strikethrough/lib/index.js
var constructsWithoutStrikethrough = [
"autolink",
"destinationLiteral",
"destinationRaw",
"reference",
"titleQuote",
"titleApostrophe"
];
handleDelete.peek = peekDelete;
function gfmStrikethroughFromMarkdown() {
return {
canContainEols: ["delete"],
enter: { strikethrough: enterStrikethrough },
exit: { strikethrough: exitStrikethrough }
};
}
function gfmStrikethroughToMarkdown() {
return {
unsafe: [
{
character: "~",
inConstruct: "phrasing",
notInConstruct: constructsWithoutStrikethrough
}
],
handlers: { delete: handleDelete }
};
}
function enterStrikethrough(token) {
this.enter({ type: "delete", children: [] }, token);
}
function exitStrikethrough(token) {
this.exit(token);
}
function handleDelete(node2, _, state, info) {
const tracker = state.createTracker(info);
const exit3 = state.enter("strikethrough");
let value = tracker.move("~~");
value += state.containerPhrasing(node2, __spreadProps(__spreadValues({}, tracker.current()), {
before: value,
after: "~"
}));
value += tracker.move("~~");
exit3();
return value;
}
function peekDelete() {
return "~";
}
// node_modules/markdown-table/index.js
function defaultStringLength(value) {
return value.length;
}
function markdownTable(table2, options) {
const settings = options || {};
const align = (settings.align || []).concat();
const stringLength = settings.stringLength || defaultStringLength;
const alignments = [];
const cellMatrix = [];
const sizeMatrix = [];
const longestCellByColumn = [];
let mostCellsPerRow = 0;
let rowIndex = -1;
while (++rowIndex < table2.length) {
const row2 = [];
const sizes2 = [];
let columnIndex2 = -1;
if (table2[rowIndex].length > mostCellsPerRow) {
mostCellsPerRow = table2[rowIndex].length;
}
while (++columnIndex2 < table2[rowIndex].length) {
const cell = serialize(table2[rowIndex][columnIndex2]);
if (settings.alignDelimiters !== false) {
const size = stringLength(cell);
sizes2[columnIndex2] = size;
if (longestCellByColumn[columnIndex2] === void 0 || size > longestCellByColumn[columnIndex2]) {
longestCellByColumn[columnIndex2] = size;
}
}
row2.push(cell);
}
cellMatrix[rowIndex] = row2;
sizeMatrix[rowIndex] = sizes2;
}
let columnIndex = -1;
if (typeof align === "object" && "length" in align) {
while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = toAlignment(align[columnIndex]);
}
} else {
const code4 = toAlignment(align);
while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = code4;
}
}
columnIndex = -1;
const row = [];
const sizes = [];
while (++columnIndex < mostCellsPerRow) {
const code4 = alignments[columnIndex];
let before = "";
let after = "";
if (code4 === 99) {
before = ":";
after = ":";
} else if (code4 === 108) {
before = ":";
} else if (code4 === 114) {
after = ":";
}
let size = settings.alignDelimiters === false ? 1 : Math.max(
1,
longestCellByColumn[columnIndex] - before.length - after.length
);
const cell = before + "-".repeat(size) + after;
if (settings.alignDelimiters !== false) {
size = before.length + size + after.length;
if (size > longestCellByColumn[columnIndex]) {
longestCellByColumn[columnIndex] = size;
}
sizes[columnIndex] = size;
}
row[columnIndex] = cell;
}
cellMatrix.splice(1, 0, row);
sizeMatrix.splice(1, 0, sizes);
rowIndex = -1;
const lines = [];
while (++rowIndex < cellMatrix.length) {
const row2 = cellMatrix[rowIndex];
const sizes2 = sizeMatrix[rowIndex];
columnIndex = -1;
const line = [];
while (++columnIndex < mostCellsPerRow) {
const cell = row2[columnIndex] || "";
let before = "";
let after = "";
if (settings.alignDelimiters !== false) {
const size = longestCellByColumn[columnIndex] - (sizes2[columnIndex] || 0);
const code4 = alignments[columnIndex];
if (code4 === 114) {
before = " ".repeat(size);
} else if (code4 === 99) {
if (size % 2) {
before = " ".repeat(size / 2 + 0.5);
after = " ".repeat(size / 2 - 0.5);
} else {
before = " ".repeat(size / 2);
after = before;
}
} else {
after = " ".repeat(size);
}
}
if (settings.delimiterStart !== false && !columnIndex) {
line.push("|");
}
if (settings.padding !== false && // Don’t add the opening space if we’re not aligning and the cell is
// empty: there will be a closing space.
!(settings.alignDelimiters === false && cell === "") && (settings.delimiterStart !== false || columnIndex)) {
line.push(" ");
}
if (settings.alignDelimiters !== false) {
line.push(before);
}
line.push(cell);
if (settings.alignDelimiters !== false) {
line.push(after);
}
if (settings.padding !== false) {
line.push(" ");
}
if (settings.delimiterEnd !== false || columnIndex !== mostCellsPerRow - 1) {
line.push("|");
}
}
lines.push(
settings.delimiterEnd === false ? line.join("").replace(/ +$/, "") : line.join("")
);
}
return lines.join("\n");
}
function serialize(value) {
return value === null || value === void 0 ? "" : String(value);
}
function toAlignment(value) {
const code4 = typeof value === "string" ? value.codePointAt(0) : 0;
return code4 === 67 || code4 === 99 ? 99 : code4 === 76 || code4 === 108 ? 108 : code4 === 82 || code4 === 114 ? 114 : 0;
}
// node_modules/mdast-util-to-markdown/lib/handle/blockquote.js
function blockquote2(node2, _, state, info) {
const exit3 = state.enter("blockquote");
const tracker = state.createTracker(info);
tracker.move("> ");
tracker.shift(2);
const value = state.indentLines(
state.containerFlow(node2, tracker.current()),
map
);
exit3();
return value;
}
function map(line, _, blank) {
return ">" + (blank ? "" : " ") + line;
}
// node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js
function patternInScope(stack, pattern) {
return listInScope(stack, pattern.inConstruct, true) && !listInScope(stack, pattern.notInConstruct, false);
}
function listInScope(stack, list3, none) {
if (typeof list3 === "string") {
list3 = [list3];
}
if (!list3 || list3.length === 0) {
return none;
}
let index2 = -1;
while (++index2 < list3.length) {
if (stack.includes(list3[index2])) {
return true;
}
}
return false;
}
// node_modules/mdast-util-to-markdown/lib/handle/break.js
function hardBreak(_, _1, state, info) {
let index2 = -1;
while (++index2 < state.unsafe.length) {
if (state.unsafe[index2].character === "\n" && patternInScope(state.stack, state.unsafe[index2])) {
return /[ \t]/.test(info.before) ? "" : " ";
}
}
return "\\\n";
}
// node_modules/longest-streak/index.js
function longestStreak(value, substring) {
const source = String(value);
let index2 = source.indexOf(substring);
let expected = index2;
let count = 0;
let max = 0;
if (typeof substring !== "string") {
throw new TypeError("Expected substring");
}
while (index2 !== -1) {
if (index2 === expected) {
if (++count > max) {
max = count;
}
} else {
count = 1;
}
expected = index2 + substring.length;
index2 = source.indexOf(substring, expected);
}
return max;
}
// node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js
function formatCodeAsIndented(node2, state) {
return Boolean(
state.options.fences === false && node2.value && // If there’s no info…
!node2.lang && // And there’s a non-whitespace character…
/[^ \r\n]/.test(node2.value) && // And the value doesn’t start or end in a blank…
!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(node2.value)
);
}
// node_modules/mdast-util-to-markdown/lib/util/check-fence.js
function checkFence(state) {
const marker = state.options.fence || "`";
if (marker !== "`" && marker !== "~") {
throw new Error(
"Cannot serialize code with `" + marker + "` for `options.fence`, expected `` ` `` or `~`"
);
}
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/code.js
function code2(node2, _, state, info) {
const marker = checkFence(state);
const raw = node2.value || "";
const suffix = marker === "`" ? "GraveAccent" : "Tilde";
if (formatCodeAsIndented(node2, state)) {
const exit4 = state.enter("codeIndented");
const value2 = state.indentLines(raw, map2);
exit4();
return value2;
}
const tracker = state.createTracker(info);
const sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3));
const exit3 = state.enter("codeFenced");
let value = tracker.move(sequence);
if (node2.lang) {
const subexit = state.enter(`codeFencedLang${suffix}`);
value += tracker.move(
state.safe(node2.lang, __spreadValues({
before: value,
after: " ",
encode: ["`"]
}, tracker.current()))
);
subexit();
}
if (node2.lang && node2.meta) {
const subexit = state.enter(`codeFencedMeta${suffix}`);
value += tracker.move(" ");
value += tracker.move(
state.safe(node2.meta, __spreadValues({
before: value,
after: "\n",
encode: ["`"]
}, tracker.current()))
);
subexit();
}
value += tracker.move("\n");
if (raw) {
value += tracker.move(raw + "\n");
}
value += tracker.move(sequence);
exit3();
return value;
}
function map2(line, _, blank) {
return (blank ? "" : " ") + line;
}
// node_modules/mdast-util-to-markdown/lib/util/check-quote.js
function checkQuote(state) {
const marker = state.options.quote || '"';
if (marker !== '"' && marker !== "'") {
throw new Error(
"Cannot serialize title with `" + marker + "` for `options.quote`, expected `\"`, or `'`"
);
}
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/definition.js
function definition2(node2, _, state, info) {
const quote = checkQuote(state);
const suffix = quote === '"' ? "Quote" : "Apostrophe";
const exit3 = state.enter("definition");
let subexit = state.enter("label");
const tracker = state.createTracker(info);
let value = tracker.move("[");
value += tracker.move(
state.safe(state.associationId(node2), __spreadValues({
before: value,
after: "]"
}, tracker.current()))
);
value += tracker.move("]: ");
subexit();
if (
// If there’s no url, or…
!node2.url || // If there are control characters or whitespace.
/[\0- \u007F]/.test(node2.url)
) {
subexit = state.enter("destinationLiteral");
value += tracker.move("<");
value += tracker.move(
state.safe(node2.url, __spreadValues({ before: value, after: ">" }, tracker.current()))
);
value += tracker.move(">");
} else {
subexit = state.enter("destinationRaw");
value += tracker.move(
state.safe(node2.url, __spreadValues({
before: value,
after: node2.title ? " " : "\n"
}, tracker.current()))
);
}
subexit();
if (node2.title) {
subexit = state.enter(`title${suffix}`);
value += tracker.move(" " + quote);
value += tracker.move(
state.safe(node2.title, __spreadValues({
before: value,
after: quote
}, tracker.current()))
);
value += tracker.move(quote);
subexit();
}
exit3();
return value;
}
// node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js
function checkEmphasis(state) {
const marker = state.options.emphasis || "*";
if (marker !== "*" && marker !== "_") {
throw new Error(
"Cannot serialize emphasis with `" + marker + "` for `options.emphasis`, expected `*`, or `_`"
);
}
return marker;
}
// node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js
function encodeCharacterReference(code4) {
return "" + code4.toString(16).toUpperCase() + ";";
}
// node_modules/mdast-util-to-markdown/lib/util/encode-info.js
function encodeInfo(outside, inside, marker) {
const outsideKind = classifyCharacter(outside);
const insideKind = classifyCharacter(inside);
if (outsideKind === void 0) {
return insideKind === void 0 ? (
// Letter inside:
// we have to encode *both* letters for `_` as it is looser.
// it already forms for `*` (and GFMs `~`).
marker === "_" ? { inside: true, outside: true } : { inside: false, outside: false }
) : insideKind === 1 ? (
// Whitespace inside: encode both (letter, whitespace).
{ inside: true, outside: true }
) : (
// Punctuation inside: encode outer (letter)
{ inside: false, outside: true }
);
}
if (outsideKind === 1) {
return insideKind === void 0 ? (
// Letter inside: already forms.
{ inside: false, outside: false }
) : insideKind === 1 ? (
// Whitespace inside: encode both (whitespace).
{ inside: true, outside: true }
) : (
// Punctuation inside: already forms.
{ inside: false, outside: false }
);
}
return insideKind === void 0 ? (
// Letter inside: already forms.
{ inside: false, outside: false }
) : insideKind === 1 ? (
// Whitespace inside: encode inner (whitespace).
{ inside: true, outside: false }
) : (
// Punctuation inside: already forms.
{ inside: false, outside: false }
);
}
// node_modules/mdast-util-to-markdown/lib/handle/emphasis.js
emphasis.peek = emphasisPeek;
function emphasis(node2, _, state, info) {
const marker = checkEmphasis(state);
const exit3 = state.enter("emphasis");
const tracker = state.createTracker(info);
const before = tracker.move(marker);
let between = tracker.move(
state.containerPhrasing(node2, __spreadValues({
after: marker,
before
}, tracker.current()))
);
const betweenHead = between.charCodeAt(0);
const open = encodeInfo(
info.before.charCodeAt(info.before.length - 1),
betweenHead,
marker
);
if (open.inside) {
between = encodeCharacterReference(betweenHead) + between.slice(1);
}
const betweenTail = between.charCodeAt(between.length - 1);
const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker);
if (close.inside) {
between = between.slice(0, -1) + encodeCharacterReference(betweenTail);
}
const after = tracker.move(marker);
exit3();
state.attentionEncodeSurroundingInfo = {
after: close.outside,
before: open.outside
};
return before + between + after;
}
function emphasisPeek(_, _1, state) {
return state.options.emphasis || "*";
}
// node_modules/unist-util-visit/lib/index.js
function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
let reverse;
let test;
let visitor;
if (typeof testOrVisitor === "function" && typeof visitorOrReverse !== "function") {
test = void 0;
visitor = testOrVisitor;
reverse = visitorOrReverse;
} else {
test = testOrVisitor;
visitor = visitorOrReverse;
reverse = maybeReverse;
}
visitParents(tree, test, overload, reverse);
function overload(node2, parents) {
const parent = parents[parents.length - 1];
const index2 = parent ? parent.children.indexOf(node2) : void 0;
return visitor(node2, index2, parent);
}
}
// node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
function formatHeadingAsSetext(node2, state) {
let literalWithBreak = false;
visit(node2, function(node3) {
if ("value" in node3 && /\r?\n|\r/.test(node3.value) || node3.type === "break") {
literalWithBreak = true;
return EXIT;
}
});
return Boolean(
(!node2.depth || node2.depth < 3) && toString(node2) && (state.options.setext || literalWithBreak)
);
}
// node_modules/mdast-util-to-markdown/lib/handle/heading.js
function heading(node2, _, state, info) {
const rank = Math.max(Math.min(6, node2.depth || 1), 1);
const tracker = state.createTracker(info);
if (formatHeadingAsSetext(node2, state)) {
const exit4 = state.enter("headingSetext");
const subexit2 = state.enter("phrasing");
const value2 = state.containerPhrasing(node2, __spreadProps(__spreadValues({}, tracker.current()), {
before: "\n",
after: "\n"
}));
subexit2();
exit4();
return value2 + "\n" + (rank === 1 ? "=" : "-").repeat(
// The whole size…
value2.length - // Minus the position of the character after the last EOL (or
// 0 if there is none)…
(Math.max(value2.lastIndexOf("\r"), value2.lastIndexOf("\n")) + 1)
);
}
const sequence = "#".repeat(rank);
const exit3 = state.enter("headingAtx");
const subexit = state.enter("phrasing");
tracker.move(sequence + " ");
let value = state.containerPhrasing(node2, __spreadValues({
before: "# ",
after: "\n"
}, tracker.current()));
if (/^[\t ]/.test(value)) {
value = encodeCharacterReference(value.charCodeAt(0)) + value.slice(1);
}
value = value ? sequence + " " + value : sequence;
if (state.options.closeAtx) {
value += " " + sequence;
}
subexit();
exit3();
return value;
}
// node_modules/mdast-util-to-markdown/lib/handle/html.js
html.peek = htmlPeek;
function html(node2) {
return node2.value || "";
}
function htmlPeek() {
return "<";
}
// node_modules/mdast-util-to-markdown/lib/handle/image.js
image2.peek = imagePeek;
function image2(node2, _, state, info) {
const quote = checkQuote(state);
const suffix = quote === '"' ? "Quote" : "Apostrophe";
const exit3 = state.enter("image");
let subexit = state.enter("label");
const tracker = state.createTracker(info);
let value = tracker.move("![");
value += tracker.move(
state.safe(node2.alt, __spreadValues({ before: value, after: "]" }, tracker.current()))
);
value += tracker.move("](");
subexit();
if (
// If there’s no url but there is a title…
!node2.url && node2.title || // If there are control characters or whitespace.
/[\0- \u007F]/.test(node2.url)
) {
subexit = state.enter("destinationLiteral");
value += tracker.move("<");
value += tracker.move(
state.safe(node2.url, __spreadValues({ before: value, after: ">" }, tracker.current()))
);
value += tracker.move(">");
} else {
subexit = state.enter("destinationRaw");
value += tracker.move(
state.safe(node2.url, __spreadValues({
before: value,
after: node2.title ? " " : ")"
}, tracker.current()))
);
}
subexit();
if (node2.title) {
subexit = state.enter(`title${suffix}`);
value += tracker.move(" " + quote);
value += tracker.move(
state.safe(node2.title, __spreadValues({
before: value,
after: quote
}, tracker.current()))
);
value += tracker.move(quote);
subexit();
}
value += tracker.move(")");
exit3();
return value;
}
function imagePeek() {
return "!";
}
// node_modules/mdast-util-to-markdown/lib/handle/image-reference.js
imageReference.peek = imageReferencePeek;
function imageReference(node2, _, state, info) {
const type = node2.referenceType;
const exit3 = state.enter("imageReference");
let subexit = state.enter("label");
const tracker = state.createTracker(info);
let value = tracker.move("![");
const alt = state.safe(node2.alt, __spreadValues({
before: value,
after: "]"
}, tracker.current()));
value += tracker.move(alt + "][");
subexit();
const stack = state.stack;
state.stack = [];
subexit = state.enter("reference");
const reference = state.safe(state.associationId(node2), __spreadValues({
before: value,
after: "]"
}, tracker.current()));
subexit();
state.stack = stack;
exit3();
if (type === "full" || !alt || alt !== reference) {
value += tracker.move(reference + "]");
} else if (type === "shortcut") {
value = value.slice(0, -1);
} else {
value += tracker.move("]");
}
return value;
}
function imageReferencePeek() {
return "!";
}
// node_modules/mdast-util-to-markdown/lib/handle/inline-code.js
inlineCode.peek = inlineCodePeek;
function inlineCode(node2, _, state) {
let value = node2.value || "";
let sequence = "`";
let index2 = -1;
while (new RegExp("(^|[^`])" + sequence + "([^`]|$)").test(value)) {
sequence += "`";
}
if (/[^ \r\n]/.test(value) && (/^[ \r\n]/.test(value) && /[ \r\n]$/.test(value) || /^`|`$/.test(value))) {
value = " " + value + " ";
}
while (++index2 < state.unsafe.length) {
const pattern = state.unsafe[index2];
const expression = state.compilePattern(pattern);
let match;
if (!pattern.atBreak)
continue;
while (match = expression.exec(value)) {
let position2 = match.index;
if (value.charCodeAt(position2) === 10 && value.charCodeAt(position2 - 1) === 13) {
position2--;
}
value = value.slice(0, position2) + " " + value.slice(match.index + 1);
}
}
return sequence + value + sequence;
}
function inlineCodePeek() {
return "`";
}
// node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js
function formatLinkAsAutolink(node2, state) {
const raw = toString(node2);
return Boolean(
!state.options.resourceLink && // If there’s a url…
node2.url && // And there’s a no title…
!node2.title && // And the content of `node` is a single text node…
node2.children && node2.children.length === 1 && node2.children[0].type === "text" && // And if the url is the same as the content…
(raw === node2.url || "mailto:" + raw === node2.url) && // And that starts w/ a protocol…
/^[a-z][a-z+.-]+:/i.test(node2.url) && // And that doesn’t contain ASCII control codes (character escapes and
// references don’t work), space, or angle brackets…
!/[\0- <>\u007F]/.test(node2.url)
);
}
// node_modules/mdast-util-to-markdown/lib/handle/link.js
link.peek = linkPeek;
function link(node2, _, state, info) {
const quote = checkQuote(state);
const suffix = quote === '"' ? "Quote" : "Apostrophe";
const tracker = state.createTracker(info);
let exit3;
let subexit;
if (formatLinkAsAutolink(node2, state)) {
const stack = state.stack;
state.stack = [];
exit3 = state.enter("autolink");
let value2 = tracker.move("<");
value2 += tracker.move(
state.containerPhrasing(node2, __spreadValues({
before: value2,
after: ">"
}, tracker.current()))
);
value2 += tracker.move(">");
exit3();
state.stack = stack;
return value2;
}
exit3 = state.enter("link");
subexit = state.enter("label");
let value = tracker.move("[");
value += tracker.move(
state.containerPhrasing(node2, __spreadValues({
before: value,
after: "]("
}, tracker.current()))
);
value += tracker.move("](");
subexit();
if (
// If there’s no url but there is a title…
!node2.url && node2.title || // If there are control characters or whitespace.
/[\0- \u007F]/.test(node2.url)
) {
subexit = state.enter("destinationLiteral");
value += tracker.move("<");
value += tracker.move(
state.safe(node2.url, __spreadValues({ before: value, after: ">" }, tracker.current()))
);
value += tracker.move(">");
} else {
subexit = state.enter("destinationRaw");
value += tracker.move(
state.safe(node2.url, __spreadValues({
before: value,
after: node2.title ? " " : ")"
}, tracker.current()))
);
}
subexit();
if (node2.title) {
subexit = state.enter(`title${suffix}`);
value += tracker.move(" " + quote);
value += tracker.move(
state.safe(node2.title, __spreadValues({
before: value,
after: quote
}, tracker.current()))
);
value += tracker.move(quote);
subexit();
}
value += tracker.move(")");
exit3();
return value;
}
function linkPeek(node2, _, state) {
return formatLinkAsAutolink(node2, state) ? "<" : "[";
}
// node_modules/mdast-util-to-markdown/lib/handle/link-reference.js
linkReference.peek = linkReferencePeek;
function linkReference(node2, _, state, info) {
const type = node2.referenceType;
const exit3 = state.enter("linkReference");
let subexit = state.enter("label");
const tracker = state.createTracker(info);
let value = tracker.move("[");
const text5 = state.containerPhrasing(node2, __spreadValues({
before: value,
after: "]"
}, tracker.current()));
value += tracker.move(text5 + "][");
subexit();
const stack = state.stack;
state.stack = [];
subexit = state.enter("reference");
const reference = state.safe(state.associationId(node2), __spreadValues({
before: value,
after: "]"
}, tracker.current()));
subexit();
state.stack = stack;
exit3();
if (type === "full" || !text5 || text5 !== reference) {
value += tracker.move(reference + "]");
} else if (type === "shortcut") {
value = value.slice(0, -1);
} else {
value += tracker.move("]");
}
return value;
}
function linkReferencePeek() {
return "[";
}
// node_modules/mdast-util-to-markdown/lib/util/check-bullet.js
function checkBullet(state) {
const marker = state.options.bullet || "*";
if (marker !== "*" && marker !== "+" && marker !== "-") {
throw new Error(
"Cannot serialize items with `" + marker + "` for `options.bullet`, expected `*`, `+`, or `-`"
);
}
return marker;
}
// node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js
function checkBulletOther(state) {
const bullet = checkBullet(state);
const bulletOther = state.options.bulletOther;
if (!bulletOther) {
return bullet === "*" ? "-" : "*";
}
if (bulletOther !== "*" && bulletOther !== "+" && bulletOther !== "-") {
throw new Error(
"Cannot serialize items with `" + bulletOther + "` for `options.bulletOther`, expected `*`, `+`, or `-`"
);
}
if (bulletOther === bullet) {
throw new Error(
"Expected `bullet` (`" + bullet + "`) and `bulletOther` (`" + bulletOther + "`) to be different"
);
}
return bulletOther;
}
// node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js
function checkBulletOrdered(state) {
const marker = state.options.bulletOrdered || ".";
if (marker !== "." && marker !== ")") {
throw new Error(
"Cannot serialize items with `" + marker + "` for `options.bulletOrdered`, expected `.` or `)`"
);
}
return marker;
}
// node_modules/mdast-util-to-markdown/lib/util/check-rule.js
function checkRule(state) {
const marker = state.options.rule || "*";
if (marker !== "*" && marker !== "-" && marker !== "_") {
throw new Error(
"Cannot serialize rules with `" + marker + "` for `options.rule`, expected `*`, `-`, or `_`"
);
}
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/list.js
function list2(node2, parent, state, info) {
const exit3 = state.enter("list");
const bulletCurrent = state.bulletCurrent;
let bullet = node2.ordered ? checkBulletOrdered(state) : checkBullet(state);
const bulletOther = node2.ordered ? bullet === "." ? ")" : "." : checkBulletOther(state);
let useDifferentMarker = parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : false;
if (!node2.ordered) {
const firstListItem = node2.children ? node2.children[0] : void 0;
if (
// Bullet could be used as a thematic break marker:
(bullet === "*" || bullet === "-") && // Empty first list item:
firstListItem && (!firstListItem.children || !firstListItem.children[0]) && // Directly in two other list items:
state.stack[state.stack.length - 1] === "list" && state.stack[state.stack.length - 2] === "listItem" && state.stack[state.stack.length - 3] === "list" && state.stack[state.stack.length - 4] === "listItem" && // That are each the first child.
state.indexStack[state.indexStack.length - 1] === 0 && state.indexStack[state.indexStack.length - 2] === 0 && state.indexStack[state.indexStack.length - 3] === 0
) {
useDifferentMarker = true;
}
if (checkRule(state) === bullet && firstListItem) {
let index2 = -1;
while (++index2 < node2.children.length) {
const item = node2.children[index2];
if (item && item.type === "listItem" && item.children && item.children[0] && item.children[0].type === "thematicBreak") {
useDifferentMarker = true;
break;
}
}
}
}
if (useDifferentMarker) {
bullet = bulletOther;
}
state.bulletCurrent = bullet;
const value = state.containerFlow(node2, info);
state.bulletLastUsed = bullet;
state.bulletCurrent = bulletCurrent;
exit3();
return value;
}
// node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js
function checkListItemIndent(state) {
const style = state.options.listItemIndent || "one";
if (style !== "tab" && style !== "one" && style !== "mixed") {
throw new Error(
"Cannot serialize items with `" + style + "` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`"
);
}
return style;
}
// node_modules/mdast-util-to-markdown/lib/handle/list-item.js
function listItem(node2, parent, state, info) {
const listItemIndent = checkListItemIndent(state);
let bullet = state.bulletCurrent || checkBullet(state);
if (parent && parent.type === "list" && parent.ordered) {
bullet = (typeof parent.start === "number" && parent.start > -1 ? parent.start : 1) + (state.options.incrementListMarker === false ? 0 : parent.children.indexOf(node2)) + bullet;
}
let size = bullet.length + 1;
if (listItemIndent === "tab" || listItemIndent === "mixed" && (parent && parent.type === "list" && parent.spread || node2.spread)) {
size = Math.ceil(size / 4) * 4;
}
const tracker = state.createTracker(info);
tracker.move(bullet + " ".repeat(size - bullet.length));
tracker.shift(size);
const exit3 = state.enter("listItem");
const value = state.indentLines(
state.containerFlow(node2, tracker.current()),
map3
);
exit3();
return value;
function map3(line, index2, blank) {
if (index2) {
return (blank ? "" : " ".repeat(size)) + line;
}
return (blank ? bullet : bullet + " ".repeat(size - bullet.length)) + line;
}
}
// node_modules/mdast-util-to-markdown/lib/handle/paragraph.js
function paragraph2(node2, _, state, info) {
const exit3 = state.enter("paragraph");
const subexit = state.enter("phrasing");
const value = state.containerPhrasing(node2, info);
subexit();
exit3();
return value;
}
// node_modules/mdast-util-phrasing/lib/index.js
var phrasing = (
/** @type {(node?: unknown) => node is Exclude} */
convert([
"break",
"delete",
"emphasis",
// To do: next major: removed since footnotes were added to GFM.
"footnote",
"footnoteReference",
"image",
"imageReference",
"inlineCode",
// Enabled by `mdast-util-math`:
"inlineMath",
"link",
"linkReference",
// Enabled by `mdast-util-mdx`:
"mdxJsxTextElement",
// Enabled by `mdast-util-mdx`:
"mdxTextExpression",
"strong",
"text",
// Enabled by `mdast-util-directive`:
"textDirective"
])
);
// node_modules/mdast-util-to-markdown/lib/handle/root.js
function root(node2, _, state, info) {
const hasPhrasing = node2.children.some(function(d) {
return phrasing(d);
});
const container = hasPhrasing ? state.containerPhrasing : state.containerFlow;
return container.call(state, node2, info);
}
// node_modules/mdast-util-to-markdown/lib/util/check-strong.js
function checkStrong(state) {
const marker = state.options.strong || "*";
if (marker !== "*" && marker !== "_") {
throw new Error(
"Cannot serialize strong with `" + marker + "` for `options.strong`, expected `*`, or `_`"
);
}
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/strong.js
strong.peek = strongPeek;
function strong(node2, _, state, info) {
const marker = checkStrong(state);
const exit3 = state.enter("strong");
const tracker = state.createTracker(info);
const before = tracker.move(marker + marker);
let between = tracker.move(
state.containerPhrasing(node2, __spreadValues({
after: marker,
before
}, tracker.current()))
);
const betweenHead = between.charCodeAt(0);
const open = encodeInfo(
info.before.charCodeAt(info.before.length - 1),
betweenHead,
marker
);
if (open.inside) {
between = encodeCharacterReference(betweenHead) + between.slice(1);
}
const betweenTail = between.charCodeAt(between.length - 1);
const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker);
if (close.inside) {
between = between.slice(0, -1) + encodeCharacterReference(betweenTail);
}
const after = tracker.move(marker + marker);
exit3();
state.attentionEncodeSurroundingInfo = {
after: close.outside,
before: open.outside
};
return before + between + after;
}
function strongPeek(_, _1, state) {
return state.options.strong || "*";
}
// node_modules/mdast-util-to-markdown/lib/handle/text.js
function text3(node2, _, state, info) {
return state.safe(node2.value, info);
}
// node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js
function checkRuleRepetition(state) {
const repetition = state.options.ruleRepetition || 3;
if (repetition < 3) {
throw new Error(
"Cannot serialize rules with repetition `" + repetition + "` for `options.ruleRepetition`, expected `3` or more"
);
}
return repetition;
}
// node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js
function thematicBreak2(_, _1, state) {
const value = (checkRule(state) + (state.options.ruleSpaces ? " " : "")).repeat(checkRuleRepetition(state));
return state.options.ruleSpaces ? value.slice(0, -1) : value;
}
// node_modules/mdast-util-to-markdown/lib/handle/index.js
var handle = {
blockquote: blockquote2,
break: hardBreak,
code: code2,
definition: definition2,
emphasis,
hardBreak,
heading,
html,
image: image2,
imageReference,
inlineCode,
link,
linkReference,
list: list2,
listItem,
paragraph: paragraph2,
root,
strong,
text: text3,
thematicBreak: thematicBreak2
};
// node_modules/mdast-util-gfm-table/lib/index.js
function gfmTableFromMarkdown() {
return {
enter: {
table: enterTable,
tableData: enterCell,
tableHeader: enterCell,
tableRow: enterRow
},
exit: {
codeText: exitCodeText,
table: exitTable,
tableData: exit2,
tableHeader: exit2,
tableRow: exit2
}
};
}
function enterTable(token) {
const align = token._align;
ok(align, "expected `_align` on table");
this.enter(
{
type: "table",
align: align.map(function(d) {
return d === "none" ? null : d;
}),
children: []
},
token
);
this.data.inTable = true;
}
function exitTable(token) {
this.exit(token);
this.data.inTable = void 0;
}
function enterRow(token) {
this.enter({ type: "tableRow", children: [] }, token);
}
function exit2(token) {
this.exit(token);
}
function enterCell(token) {
this.enter({ type: "tableCell", children: [] }, token);
}
function exitCodeText(token) {
let value = this.resume();
if (this.data.inTable) {
value = value.replace(/\\([\\|])/g, replace);
}
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "inlineCode");
node2.value = value;
this.exit(token);
}
function replace($0, $1) {
return $1 === "|" ? $1 : $0;
}
function gfmTableToMarkdown(options) {
const settings = options || {};
const padding = settings.tableCellPadding;
const alignDelimiters = settings.tablePipeAlign;
const stringLength = settings.stringLength;
const around = padding ? " " : "|";
return {
unsafe: [
{ character: "\r", inConstruct: "tableCell" },
{ character: "\n", inConstruct: "tableCell" },
// A pipe, when followed by a tab or space (padding), or a dash or colon
// (unpadded delimiter row), could result in a table.
{ atBreak: true, character: "|", after: "[ :-]" },
// A pipe in a cell must be encoded.
{ character: "|", inConstruct: "tableCell" },
// A colon must be followed by a dash, in which case it could start a
// delimiter row.
{ atBreak: true, character: ":", after: "-" },
// A delimiter row can also start with a dash, when followed by more
// dashes, a colon, or a pipe.
// This is a stricter version than the built in check for lists, thematic
// breaks, and setex heading underlines though:
//
{ atBreak: true, character: "-", after: "[:|-]" }
],
handlers: {
inlineCode: inlineCodeWithTable,
table: handleTable,
tableCell: handleTableCell,
tableRow: handleTableRow
}
};
function handleTable(node2, _, state, info) {
return serializeData(handleTableAsData(node2, state, info), node2.align);
}
function handleTableRow(node2, _, state, info) {
const row = handleTableRowAsData(node2, state, info);
const value = serializeData([row]);
return value.slice(0, value.indexOf("\n"));
}
function handleTableCell(node2, _, state, info) {
const exit3 = state.enter("tableCell");
const subexit = state.enter("phrasing");
const value = state.containerPhrasing(node2, __spreadProps(__spreadValues({}, info), {
before: around,
after: around
}));
subexit();
exit3();
return value;
}
function serializeData(matrix, align) {
return markdownTable(matrix, {
align,
// @ts-expect-error: `markdown-table` types should support `null`.
alignDelimiters,
// @ts-expect-error: `markdown-table` types should support `null`.
padding,
// @ts-expect-error: `markdown-table` types should support `null`.
stringLength
});
}
function handleTableAsData(node2, state, info) {
const children = node2.children;
let index2 = -1;
const result = [];
const subexit = state.enter("table");
while (++index2 < children.length) {
result[index2] = handleTableRowAsData(children[index2], state, info);
}
subexit();
return result;
}
function handleTableRowAsData(node2, state, info) {
const children = node2.children;
let index2 = -1;
const result = [];
const subexit = state.enter("tableRow");
while (++index2 < children.length) {
result[index2] = handleTableCell(children[index2], node2, state, info);
}
subexit();
return result;
}
function inlineCodeWithTable(node2, parent, state) {
let value = handle.inlineCode(node2, parent, state);
if (state.stack.includes("tableCell")) {
value = value.replace(/\|/g, "\\$&");
}
return value;
}
}
// node_modules/mdast-util-gfm-task-list-item/lib/index.js
function gfmTaskListItemFromMarkdown() {
return {
exit: {
taskListCheckValueChecked: exitCheck,
taskListCheckValueUnchecked: exitCheck,
paragraph: exitParagraphWithTaskListItem
}
};
}
function gfmTaskListItemToMarkdown() {
return {
unsafe: [{ atBreak: true, character: "-", after: "[:|-]" }],
handlers: { listItem: listItemWithTaskListItem }
};
}
function exitCheck(token) {
const node2 = this.stack[this.stack.length - 2];
ok(node2.type === "listItem");
node2.checked = token.type === "taskListCheckValueChecked";
}
function exitParagraphWithTaskListItem(token) {
const parent = this.stack[this.stack.length - 2];
if (parent && parent.type === "listItem" && typeof parent.checked === "boolean") {
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "paragraph");
const head = node2.children[0];
if (head && head.type === "text") {
const siblings = parent.children;
let index2 = -1;
let firstParaghraph;
while (++index2 < siblings.length) {
const sibling = siblings[index2];
if (sibling.type === "paragraph") {
firstParaghraph = sibling;
break;
}
}
if (firstParaghraph === node2) {
head.value = head.value.slice(1);
if (head.value.length === 0) {
node2.children.shift();
} else if (node2.position && head.position && typeof head.position.start.offset === "number") {
head.position.start.column++;
head.position.start.offset++;
node2.position.start = Object.assign({}, head.position.start);
}
}
}
}
this.exit(token);
}
function listItemWithTaskListItem(node2, parent, state, info) {
const head = node2.children[0];
const checkable = typeof node2.checked === "boolean" && head && head.type === "paragraph";
const checkbox = "[" + (node2.checked ? "x" : " ") + "] ";
const tracker = state.createTracker(info);
if (checkable) {
tracker.move(checkbox);
}
let value = handle.listItem(node2, parent, state, __spreadValues(__spreadValues({}, info), tracker.current()));
if (checkable) {
value = value.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/, check);
}
return value;
function check($0) {
return $0 + checkbox;
}
}
// node_modules/mdast-util-gfm/lib/index.js
function gfmFromMarkdown() {
return [
gfmAutolinkLiteralFromMarkdown(),
gfmFootnoteFromMarkdown(),
gfmStrikethroughFromMarkdown(),
gfmTableFromMarkdown(),
gfmTaskListItemFromMarkdown()
];
}
function gfmToMarkdown(options) {
return {
extensions: [
gfmAutolinkLiteralToMarkdown(),
gfmFootnoteToMarkdown(options),
gfmStrikethroughToMarkdown(),
gfmTableToMarkdown(options),
gfmTaskListItemToMarkdown()
]
};
}
// node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js
var wwwPrefix = {
tokenize: tokenizeWwwPrefix,
partial: true
};
var domain = {
tokenize: tokenizeDomain,
partial: true
};
var path2 = {
tokenize: tokenizePath,
partial: true
};
var trail = {
tokenize: tokenizeTrail,
partial: true
};
var emailDomainDotTrail = {
tokenize: tokenizeEmailDomainDotTrail,
partial: true
};
var wwwAutolink = {
name: "wwwAutolink",
tokenize: tokenizeWwwAutolink,
previous: previousWww
};
var protocolAutolink = {
name: "protocolAutolink",
tokenize: tokenizeProtocolAutolink,
previous: previousProtocol
};
var emailAutolink = {
name: "emailAutolink",
tokenize: tokenizeEmailAutolink,
previous: previousEmail
};
var text4 = {};
function gfmAutolinkLiteral() {
return {
text: text4
};
}
var code3 = 48;
while (code3 < 123) {
text4[code3] = emailAutolink;
code3++;
if (code3 === 58)
code3 = 65;
else if (code3 === 91)
code3 = 97;
}
text4[43] = emailAutolink;
text4[45] = emailAutolink;
text4[46] = emailAutolink;
text4[95] = emailAutolink;
text4[72] = [emailAutolink, protocolAutolink];
text4[104] = [emailAutolink, protocolAutolink];
text4[87] = [emailAutolink, wwwAutolink];
text4[119] = [emailAutolink, wwwAutolink];
function tokenizeEmailAutolink(effects, ok3, nok) {
const self = this;
let dot;
let data;
return start;
function start(code4) {
if (!gfmAtext(code4) || !previousEmail.call(self, self.previous) || previousUnbalanced(self.events)) {
return nok(code4);
}
effects.enter("literalAutolink");
effects.enter("literalAutolinkEmail");
return atext(code4);
}
function atext(code4) {
if (gfmAtext(code4)) {
effects.consume(code4);
return atext;
}
if (code4 === 64) {
effects.consume(code4);
return emailDomain;
}
return nok(code4);
}
function emailDomain(code4) {
if (code4 === 46) {
return effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code4);
}
if (code4 === 45 || code4 === 95 || asciiAlphanumeric(code4)) {
data = true;
effects.consume(code4);
return emailDomain;
}
return emailDomainAfter(code4);
}
function emailDomainDot(code4) {
effects.consume(code4);
dot = true;
return emailDomain;
}
function emailDomainAfter(code4) {
if (data && dot && asciiAlpha(self.previous)) {
effects.exit("literalAutolinkEmail");
effects.exit("literalAutolink");
return ok3(code4);
}
return nok(code4);
}
}
function tokenizeWwwAutolink(effects, ok3, nok) {
const self = this;
return wwwStart;
function wwwStart(code4) {
if (code4 !== 87 && code4 !== 119 || !previousWww.call(self, self.previous) || previousUnbalanced(self.events)) {
return nok(code4);
}
effects.enter("literalAutolink");
effects.enter("literalAutolinkWww");
return effects.check(wwwPrefix, effects.attempt(domain, effects.attempt(path2, wwwAfter), nok), nok)(code4);
}
function wwwAfter(code4) {
effects.exit("literalAutolinkWww");
effects.exit("literalAutolink");
return ok3(code4);
}
}
function tokenizeProtocolAutolink(effects, ok3, nok) {
const self = this;
let buffer = "";
let seen = false;
return protocolStart;
function protocolStart(code4) {
if ((code4 === 72 || code4 === 104) && previousProtocol.call(self, self.previous) && !previousUnbalanced(self.events)) {
effects.enter("literalAutolink");
effects.enter("literalAutolinkHttp");
buffer += String.fromCodePoint(code4);
effects.consume(code4);
return protocolPrefixInside;
}
return nok(code4);
}
function protocolPrefixInside(code4) {
if (asciiAlpha(code4) && buffer.length < 5) {
buffer += String.fromCodePoint(code4);
effects.consume(code4);
return protocolPrefixInside;
}
if (code4 === 58) {
const protocol = buffer.toLowerCase();
if (protocol === "http" || protocol === "https") {
effects.consume(code4);
return protocolSlashesInside;
}
}
return nok(code4);
}
function protocolSlashesInside(code4) {
if (code4 === 47) {
effects.consume(code4);
if (seen) {
return afterProtocol;
}
seen = true;
return protocolSlashesInside;
}
return nok(code4);
}
function afterProtocol(code4) {
return code4 === null || asciiControl(code4) || markdownLineEndingOrSpace(code4) || unicodeWhitespace(code4) || unicodePunctuation(code4) ? nok(code4) : effects.attempt(domain, effects.attempt(path2, protocolAfter), nok)(code4);
}
function protocolAfter(code4) {
effects.exit("literalAutolinkHttp");
effects.exit("literalAutolink");
return ok3(code4);
}
}
function tokenizeWwwPrefix(effects, ok3, nok) {
let size = 0;
return wwwPrefixInside;
function wwwPrefixInside(code4) {
if ((code4 === 87 || code4 === 119) && size < 3) {
size++;
effects.consume(code4);
return wwwPrefixInside;
}
if (code4 === 46 && size === 3) {
effects.consume(code4);
return wwwPrefixAfter;
}
return nok(code4);
}
function wwwPrefixAfter(code4) {
return code4 === null ? nok(code4) : ok3(code4);
}
}
function tokenizeDomain(effects, ok3, nok) {
let underscoreInLastSegment;
let underscoreInLastLastSegment;
let seen;
return domainInside;
function domainInside(code4) {
if (code4 === 46 || code4 === 95) {
return effects.check(trail, domainAfter, domainAtPunctuation)(code4);
}
if (code4 === null || markdownLineEndingOrSpace(code4) || unicodeWhitespace(code4) || code4 !== 45 && unicodePunctuation(code4)) {
return domainAfter(code4);
}
seen = true;
effects.consume(code4);
return domainInside;
}
function domainAtPunctuation(code4) {
if (code4 === 95) {
underscoreInLastSegment = true;
} else {
underscoreInLastLastSegment = underscoreInLastSegment;
underscoreInLastSegment = void 0;
}
effects.consume(code4);
return domainInside;
}
function domainAfter(code4) {
if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) {
return nok(code4);
}
return ok3(code4);
}
}
function tokenizePath(effects, ok3) {
let sizeOpen = 0;
let sizeClose = 0;
return pathInside;
function pathInside(code4) {
if (code4 === 40) {
sizeOpen++;
effects.consume(code4);
return pathInside;
}
if (code4 === 41 && sizeClose < sizeOpen) {
return pathAtPunctuation(code4);
}
if (code4 === 33 || code4 === 34 || code4 === 38 || code4 === 39 || code4 === 41 || code4 === 42 || code4 === 44 || code4 === 46 || code4 === 58 || code4 === 59 || code4 === 60 || code4 === 63 || code4 === 93 || code4 === 95 || code4 === 126) {
return effects.check(trail, ok3, pathAtPunctuation)(code4);
}
if (code4 === null || markdownLineEndingOrSpace(code4) || unicodeWhitespace(code4)) {
return ok3(code4);
}
effects.consume(code4);
return pathInside;
}
function pathAtPunctuation(code4) {
if (code4 === 41) {
sizeClose++;
}
effects.consume(code4);
return pathInside;
}
}
function tokenizeTrail(effects, ok3, nok) {
return trail2;
function trail2(code4) {
if (code4 === 33 || code4 === 34 || code4 === 39 || code4 === 41 || code4 === 42 || code4 === 44 || code4 === 46 || code4 === 58 || code4 === 59 || code4 === 63 || code4 === 95 || code4 === 126) {
effects.consume(code4);
return trail2;
}
if (code4 === 38) {
effects.consume(code4);
return trailCharacterReferenceStart;
}
if (code4 === 93) {
effects.consume(code4);
return trailBracketAfter;
}
if (
// `<` is an end.
code4 === 60 || // So is whitespace.
code4 === null || markdownLineEndingOrSpace(code4) || unicodeWhitespace(code4)
) {
return ok3(code4);
}
return nok(code4);
}
function trailBracketAfter(code4) {
if (code4 === null || code4 === 40 || code4 === 91 || markdownLineEndingOrSpace(code4) || unicodeWhitespace(code4)) {
return ok3(code4);
}
return trail2(code4);
}
function trailCharacterReferenceStart(code4) {
return asciiAlpha(code4) ? trailCharacterReferenceInside(code4) : nok(code4);
}
function trailCharacterReferenceInside(code4) {
if (code4 === 59) {
effects.consume(code4);
return trail2;
}
if (asciiAlpha(code4)) {
effects.consume(code4);
return trailCharacterReferenceInside;
}
return nok(code4);
}
}
function tokenizeEmailDomainDotTrail(effects, ok3, nok) {
return start;
function start(code4) {
effects.consume(code4);
return after;
}
function after(code4) {
return asciiAlphanumeric(code4) ? nok(code4) : ok3(code4);
}
}
function previousWww(code4) {
return code4 === null || code4 === 40 || code4 === 42 || code4 === 95 || code4 === 91 || code4 === 93 || code4 === 126 || markdownLineEndingOrSpace(code4);
}
function previousProtocol(code4) {
return !asciiAlpha(code4);
}
function previousEmail(code4) {
return !(code4 === 47 || gfmAtext(code4));
}
function gfmAtext(code4) {
return code4 === 43 || code4 === 45 || code4 === 46 || code4 === 95 || asciiAlphanumeric(code4);
}
function previousUnbalanced(events) {
let index2 = events.length;
let result = false;
while (index2--) {
const token = events[index2][1];
if ((token.type === "labelLink" || token.type === "labelImage") && !token._balanced) {
result = true;
break;
}
if (token._gfmAutolinkLiteralWalkedInto) {
result = false;
break;
}
}
if (events.length > 0 && !result) {
events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;
}
return result;
}
// node_modules/micromark-extension-gfm-footnote/lib/syntax.js
var indent = {
tokenize: tokenizeIndent2,
partial: true
};
function gfmFootnote() {
return {
document: {
[91]: {
name: "gfmFootnoteDefinition",
tokenize: tokenizeDefinitionStart,
continuation: {
tokenize: tokenizeDefinitionContinuation
},
exit: gfmFootnoteDefinitionEnd
}
},
text: {
[91]: {
name: "gfmFootnoteCall",
tokenize: tokenizeGfmFootnoteCall
},
[93]: {
name: "gfmPotentialFootnoteCall",
add: "after",
tokenize: tokenizePotentialGfmFootnoteCall,
resolveTo: resolveToPotentialGfmFootnoteCall
}
}
};
}
function tokenizePotentialGfmFootnoteCall(effects, ok3, nok) {
const self = this;
let index2 = self.events.length;
const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);
let labelStart;
while (index2--) {
const token = self.events[index2][1];
if (token.type === "labelImage") {
labelStart = token;
break;
}
if (token.type === "gfmFootnoteCall" || token.type === "labelLink" || token.type === "label" || token.type === "image" || token.type === "link") {
break;
}
}
return start;
function start(code4) {
if (!labelStart || !labelStart._balanced) {
return nok(code4);
}
const id = normalizeIdentifier(self.sliceSerialize({
start: labelStart.end,
end: self.now()
}));
if (id.codePointAt(0) !== 94 || !defined.includes(id.slice(1))) {
return nok(code4);
}
effects.enter("gfmFootnoteCallLabelMarker");
effects.consume(code4);
effects.exit("gfmFootnoteCallLabelMarker");
return ok3(code4);
}
}
function resolveToPotentialGfmFootnoteCall(events, context) {
let index2 = events.length;
let labelStart;
while (index2--) {
if (events[index2][1].type === "labelImage" && events[index2][0] === "enter") {
labelStart = events[index2][1];
break;
}
}
events[index2 + 1][1].type = "data";
events[index2 + 3][1].type = "gfmFootnoteCallLabelMarker";
const call = {
type: "gfmFootnoteCall",
start: Object.assign({}, events[index2 + 3][1].start),
end: Object.assign({}, events[events.length - 1][1].end)
};
const marker = {
type: "gfmFootnoteCallMarker",
start: Object.assign({}, events[index2 + 3][1].end),
end: Object.assign({}, events[index2 + 3][1].end)
};
marker.end.column++;
marker.end.offset++;
marker.end._bufferIndex++;
const string3 = {
type: "gfmFootnoteCallString",
start: Object.assign({}, marker.end),
end: Object.assign({}, events[events.length - 1][1].start)
};
const chunk = {
type: "chunkString",
contentType: "string",
start: Object.assign({}, string3.start),
end: Object.assign({}, string3.end)
};
const replacement = [
// Take the `labelImageMarker` (now `data`, the `!`)
events[index2 + 1],
events[index2 + 2],
["enter", call, context],
// The `[`
events[index2 + 3],
events[index2 + 4],
// The `^`.
["enter", marker, context],
["exit", marker, context],
// Everything in between.
["enter", string3, context],
["enter", chunk, context],
["exit", chunk, context],
["exit", string3, context],
// The ending (`]`, properly parsed and labelled).
events[events.length - 2],
events[events.length - 1],
["exit", call, context]
];
events.splice(index2, events.length - index2 + 1, ...replacement);
return events;
}
function tokenizeGfmFootnoteCall(effects, ok3, nok) {
const self = this;
const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);
let size = 0;
let data;
return start;
function start(code4) {
effects.enter("gfmFootnoteCall");
effects.enter("gfmFootnoteCallLabelMarker");
effects.consume(code4);
effects.exit("gfmFootnoteCallLabelMarker");
return callStart;
}
function callStart(code4) {
if (code4 !== 94)
return nok(code4);
effects.enter("gfmFootnoteCallMarker");
effects.consume(code4);
effects.exit("gfmFootnoteCallMarker");
effects.enter("gfmFootnoteCallString");
effects.enter("chunkString").contentType = "string";
return callData;
}
function callData(code4) {
if (
// Too long.
size > 999 || // Closing brace with nothing.
code4 === 93 && !data || // Space or tab is not supported by GFM for some reason.
// `\n` and `[` not being supported makes sense.
code4 === null || code4 === 91 || markdownLineEndingOrSpace(code4)
) {
return nok(code4);
}
if (code4 === 93) {
effects.exit("chunkString");
const token = effects.exit("gfmFootnoteCallString");
if (!defined.includes(normalizeIdentifier(self.sliceSerialize(token)))) {
return nok(code4);
}
effects.enter("gfmFootnoteCallLabelMarker");
effects.consume(code4);
effects.exit("gfmFootnoteCallLabelMarker");
effects.exit("gfmFootnoteCall");
return ok3;
}
if (!markdownLineEndingOrSpace(code4)) {
data = true;
}
size++;
effects.consume(code4);
return code4 === 92 ? callEscape : callData;
}
function callEscape(code4) {
if (code4 === 91 || code4 === 92 || code4 === 93) {
effects.consume(code4);
size++;
return callData;
}
return callData(code4);
}
}
function tokenizeDefinitionStart(effects, ok3, nok) {
const self = this;
const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);
let identifier;
let size = 0;
let data;
return start;
function start(code4) {
effects.enter("gfmFootnoteDefinition")._container = true;
effects.enter("gfmFootnoteDefinitionLabel");
effects.enter("gfmFootnoteDefinitionLabelMarker");
effects.consume(code4);
effects.exit("gfmFootnoteDefinitionLabelMarker");
return labelAtMarker;
}
function labelAtMarker(code4) {
if (code4 === 94) {
effects.enter("gfmFootnoteDefinitionMarker");
effects.consume(code4);
effects.exit("gfmFootnoteDefinitionMarker");
effects.enter("gfmFootnoteDefinitionLabelString");
effects.enter("chunkString").contentType = "string";
return labelInside;
}
return nok(code4);
}
function labelInside(code4) {
if (
// Too long.
size > 999 || // Closing brace with nothing.
code4 === 93 && !data || // Space or tab is not supported by GFM for some reason.
// `\n` and `[` not being supported makes sense.
code4 === null || code4 === 91 || markdownLineEndingOrSpace(code4)
) {
return nok(code4);
}
if (code4 === 93) {
effects.exit("chunkString");
const token = effects.exit("gfmFootnoteDefinitionLabelString");
identifier = normalizeIdentifier(self.sliceSerialize(token));
effects.enter("gfmFootnoteDefinitionLabelMarker");
effects.consume(code4);
effects.exit("gfmFootnoteDefinitionLabelMarker");
effects.exit("gfmFootnoteDefinitionLabel");
return labelAfter;
}
if (!markdownLineEndingOrSpace(code4)) {
data = true;
}
size++;
effects.consume(code4);
return code4 === 92 ? labelEscape : labelInside;
}
function labelEscape(code4) {
if (code4 === 91 || code4 === 92 || code4 === 93) {
effects.consume(code4);
size++;
return labelInside;
}
return labelInside(code4);
}
function labelAfter(code4) {
if (code4 === 58) {
effects.enter("definitionMarker");
effects.consume(code4);
effects.exit("definitionMarker");
if (!defined.includes(identifier)) {
defined.push(identifier);
}
return factorySpace(effects, whitespaceAfter, "gfmFootnoteDefinitionWhitespace");
}
return nok(code4);
}
function whitespaceAfter(code4) {
return ok3(code4);
}
}
function tokenizeDefinitionContinuation(effects, ok3, nok) {
return effects.check(blankLine, ok3, effects.attempt(indent, ok3, nok));
}
function gfmFootnoteDefinitionEnd(effects) {
effects.exit("gfmFootnoteDefinition");
}
function tokenizeIndent2(effects, ok3, nok) {
const self = this;
return factorySpace(effects, afterPrefix, "gfmFootnoteDefinitionIndent", 4 + 1);
function afterPrefix(code4) {
const tail = self.events[self.events.length - 1];
return tail && tail[1].type === "gfmFootnoteDefinitionIndent" && tail[2].sliceSerialize(tail[1], true).length === 4 ? ok3(code4) : nok(code4);
}
}
// node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js
function gfmStrikethrough(options) {
const options_ = options || {};
let single = options_.singleTilde;
const tokenizer = {
name: "strikethrough",
tokenize: tokenizeStrikethrough,
resolveAll: resolveAllStrikethrough
};
if (single === null || single === void 0) {
single = true;
}
return {
text: {
[126]: tokenizer
},
insideSpan: {
null: [tokenizer]
},
attentionMarkers: {
null: [126]
}
};
function resolveAllStrikethrough(events, context) {
let index2 = -1;
while (++index2 < events.length) {
if (events[index2][0] === "enter" && events[index2][1].type === "strikethroughSequenceTemporary" && events[index2][1]._close) {
let open = index2;
while (open--) {
if (events[open][0] === "exit" && events[open][1].type === "strikethroughSequenceTemporary" && events[open][1]._open && // If the sizes are the same:
events[index2][1].end.offset - events[index2][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {
events[index2][1].type = "strikethroughSequence";
events[open][1].type = "strikethroughSequence";
const strikethrough = {
type: "strikethrough",
start: Object.assign({}, events[open][1].start),
end: Object.assign({}, events[index2][1].end)
};
const text5 = {
type: "strikethroughText",
start: Object.assign({}, events[open][1].end),
end: Object.assign({}, events[index2][1].start)
};
const nextEvents = [["enter", strikethrough, context], ["enter", events[open][1], context], ["exit", events[open][1], context], ["enter", text5, context]];
const insideSpan2 = context.parser.constructs.insideSpan.null;
if (insideSpan2) {
splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan2, events.slice(open + 1, index2), context));
}
splice(nextEvents, nextEvents.length, 0, [["exit", text5, context], ["enter", events[index2][1], context], ["exit", events[index2][1], context], ["exit", strikethrough, context]]);
splice(events, open - 1, index2 - open + 3, nextEvents);
index2 = open + nextEvents.length - 2;
break;
}
}
}
}
index2 = -1;
while (++index2 < events.length) {
if (events[index2][1].type === "strikethroughSequenceTemporary") {
events[index2][1].type = "data";
}
}
return events;
}
function tokenizeStrikethrough(effects, ok3, nok) {
const previous4 = this.previous;
const events = this.events;
let size = 0;
return start;
function start(code4) {
if (previous4 === 126 && events[events.length - 1][1].type !== "characterEscape") {
return nok(code4);
}
effects.enter("strikethroughSequenceTemporary");
return more(code4);
}
function more(code4) {
const before = classifyCharacter(previous4);
if (code4 === 126) {
if (size > 1)
return nok(code4);
effects.consume(code4);
size++;
return more;
}
if (size < 2 && !single)
return nok(code4);
const token = effects.exit("strikethroughSequenceTemporary");
const after = classifyCharacter(code4);
token._open = !after || after === 2 && Boolean(before);
token._close = !before || before === 2 && Boolean(after);
return ok3(code4);
}
}
}
// node_modules/micromark-extension-gfm-table/lib/edit-map.js
var EditMap = class {
/**
* Create a new edit map.
*/
constructor() {
this.map = [];
}
/**
* Create an edit: a remove and/or add at a certain place.
*
* @param {number} index
* @param {number} remove
* @param {Array} add
* @returns {undefined}
*/
add(index2, remove, add) {
addImplementation(this, index2, remove, add);
}
// To do: add this when moving to `micromark`.
// /**
// * Create an edit: but insert `add` before existing additions.
// *
// * @param {number} index
// * @param {number} remove
// * @param {Array} add
// * @returns {undefined}
// */
// addBefore(index, remove, add) {
// addImplementation(this, index, remove, add, true)
// }
/**
* Done, change the events.
*
* @param {Array} events
* @returns {undefined}
*/
consume(events) {
this.map.sort(function(a, b) {
return a[0] - b[0];
});
if (this.map.length === 0) {
return;
}
let index2 = this.map.length;
const vecs = [];
while (index2 > 0) {
index2 -= 1;
vecs.push(events.slice(this.map[index2][0] + this.map[index2][1]), this.map[index2][2]);
events.length = this.map[index2][0];
}
vecs.push(events.slice());
events.length = 0;
let slice = vecs.pop();
while (slice) {
for (const element2 of slice) {
events.push(element2);
}
slice = vecs.pop();
}
this.map.length = 0;
}
};
function addImplementation(editMap, at, remove, add) {
let index2 = 0;
if (remove === 0 && add.length === 0) {
return;
}
while (index2 < editMap.map.length) {
if (editMap.map[index2][0] === at) {
editMap.map[index2][1] += remove;
editMap.map[index2][2].push(...add);
return;
}
index2 += 1;
}
editMap.map.push([at, remove, add]);
}
// node_modules/micromark-extension-gfm-table/lib/infer.js
function gfmTableAlign(events, index2) {
let inDelimiterRow = false;
const align = [];
while (index2 < events.length) {
const event = events[index2];
if (inDelimiterRow) {
if (event[0] === "enter") {
if (event[1].type === "tableContent") {
align.push(events[index2 + 1][1].type === "tableDelimiterMarker" ? "left" : "none");
}
} else if (event[1].type === "tableContent") {
if (events[index2 - 1][1].type === "tableDelimiterMarker") {
const alignIndex = align.length - 1;
align[alignIndex] = align[alignIndex] === "left" ? "center" : "right";
}
} else if (event[1].type === "tableDelimiterRow") {
break;
}
} else if (event[0] === "enter" && event[1].type === "tableDelimiterRow") {
inDelimiterRow = true;
}
index2 += 1;
}
return align;
}
// node_modules/micromark-extension-gfm-table/lib/syntax.js
function gfmTable() {
return {
flow: {
null: {
name: "table",
tokenize: tokenizeTable,
resolveAll: resolveTable
}
}
};
}
function tokenizeTable(effects, ok3, nok) {
const self = this;
let size = 0;
let sizeB = 0;
let seen;
return start;
function start(code4) {
let index2 = self.events.length - 1;
while (index2 > -1) {
const type = self.events[index2][1].type;
if (type === "lineEnding" || // Note: markdown-rs uses `whitespace` instead of `linePrefix`
type === "linePrefix")
index2--;
else
break;
}
const tail = index2 > -1 ? self.events[index2][1].type : null;
const next = tail === "tableHead" || tail === "tableRow" ? bodyRowStart : headRowBefore;
if (next === bodyRowStart && self.parser.lazy[self.now().line]) {
return nok(code4);
}
return next(code4);
}
function headRowBefore(code4) {
effects.enter("tableHead");
effects.enter("tableRow");
return headRowStart(code4);
}
function headRowStart(code4) {
if (code4 === 124) {
return headRowBreak(code4);
}
seen = true;
sizeB += 1;
return headRowBreak(code4);
}
function headRowBreak(code4) {
if (code4 === null) {
return nok(code4);
}
if (markdownLineEnding(code4)) {
if (sizeB > 1) {
sizeB = 0;
self.interrupt = true;
effects.exit("tableRow");
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return headDelimiterStart;
}
return nok(code4);
}
if (markdownSpace(code4)) {
return factorySpace(effects, headRowBreak, "whitespace")(code4);
}
sizeB += 1;
if (seen) {
seen = false;
size += 1;
}
if (code4 === 124) {
effects.enter("tableCellDivider");
effects.consume(code4);
effects.exit("tableCellDivider");
seen = true;
return headRowBreak;
}
effects.enter("data");
return headRowData(code4);
}
function headRowData(code4) {
if (code4 === null || code4 === 124 || markdownLineEndingOrSpace(code4)) {
effects.exit("data");
return headRowBreak(code4);
}
effects.consume(code4);
return code4 === 92 ? headRowEscape : headRowData;
}
function headRowEscape(code4) {
if (code4 === 92 || code4 === 124) {
effects.consume(code4);
return headRowData;
}
return headRowData(code4);
}
function headDelimiterStart(code4) {
self.interrupt = false;
if (self.parser.lazy[self.now().line]) {
return nok(code4);
}
effects.enter("tableDelimiterRow");
seen = false;
if (markdownSpace(code4)) {
return factorySpace(effects, headDelimiterBefore, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code4);
}
return headDelimiterBefore(code4);
}
function headDelimiterBefore(code4) {
if (code4 === 45 || code4 === 58) {
return headDelimiterValueBefore(code4);
}
if (code4 === 124) {
seen = true;
effects.enter("tableCellDivider");
effects.consume(code4);
effects.exit("tableCellDivider");
return headDelimiterCellBefore;
}
return headDelimiterNok(code4);
}
function headDelimiterCellBefore(code4) {
if (markdownSpace(code4)) {
return factorySpace(effects, headDelimiterValueBefore, "whitespace")(code4);
}
return headDelimiterValueBefore(code4);
}
function headDelimiterValueBefore(code4) {
if (code4 === 58) {
sizeB += 1;
seen = true;
effects.enter("tableDelimiterMarker");
effects.consume(code4);
effects.exit("tableDelimiterMarker");
return headDelimiterLeftAlignmentAfter;
}
if (code4 === 45) {
sizeB += 1;
return headDelimiterLeftAlignmentAfter(code4);
}
if (code4 === null || markdownLineEnding(code4)) {
return headDelimiterCellAfter(code4);
}
return headDelimiterNok(code4);
}
function headDelimiterLeftAlignmentAfter(code4) {
if (code4 === 45) {
effects.enter("tableDelimiterFiller");
return headDelimiterFiller(code4);
}
return headDelimiterNok(code4);
}
function headDelimiterFiller(code4) {
if (code4 === 45) {
effects.consume(code4);
return headDelimiterFiller;
}
if (code4 === 58) {
seen = true;
effects.exit("tableDelimiterFiller");
effects.enter("tableDelimiterMarker");
effects.consume(code4);
effects.exit("tableDelimiterMarker");
return headDelimiterRightAlignmentAfter;
}
effects.exit("tableDelimiterFiller");
return headDelimiterRightAlignmentAfter(code4);
}
function headDelimiterRightAlignmentAfter(code4) {
if (markdownSpace(code4)) {
return factorySpace(effects, headDelimiterCellAfter, "whitespace")(code4);
}
return headDelimiterCellAfter(code4);
}
function headDelimiterCellAfter(code4) {
if (code4 === 124) {
return headDelimiterBefore(code4);
}
if (code4 === null || markdownLineEnding(code4)) {
if (!seen || size !== sizeB) {
return headDelimiterNok(code4);
}
effects.exit("tableDelimiterRow");
effects.exit("tableHead");
return ok3(code4);
}
return headDelimiterNok(code4);
}
function headDelimiterNok(code4) {
return nok(code4);
}
function bodyRowStart(code4) {
effects.enter("tableRow");
return bodyRowBreak(code4);
}
function bodyRowBreak(code4) {
if (code4 === 124) {
effects.enter("tableCellDivider");
effects.consume(code4);
effects.exit("tableCellDivider");
return bodyRowBreak;
}
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("tableRow");
return ok3(code4);
}
if (markdownSpace(code4)) {
return factorySpace(effects, bodyRowBreak, "whitespace")(code4);
}
effects.enter("data");
return bodyRowData(code4);
}
function bodyRowData(code4) {
if (code4 === null || code4 === 124 || markdownLineEndingOrSpace(code4)) {
effects.exit("data");
return bodyRowBreak(code4);
}
effects.consume(code4);
return code4 === 92 ? bodyRowEscape : bodyRowData;
}
function bodyRowEscape(code4) {
if (code4 === 92 || code4 === 124) {
effects.consume(code4);
return bodyRowData;
}
return bodyRowData(code4);
}
}
function resolveTable(events, context) {
let index2 = -1;
let inFirstCellAwaitingPipe = true;
let rowKind = 0;
let lastCell = [0, 0, 0, 0];
let cell = [0, 0, 0, 0];
let afterHeadAwaitingFirstBodyRow = false;
let lastTableEnd = 0;
let currentTable;
let currentBody;
let currentCell;
const map3 = new EditMap();
while (++index2 < events.length) {
const event = events[index2];
const token = event[1];
if (event[0] === "enter") {
if (token.type === "tableHead") {
afterHeadAwaitingFirstBodyRow = false;
if (lastTableEnd !== 0) {
flushTableEnd(map3, context, lastTableEnd, currentTable, currentBody);
currentBody = void 0;
lastTableEnd = 0;
}
currentTable = {
type: "table",
start: Object.assign({}, token.start),
// Note: correct end is set later.
end: Object.assign({}, token.end)
};
map3.add(index2, 0, [["enter", currentTable, context]]);
} else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
inFirstCellAwaitingPipe = true;
currentCell = void 0;
lastCell = [0, 0, 0, 0];
cell = [0, index2 + 1, 0, 0];
if (afterHeadAwaitingFirstBodyRow) {
afterHeadAwaitingFirstBodyRow = false;
currentBody = {
type: "tableBody",
start: Object.assign({}, token.start),
// Note: correct end is set later.
end: Object.assign({}, token.end)
};
map3.add(index2, 0, [["enter", currentBody, context]]);
}
rowKind = token.type === "tableDelimiterRow" ? 2 : currentBody ? 3 : 1;
} else if (rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
inFirstCellAwaitingPipe = false;
if (cell[2] === 0) {
if (lastCell[1] !== 0) {
cell[0] = cell[1];
currentCell = flushCell(map3, context, lastCell, rowKind, void 0, currentCell);
lastCell = [0, 0, 0, 0];
}
cell[2] = index2;
}
} else if (token.type === "tableCellDivider") {
if (inFirstCellAwaitingPipe) {
inFirstCellAwaitingPipe = false;
} else {
if (lastCell[1] !== 0) {
cell[0] = cell[1];
currentCell = flushCell(map3, context, lastCell, rowKind, void 0, currentCell);
}
lastCell = cell;
cell = [lastCell[1], index2, 0, 0];
}
}
} else if (token.type === "tableHead") {
afterHeadAwaitingFirstBodyRow = true;
lastTableEnd = index2;
} else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
lastTableEnd = index2;
if (lastCell[1] !== 0) {
cell[0] = cell[1];
currentCell = flushCell(map3, context, lastCell, rowKind, index2, currentCell);
} else if (cell[1] !== 0) {
currentCell = flushCell(map3, context, cell, rowKind, index2, currentCell);
}
rowKind = 0;
} else if (rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
cell[3] = index2;
}
}
if (lastTableEnd !== 0) {
flushTableEnd(map3, context, lastTableEnd, currentTable, currentBody);
}
map3.consume(context.events);
index2 = -1;
while (++index2 < context.events.length) {
const event = context.events[index2];
if (event[0] === "enter" && event[1].type === "table") {
event[1]._align = gfmTableAlign(context.events, index2);
}
}
return events;
}
function flushCell(map3, context, range, rowKind, rowEnd, previousCell) {
const groupName = rowKind === 1 ? "tableHeader" : rowKind === 2 ? "tableDelimiter" : "tableData";
const valueName = "tableContent";
if (range[0] !== 0) {
previousCell.end = Object.assign({}, getPoint(context.events, range[0]));
map3.add(range[0], 0, [["exit", previousCell, context]]);
}
const now = getPoint(context.events, range[1]);
previousCell = {
type: groupName,
start: Object.assign({}, now),
// Note: correct end is set later.
end: Object.assign({}, now)
};
map3.add(range[1], 0, [["enter", previousCell, context]]);
if (range[2] !== 0) {
const relatedStart = getPoint(context.events, range[2]);
const relatedEnd = getPoint(context.events, range[3]);
const valueToken = {
type: valueName,
start: Object.assign({}, relatedStart),
end: Object.assign({}, relatedEnd)
};
map3.add(range[2], 0, [["enter", valueToken, context]]);
if (rowKind !== 2) {
const start = context.events[range[2]];
const end = context.events[range[3]];
start[1].end = Object.assign({}, end[1].end);
start[1].type = "chunkText";
start[1].contentType = "text";
if (range[3] > range[2] + 1) {
const a = range[2] + 1;
const b = range[3] - range[2] - 1;
map3.add(a, b, []);
}
}
map3.add(range[3] + 1, 0, [["exit", valueToken, context]]);
}
if (rowEnd !== void 0) {
previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));
map3.add(rowEnd, 0, [["exit", previousCell, context]]);
previousCell = void 0;
}
return previousCell;
}
function flushTableEnd(map3, context, index2, table2, tableBody) {
const exits = [];
const related = getPoint(context.events, index2);
if (tableBody) {
tableBody.end = Object.assign({}, related);
exits.push(["exit", tableBody, context]);
}
table2.end = Object.assign({}, related);
exits.push(["exit", table2, context]);
map3.add(index2 + 1, 0, exits);
}
function getPoint(events, index2) {
const event = events[index2];
const side = event[0] === "enter" ? "start" : "end";
return event[1][side];
}
// node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js
var tasklistCheck = {
name: "tasklistCheck",
tokenize: tokenizeTasklistCheck
};
function gfmTaskListItem() {
return {
text: {
[91]: tasklistCheck
}
};
}
function tokenizeTasklistCheck(effects, ok3, nok) {
const self = this;
return open;
function open(code4) {
if (
// Exit if there’s stuff before.
self.previous !== null || // Exit if not in the first content that is the first child of a list
// item.
!self._gfmTasklistFirstContentOfListItem
) {
return nok(code4);
}
effects.enter("taskListCheck");
effects.enter("taskListCheckMarker");
effects.consume(code4);
effects.exit("taskListCheckMarker");
return inside;
}
function inside(code4) {
if (markdownLineEndingOrSpace(code4)) {
effects.enter("taskListCheckValueUnchecked");
effects.consume(code4);
effects.exit("taskListCheckValueUnchecked");
return close;
}
if (code4 === 88 || code4 === 120) {
effects.enter("taskListCheckValueChecked");
effects.consume(code4);
effects.exit("taskListCheckValueChecked");
return close;
}
return nok(code4);
}
function close(code4) {
if (code4 === 93) {
effects.enter("taskListCheckMarker");
effects.consume(code4);
effects.exit("taskListCheckMarker");
effects.exit("taskListCheck");
return after;
}
return nok(code4);
}
function after(code4) {
if (markdownLineEnding(code4)) {
return ok3(code4);
}
if (markdownSpace(code4)) {
return effects.check({
tokenize: spaceThenNonSpace
}, ok3, nok)(code4);
}
return nok(code4);
}
}
function spaceThenNonSpace(effects, ok3, nok) {
return factorySpace(effects, after, "whitespace");
function after(code4) {
return code4 === null ? nok(code4) : ok3(code4);
}
}
// node_modules/micromark-extension-gfm/index.js
function gfm(options) {
return combineExtensions([
gfmAutolinkLiteral(),
gfmFootnote(),
gfmStrikethrough(options),
gfmTable(),
gfmTaskListItem()
]);
}
// node_modules/remark-gfm/lib/index.js
var emptyOptions2 = {};
function remarkGfm(options) {
const self = (
/** @type {Processor} */
this
);
const settings = options || emptyOptions2;
const data = self.data();
const micromarkExtensions = data.micromarkExtensions || (data.micromarkExtensions = []);
const fromMarkdownExtensions = data.fromMarkdownExtensions || (data.fromMarkdownExtensions = []);
const toMarkdownExtensions = data.toMarkdownExtensions || (data.toMarkdownExtensions = []);
micromarkExtensions.push(gfm(settings));
fromMarkdownExtensions.push(gfmFromMarkdown());
toMarkdownExtensions.push(gfmToMarkdown(settings));
}
// node_modules/mdast-util-math/lib/index.js
function mathFromMarkdown() {
return {
enter: {
mathFlow: enterMathFlow,
mathFlowFenceMeta: enterMathFlowMeta,
mathText: enterMathText
},
exit: {
mathFlow: exitMathFlow,
mathFlowFence: exitMathFlowFence,
mathFlowFenceMeta: exitMathFlowMeta,
mathFlowValue: exitMathData,
mathText: exitMathText,
mathTextData: exitMathData
}
};
function enterMathFlow(token) {
const code4 = {
type: "element",
tagName: "code",
properties: { className: ["language-math", "math-display"] },
children: []
};
this.enter(
{
type: "math",
meta: null,
value: "",
data: { hName: "pre", hChildren: [code4] }
},
token
);
}
function enterMathFlowMeta() {
this.buffer();
}
function exitMathFlowMeta() {
const data = this.resume();
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "math");
node2.meta = data;
}
function exitMathFlowFence() {
if (this.data.mathFlowInside)
return;
this.buffer();
this.data.mathFlowInside = true;
}
function exitMathFlow(token) {
const data = this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, "");
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "math");
this.exit(token);
node2.value = data;
const code4 = (
/** @type {HastElement} */
node2.data.hChildren[0]
);
ok(code4.type === "element");
ok(code4.tagName === "code");
code4.children.push({ type: "text", value: data });
this.data.mathFlowInside = void 0;
}
function enterMathText(token) {
this.enter(
{
type: "inlineMath",
value: "",
data: {
hName: "code",
hProperties: { className: ["language-math", "math-inline"] },
hChildren: []
}
},
token
);
this.buffer();
}
function exitMathText(token) {
const data = this.resume();
const node2 = this.stack[this.stack.length - 1];
ok(node2.type === "inlineMath");
this.exit(token);
node2.value = data;
const children = (
/** @type {Array} */
// @ts-expect-error: we defined it in `enterMathFlow`.
node2.data.hChildren
);
children.push({ type: "text", value: data });
}
function exitMathData(token) {
this.config.enter.data.call(this, token);
this.config.exit.data.call(this, token);
}
}
function mathToMarkdown(options) {
let single = (options || {}).singleDollarTextMath;
if (single === null || single === void 0) {
single = true;
}
inlineMath.peek = inlineMathPeek;
return {
unsafe: [
{ character: "\r", inConstruct: "mathFlowMeta" },
{ character: "\n", inConstruct: "mathFlowMeta" },
{
character: "$",
after: single ? void 0 : "\\$",
inConstruct: "phrasing"
},
{ character: "$", inConstruct: "mathFlowMeta" },
{ atBreak: true, character: "$", after: "\\$" }
],
handlers: { math: math2, inlineMath }
};
function math2(node2, _, state, info) {
const raw = node2.value || "";
const tracker = state.createTracker(info);
const sequence = "$".repeat(Math.max(longestStreak(raw, "$") + 1, 2));
const exit3 = state.enter("mathFlow");
let value = tracker.move(sequence);
if (node2.meta) {
const subexit = state.enter("mathFlowMeta");
value += tracker.move(
state.safe(node2.meta, __spreadValues({
after: "\n",
before: value,
encode: ["$"]
}, tracker.current()))
);
subexit();
}
value += tracker.move("\n");
if (raw) {
value += tracker.move(raw + "\n");
}
value += tracker.move(sequence);
exit3();
return value;
}
function inlineMath(node2, _, state) {
let value = node2.value || "";
let size = 1;
if (!single)
size++;
while (new RegExp("(^|[^$])" + "\\$".repeat(size) + "([^$]|$)").test(value)) {
size++;
}
const sequence = "$".repeat(size);
if (
// Contains non-space.
/[^ \r\n]/.test(value) && // Starts with space and ends with space.
(/^[ \r\n]/.test(value) && /[ \r\n]$/.test(value) || // Starts or ends with dollar.
/^\$|\$$/.test(value))
) {
value = " " + value + " ";
}
let index2 = -1;
while (++index2 < state.unsafe.length) {
const pattern = state.unsafe[index2];
if (!pattern.atBreak)
continue;
const expression = state.compilePattern(pattern);
let match;
while (match = expression.exec(value)) {
let position2 = match.index;
if (value.codePointAt(position2) === 10 && value.codePointAt(position2 - 1) === 13) {
position2--;
}
value = value.slice(0, position2) + " " + value.slice(match.index + 1);
}
}
return sequence + value + sequence;
}
function inlineMathPeek() {
return "$";
}
}
// node_modules/micromark-extension-math/lib/math-flow.js
var mathFlow = {
tokenize: tokenizeMathFenced,
concrete: true,
name: "mathFlow"
};
var nonLazyContinuation2 = {
tokenize: tokenizeNonLazyContinuation2,
partial: true
};
function tokenizeMathFenced(effects, ok3, nok) {
const self = this;
const tail = self.events[self.events.length - 1];
const initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0;
let sizeOpen = 0;
return start;
function start(code4) {
effects.enter("mathFlow");
effects.enter("mathFlowFence");
effects.enter("mathFlowFenceSequence");
return sequenceOpen(code4);
}
function sequenceOpen(code4) {
if (code4 === 36) {
effects.consume(code4);
sizeOpen++;
return sequenceOpen;
}
if (sizeOpen < 2) {
return nok(code4);
}
effects.exit("mathFlowFenceSequence");
return factorySpace(effects, metaBefore, "whitespace")(code4);
}
function metaBefore(code4) {
if (code4 === null || markdownLineEnding(code4)) {
return metaAfter(code4);
}
effects.enter("mathFlowFenceMeta");
effects.enter("chunkString", {
contentType: "string"
});
return meta(code4);
}
function meta(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("chunkString");
effects.exit("mathFlowFenceMeta");
return metaAfter(code4);
}
if (code4 === 36) {
return nok(code4);
}
effects.consume(code4);
return meta;
}
function metaAfter(code4) {
effects.exit("mathFlowFence");
if (self.interrupt) {
return ok3(code4);
}
return effects.attempt(nonLazyContinuation2, beforeNonLazyContinuation, after)(code4);
}
function beforeNonLazyContinuation(code4) {
return effects.attempt({
tokenize: tokenizeClosingFence,
partial: true
}, after, contentStart)(code4);
}
function contentStart(code4) {
return (initialSize ? factorySpace(effects, beforeContentChunk, "linePrefix", initialSize + 1) : beforeContentChunk)(code4);
}
function beforeContentChunk(code4) {
if (code4 === null) {
return after(code4);
}
if (markdownLineEnding(code4)) {
return effects.attempt(nonLazyContinuation2, beforeNonLazyContinuation, after)(code4);
}
effects.enter("mathFlowValue");
return contentChunk(code4);
}
function contentChunk(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects.exit("mathFlowValue");
return beforeContentChunk(code4);
}
effects.consume(code4);
return contentChunk;
}
function after(code4) {
effects.exit("mathFlow");
return ok3(code4);
}
function tokenizeClosingFence(effects2, ok4, nok2) {
let size = 0;
return factorySpace(effects2, beforeSequenceClose, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4);
function beforeSequenceClose(code4) {
effects2.enter("mathFlowFence");
effects2.enter("mathFlowFenceSequence");
return sequenceClose(code4);
}
function sequenceClose(code4) {
if (code4 === 36) {
size++;
effects2.consume(code4);
return sequenceClose;
}
if (size < sizeOpen) {
return nok2(code4);
}
effects2.exit("mathFlowFenceSequence");
return factorySpace(effects2, afterSequenceClose, "whitespace")(code4);
}
function afterSequenceClose(code4) {
if (code4 === null || markdownLineEnding(code4)) {
effects2.exit("mathFlowFence");
return ok4(code4);
}
return nok2(code4);
}
}
}
function tokenizeNonLazyContinuation2(effects, ok3, nok) {
const self = this;
return start;
function start(code4) {
if (code4 === null) {
return ok3(code4);
}
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return lineStart;
}
function lineStart(code4) {
return self.parser.lazy[self.now().line] ? nok(code4) : ok3(code4);
}
}
// node_modules/micromark-extension-math/lib/math-text.js
function mathText(options) {
const options_ = options || {};
let single = options_.singleDollarTextMath;
if (single === null || single === void 0) {
single = true;
}
return {
tokenize: tokenizeMathText,
resolve: resolveMathText,
previous: previous3,
name: "mathText"
};
function tokenizeMathText(effects, ok3, nok) {
const self = this;
let sizeOpen = 0;
let size;
let token;
return start;
function start(code4) {
effects.enter("mathText");
effects.enter("mathTextSequence");
return sequenceOpen(code4);
}
function sequenceOpen(code4) {
if (code4 === 36) {
effects.consume(code4);
sizeOpen++;
return sequenceOpen;
}
if (sizeOpen < 2 && !single) {
return nok(code4);
}
effects.exit("mathTextSequence");
return between(code4);
}
function between(code4) {
if (code4 === null) {
return nok(code4);
}
if (code4 === 36) {
token = effects.enter("mathTextSequence");
size = 0;
return sequenceClose(code4);
}
if (code4 === 32) {
effects.enter("space");
effects.consume(code4);
effects.exit("space");
return between;
}
if (markdownLineEnding(code4)) {
effects.enter("lineEnding");
effects.consume(code4);
effects.exit("lineEnding");
return between;
}
effects.enter("mathTextData");
return data(code4);
}
function data(code4) {
if (code4 === null || code4 === 32 || code4 === 36 || markdownLineEnding(code4)) {
effects.exit("mathTextData");
return between(code4);
}
effects.consume(code4);
return data;
}
function sequenceClose(code4) {
if (code4 === 36) {
effects.consume(code4);
size++;
return sequenceClose;
}
if (size === sizeOpen) {
effects.exit("mathTextSequence");
effects.exit("mathText");
return ok3(code4);
}
token.type = "mathTextData";
return data(code4);
}
}
}
function resolveMathText(events) {
let tailExitIndex = events.length - 4;
let headEnterIndex = 3;
let index2;
let enter;
if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) {
index2 = headEnterIndex;
while (++index2 < tailExitIndex) {
if (events[index2][1].type === "mathTextData") {
events[tailExitIndex][1].type = "mathTextPadding";
events[headEnterIndex][1].type = "mathTextPadding";
headEnterIndex += 2;
tailExitIndex -= 2;
break;
}
}
}
index2 = headEnterIndex - 1;
tailExitIndex++;
while (++index2 <= tailExitIndex) {
if (enter === void 0) {
if (index2 !== tailExitIndex && events[index2][1].type !== "lineEnding") {
enter = index2;
}
} else if (index2 === tailExitIndex || events[index2][1].type === "lineEnding") {
events[enter][1].type = "mathTextData";
if (index2 !== enter + 2) {
events[enter][1].end = events[index2 - 1][1].end;
events.splice(enter + 2, index2 - enter - 2);
tailExitIndex -= index2 - enter - 2;
index2 = enter + 2;
}
enter = void 0;
}
}
return events;
}
function previous3(code4) {
return code4 !== 36 || this.events[this.events.length - 1][1].type === "characterEscape";
}
// node_modules/micromark-extension-math/lib/syntax.js
function math(options) {
return {
flow: {
[36]: mathFlow
},
text: {
[36]: mathText(options)
}
};
}
// node_modules/remark-math/lib/index.js
var emptyOptions3 = {};
function remarkMath(options) {
const self = (
/** @type {Processor} */
this
);
const settings = options || emptyOptions3;
const data = self.data();
const micromarkExtensions = data.micromarkExtensions || (data.micromarkExtensions = []);
const fromMarkdownExtensions = data.fromMarkdownExtensions || (data.fromMarkdownExtensions = []);
const toMarkdownExtensions = data.toMarkdownExtensions || (data.toMarkdownExtensions = []);
micromarkExtensions.push(math(settings));
fromMarkdownExtensions.push(mathFromMarkdown());
toMarkdownExtensions.push(mathToMarkdown(settings));
}
// node_modules/@jxpeng98/martian/build/src/index.js
function markdownToBlocks(body, options) {
const root2 = unified().use(remarkParse).use(remarkGfm).use(remarkMath).parse(body);
return parseBlocks(root2, options);
}
// node_modules/yaml-front-matter/src/index.js
var jsYaml = require_js_yaml2();
function parse2(text5, options, loadSafe) {
let contentKeyName = options && typeof options === "string" ? options : options && options.contentKeyName ? options.contentKeyName : "__content";
let passThroughOptions = options && typeof options === "object" ? options : void 0;
let re = /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?([\w\W]*)*/, results = re.exec(text5), conf = {}, yamlOrJson;
if (yamlOrJson = results[2]) {
if (yamlOrJson.charAt(0) === "{") {
conf = JSON.parse(yamlOrJson);
} else {
if (loadSafe) {
conf = jsYaml.safeLoad(yamlOrJson, passThroughOptions);
} else {
conf = jsYaml.load(yamlOrJson, passThroughOptions);
}
}
}
conf[contentKeyName] = results[3] || "";
return conf;
}
function loadFront(content3, options) {
return parse2(content3, options, false);
}
// src/upload/updateYaml.ts
var import_obsidian3 = require("obsidian");
// src/utils/frontmatter.ts
var DEFAULT_AUTO_SYNC_DATABASE_KEY = "autosync-database";
function resolveAutoSyncKey(rawKey) {
if (typeof rawKey === "string") {
const trimmed = rawKey.trim();
if (trimmed.length > 0) {
return trimmed;
}
}
return DEFAULT_AUTO_SYNC_DATABASE_KEY;
}
function toCandidateList(value) {
if (Array.isArray(value)) {
return value.map((item) => String(item != null ? item : "").trim());
}
if (typeof value === "string") {
if (value.includes(",")) {
return value.split(",").map((item) => item.trim());
}
return [value.trim()];
}
return [];
}
function parseAutoSyncDatabaseList(value) {
const candidates = toCandidateList(value).map((name) => name.replace(/^\[|\]$/g, "").trim()).filter(Boolean);
const seen = /* @__PURE__ */ new Map();
for (const name of candidates) {
const key = name.toLowerCase();
if (!seen.has(key)) {
seen.set(key, name);
}
}
return Array.from(seen.values());
}
function ensureAutoSyncDatabaseEntry(value, abName) {
const current = parseAutoSyncDatabaseList(value);
const lower = abName.toLowerCase();
let contains = false;
const updated = current.map((name) => {
if (name.toLowerCase() === lower) {
contains = true;
return abName;
}
return name;
});
if (!contains) {
updated.push(abName);
}
return updated;
}
// src/upload/updateYaml.ts
function updateYamlInfo(yamlContent, nowFile, res, app, plugin, dbDetails) {
return __async(this, null, function* () {
let { url, id } = res;
const { notionUser, NotionLinkDisplay } = plugin.settings;
const { abName } = dbDetails;
const notionIDKey = `NotionID-${abName}`;
const linkKey = `link-${abName}`;
const autoSyncKey = plugin.getAutoSyncFrontmatterKey();
if (notionUser !== "") {
url = url.replace("www.notion.so", `${notionUser}.notion.site`);
}
yield app.fileManager.processFrontMatter(nowFile, (yamlContent2) => {
if (yamlContent2[notionIDKey]) {
delete yamlContent2[notionIDKey];
}
if (yamlContent2[linkKey]) {
delete yamlContent2[linkKey];
}
yamlContent2[notionIDKey] = id;
NotionLinkDisplay ? yamlContent2[linkKey] = url : null;
yamlContent2[autoSyncKey] = ensureAutoSyncDatabaseEntry(
yamlContent2[autoSyncKey],
abName
);
});
if (plugin.settings.autoCopyNotionLink) {
try {
yield navigator.clipboard.writeText(url);
} catch (error) {
console.log(error);
new import_obsidian3.Notice(`${i18nConfig.CopyErrorMessage}`);
}
}
});
}
// src/upload/common/UploadBase.ts
var import_obsidian4 = require("obsidian");
var NOTION_API_VERSION = "2025-09-03";
var UploadBase = class {
constructor(plugin, dbDetails) {
this.isAutoSync = false;
this.plugin = plugin;
this.dbDetails = dbDetails;
}
shouldShowSuccessNotices() {
if (!this.isAutoSync) {
return true;
}
return !!this.plugin.settings.autoSyncSuccessNotice;
}
deletePage(notionID) {
return __async(this, null, function* () {
const { notionAPI } = this.dbDetails;
return (0, import_obsidian4.requestUrl)({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": NOTION_API_VERSION
},
body: "",
throw: false
}).catch(
(error) => this.handleRequestError(error, `Deleting Notion page ${notionID}`)
);
});
}
prepareBlocks(childArr) {
this.stripCodeAnnotations(childArr);
const childArrLength = childArr.length;
if (childArrLength <= 100) {
this.debugLog("UploadBase", "Blocks fit into a single request", {
totalBlocks: childArrLength
});
return {
firstChunk: childArr,
extraChunks: []
};
}
const extraChunks = [];
for (let i = 100; i < childArr.length; i += 100) {
extraChunks.push(childArr.slice(i, i + 100));
}
this.debugLog("UploadBase", "Blocks split into multiple chunks", {
totalBlocks: childArrLength,
firstChunkSize: 100,
extraChunkCount: extraChunks.length,
lastChunkSize: extraChunks[extraChunks.length - 1].length
});
return {
firstChunk: childArr.slice(0, 100),
extraChunks
};
}
applyCover(body, cover) {
var _a, _b, _c;
if (cover) {
body.cover = {
type: "external",
external: {
url: cover
}
};
} else if (!body.cover && this.plugin.settings.bannerUrl) {
body.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl
}
};
}
this.debugLog("UploadBase", "Cover applied to payload", {
chosenCover: (_c = (_b = (_a = body.cover) == null ? void 0 : _a.external) == null ? void 0 : _b.url) != null ? _c : null,
defaultBannerUsed: !cover && !!this.plugin.settings.bannerUrl
});
}
resolveCoverForUpdate(cover) {
return __async(this, null, function* () {
if (cover) {
this.debugLog("UploadBase", "Existing cover retained for update", {
cover
});
return cover;
}
const databaseCover = yield this.fetchDatabaseCover();
return databaseCover != null ? databaseCover : void 0;
});
}
submitPage(body, extraChunks) {
return __async(this, null, function* () {
var _a, _b;
const { notionAPI } = this.dbDetails;
const startedAt = Date.now();
const response = yield (0, import_obsidian4.requestUrl)({
url: `https://api.notion.com/v1/pages`,
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": NOTION_API_VERSION
},
body: JSON.stringify(body),
throw: false
}).catch(
(error) => this.handleRequestError(error, "Creating Notion page")
);
const data = yield response.json;
this.debugLog("UploadBase", "Page creation response received", {
status: response.status,
durationMs: Date.now() - startedAt,
notionUrl: (_a = data == null ? void 0 : data.url) != null ? _a : null,
pageId: (_b = data == null ? void 0 : data.id) != null ? _b : null
});
if (response.status !== 200) {
new import_obsidian4.Notice(`Error ${data.status}: ${data.code}
${i18nConfig["CheckConsole"]}`, 5e3);
console.log(`Error message:
${data.message}`);
} else {
if (extraChunks.length > 0) {
yield this.appendExtraBlocks(data.id, extraChunks);
}
}
return { response, data };
});
}
stripCodeAnnotations(childArr) {
childArr.forEach((block) => {
if (block.type === "code") {
block.code.rich_text.forEach((item) => {
if (item.type === "text" && item.annotations) {
delete item.annotations;
}
});
}
});
}
appendExtraBlocks(pageId, extraChunks) {
return __async(this, null, function* () {
const { notionAPI } = this.dbDetails;
for (let i = 0; i < extraChunks.length; i++) {
const chunk = extraChunks[i];
const extraBlocks = {
children: chunk
};
const extraResponse = yield (0, import_obsidian4.requestUrl)({
url: `https://api.notion.com/v1/blocks/${pageId}/children`,
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": NOTION_API_VERSION
},
body: JSON.stringify(extraBlocks),
throw: false
}).catch(
(error) => this.handleRequestError(error, `Appending blocks to page ${pageId}`)
);
const extraData = yield extraResponse.json;
if (extraResponse.status !== 200) {
new import_obsidian4.Notice(`Error ${extraData.status}: ${extraData.code}
${i18nConfig["CheckConsole"]}`, 5e3);
console.log(`Error message:
${extraData.message}`);
} else {
console.log(`${i18nConfig["ExtraBlockUploaded"]} to page: ${pageId}`);
if (i === extraChunks.length - 1) {
console.log(`${i18nConfig["BlockUploaded"]} to page: ${pageId}`);
if (this.shouldShowSuccessNotices()) {
new import_obsidian4.Notice(`${i18nConfig["BlockUploaded"]} page: ${pageId}`, 5e3);
}
}
}
}
});
}
fetchDatabaseCover() {
return __async(this, null, function* () {
const { notionAPI, databaseID } = this.dbDetails;
const response = yield (0, import_obsidian4.requestUrl)({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: "GET",
headers: {
Authorization: "Bearer " + notionAPI,
"Notion-Version": NOTION_API_VERSION
},
throw: false
}).catch(
(error) => this.handleRequestError(error, `Fetching database ${databaseID}`)
);
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
}
return null;
});
}
debugLog(context, message, payload) {
if (payload) {
console.log(`[${context}] ${message}`, payload);
} else {
console.log(`[${context}] ${message}`);
}
}
maskValue(value, visibleChars = 4) {
if (!value) {
return value;
}
if (value.length <= visibleChars * 2) {
return `${value.slice(0, visibleChars)}***`;
}
return `${value.slice(0, visibleChars)}***${value.slice(-visibleChars)}`;
}
handleRequestError(error, context) {
const message = error instanceof Error && error.message ? error.message : String(error);
console.error(`[UploadBase] ${context} failed`, {
message,
error
});
throw new Error(
`${context} failed: ${message}. Please check your network connection or proxy settings.`
);
}
};
// src/upload/common/AttachmentProcessor.ts
var import_obsidian6 = require("obsidian");
// src/upload/common/AttachmentUploader.ts
var import_obsidian5 = require("obsidian");
var NOTION_API_VERSION2 = "2025-09-03";
var MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
var AttachmentUploader = class {
constructor(plugin, dbDetails) {
this.textEncoder = new TextEncoder();
this.plugin = plugin;
this.dbDetails = dbDetails;
}
uploadFile(file) {
return __async(this, null, function* () {
var _a, _b, _c;
const { notionAPI } = this.dbDetails;
const fileSizeBytes = (_b = (_a = file.stat) == null ? void 0 : _a.size) != null ? _b : 0;
const contentType = this.getContentType(file.extension);
if (fileSizeBytes > MAX_UPLOAD_BYTES) {
throw new Error(
`File too large for Notion upload (max 5MB): ${file.path} (${(fileSizeBytes / 1024 / 1024).toFixed(2)} MB)`
);
}
const mode = "single_part";
console.log(`[AttachmentUploader] uploadFile: ${file.name}`, {
path: file.path,
size: `${(fileSizeBytes / 1024).toFixed(2)} KB`,
contentType,
mode
});
const session = yield this.createUploadSession({
mode,
notionAPI
});
console.log(`[AttachmentUploader] Upload session created:`, {
sessionId: session.id,
status: session.status
});
const binary = yield this.plugin.app.vault.readBinary(file);
console.log(`[AttachmentUploader] Read binary data: ${binary.byteLength} bytes`);
if (binary.byteLength > MAX_UPLOAD_BYTES) {
throw new Error(
`File too large for Notion upload (max 5MB): ${file.path} (${(binary.byteLength / 1024 / 1024).toFixed(2)} MB)`
);
}
const uploadUrl = (_c = session.upload_url) != null ? _c : `https://api.notion.com/v1/file_uploads/${encodeURIComponent(session.id)}/send`;
yield this.sendFileData(session.id, uploadUrl, binary, notionAPI, file.name, contentType);
console.log(`[AttachmentUploader] Upload complete: ${file.name} -> ${session.id}`);
return { id: session.id, filename: file.name };
});
}
createUploadSession(params) {
return __async(this, null, function* () {
var _a, _b, _c;
console.log(`[AttachmentUploader] Creating upload session:`, {
mode: params.mode
});
const response = yield this.requestWithRetry({
url: "https://api.notion.com/v1/file_uploads",
method: "POST",
headers: {
accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${params.notionAPI}`,
"Notion-Version": NOTION_API_VERSION2
},
body: JSON.stringify({
mode: params.mode
}),
throw: false
});
const data = response.json;
if (response.status < 200 || response.status >= 300) {
console.error(`[AttachmentUploader] Failed to create upload session:`, {
status: response.status,
message: data == null ? void 0 : data.message,
response: data
});
throw new Error(`Failed to create upload session: ${(_a = data == null ? void 0 : data.message) != null ? _a : response.status}`);
}
const id = (_c = data == null ? void 0 : data.id) != null ? _c : (_b = data == null ? void 0 : data.file_upload) == null ? void 0 : _b.id;
if (!id) {
throw new Error("Upload session response missing id");
}
return { id, status: data.status, upload_url: data.upload_url };
});
}
sendFileData(fileUploadId, uploadUrl, binary, notionAPI, filename, contentType) {
return __async(this, null, function* () {
var _a;
console.log(`[AttachmentUploader] Sending file data for session: ${fileUploadId} (${binary.byteLength} bytes)`);
const { body, boundary } = this.buildMultipartBody({
fieldName: "file",
filename,
contentType: contentType || "application/octet-stream",
binary
});
const response = yield this.requestWithRetry({
url: uploadUrl,
method: "POST",
headers: {
accept: "application/json",
"Content-Type": `multipart/form-data; boundary=${boundary}`,
Authorization: `Bearer ${notionAPI}`,
"Notion-Version": NOTION_API_VERSION2
},
body,
throw: false
});
const data = response.json;
if (response.status < 200 || response.status >= 300) {
console.error(`[AttachmentUploader] Failed to send file data:`, {
sessionId: fileUploadId,
status: response.status,
message: data == null ? void 0 : data.message,
response: data
});
throw new Error(`Failed to send file data: ${(_a = data == null ? void 0 : data.message) != null ? _a : response.status}`);
}
console.log(`[AttachmentUploader] File data sent successfully for session: ${fileUploadId}`);
});
}
buildMultipartBody(params) {
const boundary = `----NotionFormBoundary${Math.random().toString(16).slice(2)}${Math.random().toString(16).slice(2)}`;
const safeFilename = params.filename.replace(/"/g, '\\"');
const prefix = [
`--${boundary}\r
`,
`Content-Disposition: form-data; name="${params.fieldName}"; filename="${safeFilename}"\r
`,
`Content-Type: ${params.contentType}\r
`,
`\r
`
].join("");
const suffix = `\r
--${boundary}--\r
`;
const prefixBytes = this.textEncoder.encode(prefix);
const fileBytes = new Uint8Array(params.binary);
const suffixBytes = this.textEncoder.encode(suffix);
const out = new Uint8Array(prefixBytes.length + fileBytes.length + suffixBytes.length);
out.set(prefixBytes, 0);
out.set(fileBytes, prefixBytes.length);
out.set(suffixBytes, prefixBytes.length + fileBytes.length);
return { body: out.buffer, boundary };
}
requestWithRetry(params, maxAttempts = 4) {
return __async(this, null, function* () {
let attempt = 0;
let lastError;
while (attempt < maxAttempts) {
attempt++;
try {
const response = yield (0, import_obsidian5.requestUrl)(params);
if (this.shouldRetry(response.status) && attempt < maxAttempts) {
const delayMs = this.getRetryDelay(response, attempt);
console.warn(`[AttachmentUploader] Retryable status ${response.status}, attempt ${attempt}/${maxAttempts}, retrying in ${delayMs}ms`);
yield this.sleep(delayMs);
continue;
}
return response;
} catch (error) {
lastError = error;
console.error(`[AttachmentUploader] Request failed, attempt ${attempt}/${maxAttempts}:`, error);
if (attempt >= maxAttempts)
break;
const delayMs = this.getRetryDelay(void 0, attempt);
console.warn(`[AttachmentUploader] Retrying in ${delayMs}ms`);
yield this.sleep(delayMs);
}
}
console.error(`[AttachmentUploader] Request failed after ${maxAttempts} attempts`);
throw lastError != null ? lastError : new Error("Request failed after retries");
});
}
shouldRetry(status) {
return status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
}
getRetryDelay(response, attempt) {
var _a, _b, _c;
const retryAfter = (_c = (_a = response == null ? void 0 : response.headers) == null ? void 0 : _a["retry-after"]) != null ? _c : (_b = response == null ? void 0 : response.headers) == null ? void 0 : _b["Retry-After"];
if (retryAfter) {
const seconds = parseInt(retryAfter, 10);
if (!isNaN(seconds))
return seconds * 1e3;
}
const base = 500;
const max = 8e3;
const expo = Math.min(max, base * Math.pow(2, attempt - 1));
const jitter = Math.floor(Math.random() * 250);
return expo + jitter;
}
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
getContentType(extension2) {
var _a;
const ext = extension2.toLowerCase();
const mimeTypes = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
svg: "image/svg+xml",
heic: "image/heic",
tif: "image/tiff",
tiff: "image/tiff",
bmp: "image/bmp",
pdf: "application/pdf"
};
return (_a = mimeTypes[ext]) != null ? _a : "application/octet-stream";
}
};
// src/upload/common/AttachmentProcessor.ts
var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
"png",
"jpg",
"jpeg",
"gif",
"webp",
"svg",
"heic",
"tif",
"tiff",
"bmp"
]);
var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
...IMAGE_EXTENSIONS,
"pdf"
]);
var AttachmentProcessor = class {
constructor(plugin, dbDetails) {
this.plugin = plugin;
this.dbDetails = dbDetails;
this.uploader = new AttachmentUploader(plugin, dbDetails);
}
isStandaloneOnLine(input, offset, match) {
const lineStart = input.lastIndexOf("\n", Math.max(0, offset - 1)) + 1;
const lineEndIdx = input.indexOf("\n", offset + match.length);
const lineEnd = lineEndIdx === -1 ? input.length : lineEndIdx;
const before = input.slice(lineStart, offset).trim();
const after = input.slice(offset + match.length, lineEnd).trim();
return before.length === 0 && after.length === 0;
}
hasInternalAttachments(content3, sourceFile) {
const app = this.plugin.app;
const contentWithoutCode = content3.replace(/```[\s\S]*?```|`[^`\n]+`/g, "");
const embedImageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g;
const embedWikilinkRegex = /!\[\[([^\]]+)\]\]/g;
const linkMarkdownRegex = new RegExp("(? {
const placeholder = `__CODE_BLOCK_${codeBlockPlaceholders.length}__`;
codeBlockPlaceholders.push(match);
return placeholder;
});
console.log(`[AttachmentProcessor] Stripped ${codeBlockPlaceholders.length} code blocks`);
const { internal, external } = this.collectAttachments(contentWithoutCode, sourceFile);
if (external.length > 0) {
console.log(`[AttachmentProcessor] Found ${external.length} external reference(s) (will be skipped):`);
external.forEach((ref, idx) => {
console.log(` ${idx + 1}. [EXTERNAL] ${ref}`);
});
}
if (internal.length === 0) {
console.log(`[AttachmentProcessor] No internal attachments found in ${sourceFile.path}`);
return {
content: content3,
imageUrlToUploadId: {},
filePlaceholderToUpload: {}
};
}
console.log(`[AttachmentProcessor] Found ${internal.length} internal attachment(s) to upload:`);
internal.forEach((attachment, idx) => {
const typeLabel = this.isImage(attachment.file) ? "IMAGE" : "FILE";
const sizeKB = (attachment.file.stat.size / 1024).toFixed(2);
console.log(` ${idx + 1}. [${typeLabel}] ${attachment.file.path} (${sizeKB} KB) - Ref: "${attachment.originalRef}"`);
});
const uploadedMap = /* @__PURE__ */ new Map();
for (const attachment of internal) {
try {
console.log(`[AttachmentProcessor] Uploading: ${attachment.file.path} (${(attachment.file.stat.size / 1024).toFixed(2)} KB)`);
const result = yield this.uploader.uploadFile(attachment.file);
uploadedMap.set(attachment.file.path, { id: result.id, file: attachment.file });
console.log(`[AttachmentProcessor] \u2713 Uploaded successfully: ${attachment.file.name} -> ${result.id}`);
} catch (error) {
console.error(`[AttachmentProcessor] \u2717 Failed to upload ${attachment.file.path}:`, error);
}
}
console.log(`[AttachmentProcessor] Upload complete: ${uploadedMap.size}/${internal.length} successful`);
const rewriteResult = this.rewriteContent(contentWithoutCode, sourceFile, uploadedMap);
let restoredContent = rewriteResult.content;
codeBlockPlaceholders.forEach((code4, idx) => {
restoredContent = restoredContent.replace(`__CODE_BLOCK_${idx}__`, code4);
});
console.log(`[AttachmentProcessor] Content rewrite complete:`, {
imageReplacements: Object.keys(rewriteResult.imageUrlToUploadId).length,
fileReplacements: Object.keys(rewriteResult.filePlaceholderToUpload).length
});
return {
content: restoredContent,
imageUrlToUploadId: rewriteResult.imageUrlToUploadId,
filePlaceholderToUpload: rewriteResult.filePlaceholderToUpload
};
});
}
collectAttachments(content3, sourceFile) {
const internal = [];
const external = [];
const seen = /* @__PURE__ */ new Set();
const app = this.plugin.app;
console.log(`[AttachmentProcessor] Scanning for attachments in content (${content3.length} chars)`);
const embedImageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g;
const embedWikilinkRegex = /!\[\[([^\]]+)\]\]/g;
const linkMarkdownRegex = new RegExp("(? parsed path: "${rawPath}"`);
if (this.shouldSkipLinkDestination(rawPath)) {
if (this.isTodoUrl(rawPath)) {
console.log(`[AttachmentProcessor] \u2298 Unsupported URL scheme (TODO, skipped): ${rawPath}`);
} else {
console.log(`[AttachmentProcessor] \u2298 External URL (skipped): ${rawPath}`);
}
external.push(match[0]);
continue;
}
const file = this.resolveFile(app, sourceFile, rawPath);
if (!file) {
console.log(`[AttachmentProcessor] \u2717 Could not resolve file for path: "${rawPath}"`);
} else if (!this.isSupported(file)) {
console.log(`[AttachmentProcessor] \u2717 Unsupported file type: ${file.extension} (${file.path})`);
} else if (seen.has(file.path)) {
console.log(`[AttachmentProcessor] \u229A Duplicate (already added): ${file.path}`);
} else {
seen.add(file.path);
internal.push({ file, originalRef: match[0] });
console.log(`[AttachmentProcessor] \u2713 Added: ${file.path}`);
}
}
let wikiEmbedCount = 0;
while ((match = embedWikilinkRegex.exec(content3)) !== null) {
wikiEmbedCount++;
const linkPath = this.parseWikilink(match[1]);
console.log(`[AttachmentProcessor] Found embedded wikilink #${wikiEmbedCount}: "${match[0]}" -> parsed path: "${linkPath}"`);
if (this.shouldSkipLinkDestination(linkPath)) {
if (this.isTodoUrl(linkPath)) {
console.log(`[AttachmentProcessor] \u2298 Unsupported URL scheme (TODO, skipped): ${linkPath}`);
} else {
console.log(`[AttachmentProcessor] \u2298 External URL (skipped): ${linkPath}`);
}
external.push(match[0]);
continue;
}
const file = this.resolveFile(app, sourceFile, linkPath);
if (!file) {
console.log(`[AttachmentProcessor] \u2717 Could not resolve file for path: "${linkPath}"`);
} else if (!this.isSupported(file)) {
console.log(`[AttachmentProcessor] \u2717 Unsupported file type: ${file.extension} (${file.path})`);
} else if (seen.has(file.path)) {
console.log(`[AttachmentProcessor] \u229A Duplicate (already added): ${file.path}`);
} else {
seen.add(file.path);
internal.push({ file, originalRef: match[0] });
console.log(`[AttachmentProcessor] \u2713 Added: ${file.path}`);
}
}
let linkCount = 0;
while ((match = linkMarkdownRegex.exec(content3)) !== null) {
linkCount++;
const rawPath = this.parseDestination(match[2]);
console.log(`[AttachmentProcessor] Found markdown link #${linkCount}: "${match[0]}" -> parsed path: "${rawPath}"`);
if (this.shouldSkipLinkDestination(rawPath)) {
if (this.isTodoUrl(rawPath)) {
console.log(`[AttachmentProcessor] \u2298 Unsupported URL scheme (TODO, skipped): ${rawPath}`);
} else {
console.log(`[AttachmentProcessor] \u2298 External URL (skipped): ${rawPath}`);
}
external.push(match[0]);
continue;
}
const file = this.resolveFile(app, sourceFile, rawPath);
if (!file) {
console.log(`[AttachmentProcessor] \u2717 Could not resolve file for path: "${rawPath}"`);
} else if (!this.isSupported(file)) {
console.log(`[AttachmentProcessor] \u2717 Unsupported file type: ${file.extension} (${file.path})`);
} else if (seen.has(file.path)) {
console.log(`[AttachmentProcessor] \u229A Duplicate (already added): ${file.path}`);
} else {
seen.add(file.path);
internal.push({ file, originalRef: match[0] });
console.log(`[AttachmentProcessor] \u2713 Added: ${file.path}`);
}
}
let wikilinkCount = 0;
while ((match = linkWikilinkRegex.exec(content3)) !== null) {
wikilinkCount++;
const linkPath = this.parseWikilink(match[1]);
console.log(`[AttachmentProcessor] Found wikilink reference #${wikilinkCount}: "${match[0]}" -> parsed path: "${linkPath}"`);
if (this.shouldSkipLinkDestination(linkPath)) {
if (this.isTodoUrl(linkPath)) {
console.log(`[AttachmentProcessor] \u2298 Unsupported URL scheme (TODO, skipped): ${linkPath}`);
} else {
console.log(`[AttachmentProcessor] \u2298 External URL (skipped): ${linkPath}`);
}
external.push(match[0]);
continue;
}
const file = this.resolveFile(app, sourceFile, linkPath);
if (!file) {
console.log(`[AttachmentProcessor] \u2717 Could not resolve file for path: "${linkPath}"`);
} else if (!this.isSupported(file)) {
console.log(`[AttachmentProcessor] \u2717 Unsupported file type: ${file.extension} (${file.path})`);
} else if (seen.has(file.path)) {
console.log(`[AttachmentProcessor] \u229A Duplicate (already added): ${file.path}`);
} else {
seen.add(file.path);
internal.push({ file, originalRef: match[0] });
console.log(`[AttachmentProcessor] \u2713 Added: ${file.path}`);
}
}
console.log(`[AttachmentProcessor] Scan complete: ${embedCount} embeds, ${wikiEmbedCount} wiki-embeds, ${linkCount} links, ${wikilinkCount} wikilinks -> ${internal.length} internal attachments, ${external.length} external references`);
return { internal, external };
}
rewriteContent(content3, sourceFile, uploadedMap) {
const imageUrlToUploadId = {};
const filePlaceholderToUpload = {};
const app = this.plugin.app;
let rewritten = content3;
rewritten = rewritten.replace(
/!\[([^\]]*)\]\(([^)]+)\)/g,
(fullMatch, altText, rawDest, offset, input) => {
const path3 = this.parseDestination(rawDest);
if (this.shouldSkipLinkDestination(path3))
return fullMatch;
const file = this.resolveFile(app, sourceFile, path3);
if (!file)
return fullMatch;
const uploaded = uploadedMap.get(file.path);
if (!uploaded)
return fullMatch;
if (this.isImage(file)) {
const sentinelUrl = this.buildSentinelUrl(uploaded.id, file, altText);
imageUrlToUploadId[sentinelUrl] = uploaded.id;
const markdown = ``;
return typeof offset === "number" && typeof input === "string" && this.isStandaloneOnLine(input, offset, fullMatch) ? `
${markdown}
` : markdown;
} else {
const token = `__NOTION_FILE_UPLOAD__:${uploaded.id}`;
filePlaceholderToUpload[token] = { id: uploaded.id, name: file.name };
return `
\`${token}\`
`;
}
}
);
rewritten = rewritten.replace(
/!\[\[([^\]]+)\]\]/g,
(fullMatch, inner, offset, input) => {
const linkPath = this.parseWikilink(inner);
if (this.shouldSkipLinkDestination(linkPath))
return fullMatch;
const file = this.resolveFile(app, sourceFile, linkPath);
if (!file)
return fullMatch;
const uploaded = uploadedMap.get(file.path);
if (!uploaded)
return fullMatch;
if (this.isImage(file)) {
const sentinelUrl = this.buildSentinelUrl(uploaded.id, file);
imageUrlToUploadId[sentinelUrl] = uploaded.id;
const markdown = ``;
return typeof offset === "number" && typeof input === "string" && this.isStandaloneOnLine(input, offset, fullMatch) ? `
${markdown}
` : markdown;
} else {
const token = `__NOTION_FILE_UPLOAD__:${uploaded.id}`;
filePlaceholderToUpload[token] = { id: uploaded.id, name: file.name };
return `
\`${token}\`
`;
}
}
);
rewritten = rewritten.replace(
new RegExp("(? {
const path3 = this.parseDestination(rawDest);
if (this.shouldSkipLinkDestination(path3))
return fullMatch;
const file = this.resolveFile(app, sourceFile, path3);
if (!file)
return fullMatch;
const uploaded = uploadedMap.get(file.path);
if (!uploaded)
return fullMatch;
const token = `__NOTION_FILE_UPLOAD__:${uploaded.id}`;
filePlaceholderToUpload[token] = { id: uploaded.id, name: file.name };
return `
\`${token}\`
`;
}
);
rewritten = rewritten.replace(
new RegExp("(? {
const linkPath = this.parseWikilink(inner);
if (this.shouldSkipLinkDestination(linkPath))
return fullMatch;
const file = this.resolveFile(app, sourceFile, linkPath);
if (!file)
return fullMatch;
const uploaded = uploadedMap.get(file.path);
if (!uploaded)
return fullMatch;
const token = `__NOTION_FILE_UPLOAD__:${uploaded.id}`;
filePlaceholderToUpload[token] = { id: uploaded.id, name: file.name };
return `
\`${token}\`
`;
}
);
return { content: rewritten, imageUrlToUploadId, filePlaceholderToUpload };
}
parseDestination(rawDest) {
const trimmed = rawDest.trim();
if (trimmed.startsWith("<") && trimmed.includes(">")) {
const end = trimmed.indexOf(">");
return this.decodePathOrUrl(trimmed.slice(1, end));
}
const match = trimmed.match(/^(\S+)/);
return this.decodePathOrUrl(match ? match[1] : trimmed);
}
parseWikilink(inner) {
var _a, _b, _c, _d;
const trimmed = inner.trim();
const beforeAlias = (_b = (_a = trimmed.split("|")[0]) == null ? void 0 : _a.trim()) != null ? _b : trimmed;
const beforeHeading = (_d = (_c = beforeAlias.split("#")[0]) == null ? void 0 : _c.trim()) != null ? _d : beforeAlias;
return this.decodePathOrUrl(beforeHeading);
}
decodePathOrUrl(value) {
var _a;
const stripped = (_a = value.split(/[?#]/)[0]) != null ? _a : value;
try {
return decodeURIComponent(stripped);
} catch (e) {
return stripped;
}
}
isExternalUrl(link2) {
return link2.startsWith("http://") || link2.startsWith("https://");
}
isTodoUrl(link2) {
return link2.startsWith("obsidian://") || link2.startsWith("app://");
}
shouldSkipLinkDestination(link2) {
return this.isExternalUrl(link2) || this.isTodoUrl(link2);
}
resolveFile(app, sourceFile, link2, options) {
const shouldLog = (options == null ? void 0 : options.log) !== false;
const log = (...args) => {
if (shouldLog)
console.log(...args);
};
if (!link2.trim()) {
log(`[AttachmentProcessor] resolveFile: empty link`);
return null;
}
if (this.isTodoUrl(link2)) {
return null;
}
const cached = app.metadataCache.getFirstLinkpathDest(link2, sourceFile.path);
if (cached instanceof import_obsidian6.TFile) {
log(`[AttachmentProcessor] resolveFile: \u2713 Resolved via metadata cache: ${link2} -> ${cached.path}`);
return cached;
}
const byPath = app.vault.getAbstractFileByPath((0, import_obsidian6.normalizePath)(link2));
if (byPath instanceof import_obsidian6.TFile) {
log(`[AttachmentProcessor] resolveFile: \u2713 Resolved via absolute path: ${link2} -> ${byPath.path}`);
return byPath;
}
const sourceDir = sourceFile.path.includes("/") ? sourceFile.path.slice(0, sourceFile.path.lastIndexOf("/")) : "";
const relPath = (0, import_obsidian6.normalizePath)(sourceDir ? `${sourceDir}/${link2}` : link2);
const byRel = app.vault.getAbstractFileByPath(relPath);
if (byRel instanceof import_obsidian6.TFile) {
log(`[AttachmentProcessor] resolveFile: \u2713 Resolved via relative path: ${link2} -> ${byRel.path}`);
return byRel;
}
log(`[AttachmentProcessor] resolveFile: \u2717 Failed to resolve: ${link2} (tried cache, absolute, relative)`);
return null;
}
/*
// TODO: Support `obsidian://` URL destinations.
private parseObsidianUrl(url: string): string | null {
try {
const urlObj = new URL(url);
// obsidian://open?vault=VaultName&file=path/to/file.png
const filePath = urlObj.searchParams.get("file");
if (filePath) {
return decodeURIComponent(filePath);
}
return null;
} catch {
return null;
}
}
// TODO: Support `app://` URL destinations.
private parseAppUrl(url: string): string | null {
try {
const urlObj = new URL(url);
const pathname = urlObj.pathname;
if (!pathname || pathname === "/") return null;
return decodeURIComponent(pathname);
} catch {
return null;
}
}
// TODO: Support mapping absolute paths to vault paths for `app://local/...`.
private mapAbsolutePathToVault(app: App, absolutePath: string): string | null {
const adapter: any = app.vault.adapter;
if (typeof adapter?.getBasePath !== "function") {
return null;
}
let normalizedAbsolute = absolutePath.replace(/\\/g, "/");
if (/^\/[A-Za-z]:\//.test(normalizedAbsolute)) {
normalizedAbsolute = normalizedAbsolute.slice(1);
}
let basePath = String(adapter.getBasePath()).replace(/\\/g, "/");
if (basePath.endsWith("/")) {
basePath = basePath.slice(0, -1);
}
if (/^\/[A-Za-z]:\//.test(basePath)) {
basePath = basePath.slice(1);
}
const windowsStyle = /^[A-Za-z]:\//.test(basePath);
const compareAbsolute = windowsStyle ? normalizedAbsolute.toLowerCase() : normalizedAbsolute;
const compareBase = windowsStyle ? basePath.toLowerCase() : basePath;
if (!compareAbsolute.startsWith(compareBase)) {
return null;
}
let relative = normalizedAbsolute.slice(basePath.length);
if (relative.startsWith("/")) {
relative = relative.slice(1);
}
return relative || null;
}
*/
isSupported(file) {
var _a, _b;
const ext = (_b = (_a = file.extension) == null ? void 0 : _a.toLowerCase()) != null ? _b : "";
return SUPPORTED_EXTENSIONS.has(ext);
}
isImage(file) {
var _a, _b;
const ext = (_b = (_a = file.extension) == null ? void 0 : _a.toLowerCase()) != null ? _b : "";
return IMAGE_EXTENSIONS.has(ext);
}
buildSentinelUrl(uploadId, file, _altText) {
var _a, _b;
const ext = (_b = (_a = file.extension) == null ? void 0 : _a.toLowerCase()) != null ? _b : "";
const suffix = ext ? `.${ext}` : "";
return `https://notion-file-upload.local/${uploadId}${suffix}`;
}
};
function applyBlockRewrites(blocks, rewrites) {
transformBlocksInPlace(blocks, rewrites);
}
function transformBlocksInPlace(blocks, rewrites) {
var _a, _b, _c, _d;
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
if ((block == null ? void 0 : block.type) === "image" && ((_a = block == null ? void 0 : block.image) == null ? void 0 : _a.type) === "external") {
const url = (_c = (_b = block.image) == null ? void 0 : _b.external) == null ? void 0 : _c.url;
if (url && rewrites.imageUrlToUploadId[url]) {
const caption = (_d = block.image) == null ? void 0 : _d.caption;
block.image = __spreadValues({
type: "file_upload",
file_upload: { id: rewrites.imageUrlToUploadId[url] }
}, caption ? { caption } : {});
}
}
if ((block == null ? void 0 : block.type) === "paragraph") {
const token = extractParagraphText(block);
if (token && rewrites.filePlaceholderToUpload[token]) {
const { id, name } = rewrites.filePlaceholderToUpload[token];
blocks[i] = buildFileBlock(id, name);
}
}
const inner = block == null ? void 0 : block[block == null ? void 0 : block.type];
if ((inner == null ? void 0 : inner.children) && Array.isArray(inner.children)) {
transformBlocksInPlace(inner.children, rewrites);
}
}
}
function extractParagraphText(block) {
var _a;
const richText2 = (_a = block == null ? void 0 : block.paragraph) == null ? void 0 : _a.rich_text;
if (!Array.isArray(richText2) || richText2.length === 0)
return void 0;
return richText2.map((item) => {
var _a2, _b, _c;
return (_c = (_b = item == null ? void 0 : item.plain_text) != null ? _b : (_a2 = item == null ? void 0 : item.text) == null ? void 0 : _a2.content) != null ? _c : "";
}).join("").trim() || void 0;
}
function buildFileBlock(uploadId, name) {
return {
object: "block",
type: "file",
file: {
type: "file_upload",
file_upload: { id: uploadId }
}
};
}
// src/upload/Upload2Notion.ts
var Upload2Notion = class extends UploadBase {
constructor(plugin, dbDetails) {
super(plugin, dbDetails);
}
sync(request) {
return __async(this, null, function* () {
const startedAt = Date.now();
this.isAutoSync = !!request.isAutoSync;
let response;
switch (request.dataset) {
case "general":
response = yield this.handleGeneral(request);
break;
case "next":
response = yield this.handleNext(request);
break;
case "custom":
response = yield this.handleCustom(request);
break;
default:
throw new Error(`Unsupported dataset type: ${request.dataset}`);
}
if (response.response && response.response.status === 200) {
yield updateYamlInfo(
request.markdown,
request.nowFile,
response.data,
request.app,
this.plugin,
this.dbDetails
);
} else {
console.log(`[Upload2Notion] Sync failed`, response.data);
}
return response;
});
}
handleGeneral(request) {
return __async(this, null, function* () {
var _a, _b;
console.log(`[Upload2Notion] Handling general dataset`, {
cover: request.cover,
tags: request.tags
});
const blocks = yield this.buildBlocks(request.markdown, request.nowFile, {
notionLimits: { truncate: false }
});
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "General dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId != null ? notionId : null,
tagCount: (_b = (_a = request.tags) == null ? void 0 : _a.length) != null ? _b : 0
});
return this.upsertGeneral({
title: request.title,
cover: request.cover,
tags: request.tags || [],
childArr: blocks,
notionId
});
});
}
handleNext(request) {
return __async(this, null, function* () {
console.log(`[Upload2Notion] Handling next dataset`, {
type: request.type,
slug: request.slug,
category: request.category
});
const blocks = yield this.buildBlocks(request.markdown, request.nowFile, {
notionLimits: { truncate: false }
});
this.splitRichTextParagraphs(blocks);
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "Next dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId != null ? notionId : null,
hasEmoji: !!request.emoji,
tags: request.tags || []
});
return this.upsertNext({
title: request.title,
emoji: request.emoji,
cover: request.cover,
tags: request.tags || [],
type: request.type,
slug: request.slug,
stats: request.stats,
category: request.category,
summary: request.summary,
password: request.password,
favicon: request.favicon,
datetime: request.datetime,
childArr: blocks,
notionId
});
});
}
handleCustom(request) {
return __async(this, null, function* () {
console.log(`[Upload2Notion] Handling custom dataset`, {
customKeys: Object.keys(request.customValues || {})
});
const blocks = yield this.buildBlocks(request.markdown, request.nowFile, {
strictImageUrls: true,
notionLimits: { truncate: false }
});
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "Custom dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId != null ? notionId : null,
customValueKeys: Object.keys(request.customValues || {})
});
return this.upsertCustom({
cover: request.cover,
customValues: request.customValues,
childArr: blocks,
notionId
});
});
}
buildBlocks(markdown, nowFile, options) {
return __async(this, null, function* () {
var _a;
const yamlContent = loadFront(markdown);
let content3 = (_a = yamlContent.__content) != null ? _a : "";
const processor = new AttachmentProcessor(this.plugin, this.dbDetails);
const result = yield processor.processContent(content3, nowFile);
content3 = result.content;
const imageUrlToUploadId = result.imageUrlToUploadId;
const filePlaceholderToUpload = result.filePlaceholderToUpload;
const blocks = markdownToBlocks(content3, options);
if (Object.keys(imageUrlToUploadId).length > 0 || Object.keys(filePlaceholderToUpload).length > 0) {
applyBlockRewrites(blocks, { imageUrlToUploadId, filePlaceholderToUpload });
}
this.debugLog("Upload2Notion", "Converted markdown to blocks", {
blockCount: blocks.length,
firstBlockTypes: blocks.slice(0, 5).map((block) => block == null ? void 0 : block.type),
options
});
return blocks;
});
}
getNotionId(app, nowFile) {
var _a;
const frontMatter = (_a = app.metadataCache.getFileCache(nowFile)) == null ? void 0 : _a.frontmatter;
if (!frontMatter) {
this.debugLog("Upload2Notion", "No frontmatter found when resolving Notion ID", {
filePath: nowFile.path
});
return void 0;
}
const { abName } = this.dbDetails;
const notionIDKey = `NotionID-${abName}`;
const notionId = frontMatter[notionIDKey];
return notionId ? String(notionId) : void 0;
}
splitRichTextParagraphs(blocks) {
blocks.forEach((block, index2) => {
if (block.type === "paragraph" && block.paragraph.rich_text.length > LIMITS.RICH_TEXT_ARRAYS) {
console.log(`[Upload2Notion] Splitting rich text paragraph`, {
index: index2,
length: block.paragraph.rich_text.length
});
const paragraphChunks = this.chunkArray(block.paragraph.rich_text, 100);
const newParagraphBlocks = paragraphChunks.map((chunk) => paragraph(chunk));
blocks.splice(index2, 1, ...newParagraphBlocks);
}
});
}
chunkArray(items, size) {
const result = [];
for (let i = 0; i < items.length; i += size) {
result.push(items.slice(i, i + size));
}
return result;
}
upsertGeneral(params) {
return __async(this, null, function* () {
var _a;
const { firstChunk, extraChunks } = this.prepareBlocks(params.childArr);
const cover = params.notionId ? yield this.resolveCoverForUpdate(params.cover) : params.cover;
this.debugLog("Upload2Notion", "Upserting general page", {
title: params.title,
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover != null ? cover : null,
notionIdExisting: (_a = params.notionId) != null ? _a : null,
tagList: params.tags
});
if (params.notionId) {
console.log(`[Upload2Notion] Deleting existing Notion page`, {
notionId: params.notionId
});
yield this.deletePage(params.notionId);
}
const body = this.buildGeneralBody({
title: params.title,
tags: params.tags,
firstChunk
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
});
}
upsertNext(params) {
return __async(this, null, function* () {
var _a;
const { firstChunk, extraChunks } = this.prepareBlocks(params.childArr);
const cover = params.notionId ? yield this.resolveCoverForUpdate(params.cover) : params.cover;
this.debugLog("Upload2Notion", "Upserting NotionNext page", {
title: params.title,
type: params.type,
slug: params.slug,
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover != null ? cover : null,
hasEmoji: !!params.emoji,
notionIdExisting: (_a = params.notionId) != null ? _a : null
});
if (params.notionId) {
yield this.deletePage(params.notionId);
}
const body = this.buildNextBody({
firstChunk,
title: params.title,
emoji: params.emoji,
tags: params.tags,
type: params.type,
slug: params.slug,
stats: params.stats,
category: params.category,
summary: params.summary,
password: params.password,
favicon: params.favicon,
datetime: params.datetime
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
});
}
upsertCustom(params) {
return __async(this, null, function* () {
var _a;
const { firstChunk, extraChunks } = this.prepareBlocks(params.childArr);
const cover = params.notionId ? yield this.resolveCoverForUpdate(params.cover) : params.cover;
this.debugLog("Upload2Notion", "Upserting custom page", {
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover != null ? cover : null,
notionIdExisting: (_a = params.notionId) != null ? _a : null,
customValueKeys: Object.keys(params.customValues || {})
});
if (params.notionId) {
yield this.deletePage(params.notionId);
}
const body = this.buildCustomBody({
customValues: params.customValues,
firstChunk
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
});
}
buildGeneralBody(params) {
const {
databaseID,
customTitleButton,
customTitleName,
tagButton
} = this.dbDetails;
return {
parent: {
database_id: databaseID
},
properties: __spreadValues({
[customTitleButton ? customTitleName : "title"]: {
title: [
{
text: {
content: params.title
}
}
]
}
}, tagButton ? {
tags: {
multi_select: params.tags && params.tags.length > 0 ? params.tags.map((tag) => ({ name: tag })) : []
}
} : {}),
children: params.firstChunk
};
}
buildNextBody(params) {
const { databaseID } = this.dbDetails;
const pageProperties = {
parent: {
database_id: databaseID
},
properties: {
title: {
title: [
{
text: {
content: params.title
}
}
]
},
type: {
select: {
name: params.type || "Post"
}
},
status: {
select: {
name: params.stats || "Draft"
}
},
category: {
select: {
name: params.category || "Obsidian"
}
},
password: {
rich_text: [
{
text: {
content: params.password || ""
}
}
]
},
icon: {
rich_text: [
{
text: {
content: params.favicon || ""
}
}
]
},
date: {
date: {
start: params.datetime || (/* @__PURE__ */ new Date()).toISOString()
}
}
}
};
if (params.tags && params.tags.length > 0) {
pageProperties.properties.tags = {
multi_select: params.tags.map((tag) => ({ name: tag }))
};
}
if (params.emoji) {
pageProperties.icon = {
emoji: params.emoji
};
}
if (params.slug) {
pageProperties.properties.slug = {
rich_text: [
{
text: {
content: params.slug
}
}
]
};
}
if (params.summary) {
pageProperties.properties.summary = {
rich_text: [
{
text: {
content: params.summary
}
}
]
};
}
return __spreadProps(__spreadValues({}, pageProperties), {
children: params.firstChunk
});
}
buildCustomBody(params) {
const { customProperties, databaseID } = this.dbDetails;
const properties = {};
if (customProperties) {
customProperties.forEach(({ customName, customType }) => {
if (params.customValues[customName] !== void 0) {
const propertyValue = this.buildCustomProperty(customName, customType, params.customValues);
if (propertyValue !== void 0) {
properties[customName] = propertyValue;
}
}
});
}
return {
parent: {
database_id: databaseID
},
properties,
children: params.firstChunk
};
}
buildCustomProperty(customName, customType, customValues) {
const value = customValues[customName] || "";
switch (customType) {
case "title":
return {
title: [
{
text: {
content: value
}
}
]
};
case "rich_text":
return {
rich_text: [
{
text: {
content: value || ""
}
}
]
};
case "date":
return {
date: {
start: value || (/* @__PURE__ */ new Date()).toISOString()
}
};
case "number":
return {
number: Number(value)
};
case "phone_number":
return {
phone_number: value
};
case "email":
return {
email: value
};
case "url":
return {
url: value
};
case "files":
return {
files: Array.isArray(value) ? value.map((url) => ({
name: url,
type: "external",
external: {
url
}
})) : [
{
name: value,
type: "external",
external: {
url: value
}
}
]
};
case "checkbox":
return {
checkbox: Boolean(value) || false
};
case "select":
return {
select: {
name: value
}
};
case "multi_select":
return {
multi_select: Array.isArray(value) ? value.map((item) => ({ name: item })) : [{ name: value }]
};
case "relation":
return {
relation: Array.isArray(value) ? value.map((item) => ({ id: item })) : [{ id: value }]
};
default:
return void 0;
}
}
};
// src/upload/common/getMarkdownNext.ts
var import_obsidian7 = require("obsidian");
function getNowFileMarkdownContentNext(app, settings) {
return __async(this, null, function* () {
const nowFile = app.workspace.getActiveFile();
let emoji = "";
let cover = "";
let tags = [];
let type = "";
let slug = "";
let stats = "";
let status = "";
let category = "";
let summary = "";
let paword = "";
let favicon = "";
let datetime = "";
const FileCache = app.metadataCache.getFileCache(nowFile);
try {
emoji = FileCache.frontmatter.titleicon;
cover = FileCache.frontmatter.coverurl;
tags = FileCache.frontmatter.tags;
type = FileCache.frontmatter.type;
slug = FileCache.frontmatter.slug;
stats = FileCache.frontmatter.stats || FileCache.frontmatter.status;
category = FileCache.frontmatter.category;
summary = FileCache.frontmatter.summary;
paword = FileCache.frontmatter.password;
favicon = FileCache.frontmatter.icon;
datetime = FileCache.frontmatter.date;
} catch (error) {
new import_obsidian7.Notice(i18nConfig["set-tags-fail"]);
}
if (nowFile) {
const markDownData = yield nowFile.vault.read(nowFile);
return {
markDownData,
nowFile,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime
};
} else {
new import_obsidian7.Notice(i18nConfig["open-file"]);
return;
}
});
}
// src/upload/common/getMarkdownGeneral.ts
var import_obsidian8 = require("obsidian");
function getNowFileMarkdownContentGeneral(app, settings) {
return __async(this, null, function* () {
const nowFile = app.workspace.getActiveFile();
let cover = "";
let tags = [];
const FileCache = app.metadataCache.getFileCache(nowFile);
try {
cover = FileCache.frontmatter.coverurl;
tags = FileCache.frontmatter.tags;
} catch (error) {
new import_obsidian8.Notice(i18nConfig["set-tags-fail"]);
}
if (nowFile) {
const markDownData = yield nowFile.vault.read(nowFile);
return {
markDownData,
nowFile,
cover,
tags
};
} else {
new import_obsidian8.Notice(i18nConfig["open-file"]);
return;
}
});
}
// src/upload/common/getMarkdownCustom.ts
var import_obsidian9 = require("obsidian");
function getNowFileMarkdownContentCustom(app, dbDetails) {
return __async(this, null, function* () {
const nowFile = app.workspace.getActiveFile();
if (!nowFile) {
new import_obsidian9.Notice(i18nConfig["open-file"]);
return;
}
let cover = "";
let customValues = {};
const FileCache = app.metadataCache.getFileCache(nowFile);
try {
cover = FileCache.frontmatter.coverurl;
const customPropertyNames = dbDetails.customProperties.filter((property) => property.customType !== "title").map((property) => property.customName);
customPropertyNames.forEach((propertyName) => {
if (FileCache.frontmatter && FileCache.frontmatter[propertyName] !== void 0) {
customValues[propertyName] = FileCache.frontmatter[propertyName];
}
});
const titleProperty = dbDetails.customProperties.find((property) => property.customType === "title");
if (titleProperty) {
customValues[titleProperty.customName] = FileCache.frontmatter && FileCache.frontmatter[titleProperty.customName] ? FileCache.frontmatter[titleProperty.customName] : (
// use the front matter value if it exists
nowFile.basename
);
}
} catch (error) {
new import_obsidian9.Notice(i18nConfig["set-tags-fail"]);
}
if (nowFile) {
const markDownData = yield nowFile.vault.read(nowFile);
return {
markDownData,
nowFile,
cover,
customValues
};
} else {
new import_obsidian9.Notice(i18nConfig["open-file"]);
return;
}
});
}
// src/upload/uploadCommand.ts
var SYNC_ERROR_NOTICE_DURATION = 8e3;
function extractErrorMessage(error) {
if (error instanceof Error && error.message) {
return error.message;
}
return String(error);
}
function shouldShowAutoSyncSuccessNotice(plugin, options) {
if (!(options == null ? void 0 : options.isAutoSync)) {
return true;
}
return !!plugin.settings.autoSyncSuccessNotice;
}
function notifySyncError(prefix, basename2, error) {
const errorMessage = extractErrorMessage(error);
console.error(`${prefix} Sync failed`, error);
new import_obsidian10.Notice(
`${i18nConfig["sync-fail"]} ${basename2}. ${errorMessage}
${i18nConfig["CheckConsole"]}`,
SYNC_ERROR_NOTICE_DURATION
);
}
function logCommandDebug(context, message, payload) {
if (payload) {
console.log(`[${context}] ${message}`, payload);
} else {
console.log(`[${context}] ${message}`);
}
}
function uploadCommandNext(plugin, settings, dbDetails, app, options) {
return __async(this, null, function* () {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
const { notionAPI, databaseID } = dbDetails;
console.log(`[uploadCommandNext] ${(/* @__PURE__ */ new Date()).toISOString()} Triggered for file`, (_a = app.workspace.getActiveFile()) == null ? void 0 : _a.path);
if (notionAPI === "" || databaseID === "") {
const setAPIMessage = i18nConfig["set-api-id"];
new import_obsidian10.Notice(setAPIMessage);
return;
}
const {
markDownData,
nowFile,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime
} = yield getNowFileMarkdownContentNext(app, settings);
logCommandDebug("uploadCommandNext", "Metadata extracted from markdown", {
hasMarkdown: !!markDownData,
markdownLength: (_b = markDownData == null ? void 0 : markDownData.length) != null ? _b : 0,
tagCount: (_c = tags == null ? void 0 : tags.length) != null ? _c : 0,
coverIncluded: !!cover,
hasEmoji: !!emoji,
type,
slug,
hasPassword: !!paword,
datetime
});
if (markDownData) {
const { basename: basename2 } = nowFile;
logCommandDebug("uploadCommandNext", "Preparing to upload", {
filename: basename2,
filePath: nowFile.path
});
const upload = new Upload2Notion(plugin, dbDetails);
let res;
try {
res = yield upload.sync({
dataset: "next",
isAutoSync: options == null ? void 0 : options.isAutoSync,
title: basename2,
emoji: emoji || "",
cover: cover || "",
tags: tags || [],
type: type || "",
slug: slug || "",
stats: stats || "",
category: category || "",
summary: summary || "",
password: paword || "",
favicon: favicon || "",
datetime: datetime || "",
markdown: markDownData,
nowFile,
app
});
} catch (error) {
notifySyncError("[uploadCommandNext]", basename2, error);
logCommandDebug("uploadCommandNext", "Sync threw error", {
filename: basename2,
error: extractErrorMessage(error)
});
return;
}
const { response } = res;
if (response.status === 200) {
if (shouldShowAutoSyncSuccessNotice(plugin, options)) {
new import_obsidian10.Notice(`${i18nConfig["sync-preffix"]} ${basename2} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
}
logCommandDebug("uploadCommandNext", "Sync succeeded", {
filename: basename2,
status: response.status,
pageId: (_e = (_d = res.data) == null ? void 0 : _d.id) != null ? _e : null,
pageUrl: (_g = (_f = res.data) == null ? void 0 : _f.url) != null ? _g : null
});
} else {
new import_obsidian10.Notice(`${i18nConfig["sync-fail"]} ${basename2}`, 5e3);
console.log(`${i18nConfig["sync-fail"]} ${basename2}`);
logCommandDebug("uploadCommandNext", "Sync failed with status", {
filename: basename2,
status: response.status,
errorCode: (_i = (_h = res.data) == null ? void 0 : _h.code) != null ? _i : null,
errorStatus: (_k = (_j = res.data) == null ? void 0 : _j.status) != null ? _k : null
});
}
}
});
}
function uploadCommandGeneral(plugin, settings, dbDetails, app, options) {
return __async(this, null, function* () {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
const { notionAPI, databaseID } = dbDetails;
console.log(`[uploadCommandGeneral] ${(/* @__PURE__ */ new Date()).toISOString()} Triggered for file`, (_a = app.workspace.getActiveFile()) == null ? void 0 : _a.path);
if (notionAPI === "" || databaseID === "") {
const setAPIMessage = i18nConfig["set-api-id"];
new import_obsidian10.Notice(setAPIMessage);
return;
}
const { markDownData, nowFile, cover, tags } = yield getNowFileMarkdownContentGeneral(app, settings);
if (!(options == null ? void 0 : options.isAutoSync)) {
new import_obsidian10.Notice(i18nConfig.StartUpload.replace("{filename}", nowFile.basename));
}
console.log(`Start upload ${nowFile.basename}`);
if (markDownData) {
const { basename: basename2 } = nowFile;
logCommandDebug("uploadCommandGeneral", "Preparing to upload", {
filename: basename2,
markdownLength: markDownData.length,
tagCount: (_b = tags == null ? void 0 : tags.length) != null ? _b : 0,
hasCover: !!cover
});
const upload = new Upload2Notion(plugin, dbDetails);
let res;
try {
res = yield upload.sync({
dataset: "general",
isAutoSync: options == null ? void 0 : options.isAutoSync,
title: basename2,
cover: cover || "",
tags: tags || [],
markdown: markDownData,
nowFile,
app
});
} catch (error) {
notifySyncError("[uploadCommandGeneral]", basename2, error);
logCommandDebug("uploadCommandGeneral", "Sync threw error", {
filename: basename2,
error: extractErrorMessage(error)
});
return;
}
const { response } = res;
if (response.status === 200) {
if (shouldShowAutoSyncSuccessNotice(plugin, options)) {
new import_obsidian10.Notice(`${i18nConfig["sync-preffix"]} ${basename2} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
}
logCommandDebug("uploadCommandGeneral", "Sync succeeded", {
filename: basename2,
status: response.status,
pageId: (_d = (_c = res.data) == null ? void 0 : _c.id) != null ? _d : null,
pageUrl: (_f = (_e = res.data) == null ? void 0 : _e.url) != null ? _f : null
});
} else {
new import_obsidian10.Notice(`${i18nConfig["sync-fail"]} ${basename2}`, 5e3);
console.log(`${i18nConfig["sync-fail"]} ${basename2}`);
logCommandDebug("uploadCommandGeneral", "Sync failed with status", {
filename: basename2,
status: response.status,
errorCode: (_h = (_g = res.data) == null ? void 0 : _g.code) != null ? _h : null,
errorStatus: (_j = (_i = res.data) == null ? void 0 : _i.status) != null ? _j : null
});
}
}
});
}
function uploadCommandCustom(plugin, settings, dbDetails, app, options) {
return __async(this, null, function* () {
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
const { notionAPI, databaseID } = dbDetails;
console.log(`[uploadCommandCustom] ${(/* @__PURE__ */ new Date()).toISOString()} Triggered for file`, (_a = app.workspace.getActiveFile()) == null ? void 0 : _a.path);
if (notionAPI === "" || databaseID === "") {
const setAPIMessage = i18nConfig["set-api-id"];
new import_obsidian10.Notice(setAPIMessage);
return;
}
const { markDownData, nowFile, cover, customValues } = yield getNowFileMarkdownContentCustom(app, dbDetails);
if (!(options == null ? void 0 : options.isAutoSync)) {
new import_obsidian10.Notice(i18nConfig.StartUpload.replace("{filename}", nowFile.basename));
}
console.log(`Start upload ${nowFile.basename}`);
if (markDownData) {
const { basename: basename2 } = nowFile;
logCommandDebug("uploadCommandCustom", "Preparing to upload", {
filename: basename2,
markdownLength: markDownData.length,
hasCover: !!cover,
customValueKeys: Object.keys(customValues || {})
});
const upload = new Upload2Notion(plugin, dbDetails);
let res;
try {
res = yield upload.sync({
dataset: "custom",
isAutoSync: options == null ? void 0 : options.isAutoSync,
cover: cover || "",
customValues,
markdown: markDownData,
nowFile,
app
});
} catch (error) {
notifySyncError("[uploadCommandCustom]", basename2, error);
logCommandDebug("uploadCommandCustom", "Sync threw error", {
filename: basename2,
error: extractErrorMessage(error)
});
return;
}
const { response } = res;
if (response.status === 200) {
if (shouldShowAutoSyncSuccessNotice(plugin, options)) {
new import_obsidian10.Notice(`${i18nConfig["sync-preffix"]} ${basename2} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
}
logCommandDebug("uploadCommandCustom", "Sync succeeded", {
filename: basename2,
status: response.status,
pageId: (_c = (_b = res.data) == null ? void 0 : _b.id) != null ? _c : null,
pageUrl: (_e = (_d = res.data) == null ? void 0 : _d.url) != null ? _e : null
});
} else {
new import_obsidian10.Notice(`${i18nConfig["sync-fail"]} ${basename2}`, 5e3);
console.log(`${i18nConfig["sync-fail"]} ${basename2}`);
logCommandDebug("uploadCommandCustom", "Sync failed with status", {
filename: basename2,
status: response.status,
errorCode: (_g = (_f = res.data) == null ? void 0 : _f.code) != null ? _g : null,
errorStatus: (_i = (_h = res.data) == null ? void 0 : _h.status) != null ? _i : null
});
}
}
});
}
// src/commands/NotionCommands.ts
var RibbonCommands = class {
constructor(plugin) {
this.Ncommand = [];
this.plugin = plugin;
for (let key in this.plugin.settings.databaseDetails) {
let dbDetails = this.plugin.settings.databaseDetails[key];
this.addCommandForDatabase(dbDetails);
}
this.Ncommand.forEach((command) => {
this.plugin.addCommand(
{
id: command.id,
name: command.name,
editorCallback: command.editorCallback
}
);
});
}
ribbonDisplay() {
return __async(this, null, function* () {
const NcommandList = [];
this.Ncommand.map(
(command) => NcommandList.push(
{
name: command.name,
match: command.editorCallback
}
)
);
const fusg = new FuzzySuggester(this.plugin);
fusg.setSuggesterData(NcommandList);
yield fusg.display((results) => __async(this, null, function* () {
yield results.match();
}));
});
}
// if the setting has been changed, try to rebuild the command list
updateCommand() {
return __async(this, null, function* () {
this.Ncommand = [];
for (let key in this.plugin.settings.databaseDetails) {
let dbDetails = this.plugin.settings.databaseDetails[key];
this.addCommandForDatabase(dbDetails);
}
this.Ncommand.forEach((command) => {
this.plugin.addCommand(
{
id: command.id,
name: command.name,
editorCallback: command.editorCallback
}
);
});
});
}
addCommandForDatabase(dbDetails) {
let commandId = `share-to-${dbDetails.abName}`;
let commandName = `Share to ${dbDetails.fullName} (${dbDetails.abName})`;
let editorCallback;
if (dbDetails.format === "next") {
editorCallback = (editor, view) => __async(this, null, function* () {
yield uploadCommandNext(this.plugin, this.plugin.settings, dbDetails, this.plugin.app);
});
} else if (dbDetails.format === "general") {
editorCallback = (editor, view) => __async(this, null, function* () {
yield uploadCommandGeneral(this.plugin, this.plugin.settings, dbDetails, this.plugin.app);
});
} else if (dbDetails.format === "custom") {
editorCallback = (editor, view) => __async(this, null, function* () {
yield uploadCommandCustom(this.plugin, this.plugin.settings, dbDetails, this.plugin.app);
});
}
this.Ncommand.push({ id: commandId, name: commandName, editorCallback });
}
};
// src/ui/settingTabs.ts
var import_obsidian15 = require("obsidian");
// src/ui/settingModal.ts
var import_obsidian11 = require("obsidian");
var SettingModal = class extends import_obsidian11.Modal {
constructor(app, plugin, settingTab, dbDetails) {
super(app);
this.propertyLines = [];
// Store all property line settings
this.properties = [];
// Index signature
this.data = {
databaseFormat: "none",
databaseFullName: "",
databaseAbbreviateName: "",
notionAPI: "",
databaseID: "",
tagButton: true,
customTitleButton: false,
customTitleName: "",
customProperties: [],
// customValues: '',
saved: false
};
this.plugin = plugin;
this.settingTab = settingTab;
this.properties = [];
if (dbDetails) {
this.data.databaseFormat = dbDetails.format;
this.data.databaseFullName = dbDetails.fullName;
this.data.databaseAbbreviateName = dbDetails.abName;
this.data.notionAPI = dbDetails.notionAPI;
this.data.databaseID = dbDetails.databaseID;
this.data.tagButton = dbDetails.tagButton;
this.data.customTitleButton = dbDetails.customTitleButton;
this.data.customTitleName = dbDetails.customTitleName;
this.data.customProperties = dbDetails.customProperties;
this.data.saved = dbDetails.saved;
}
}
display() {
this.containerEl.addClass("settings-modal");
this.titleEl.setText(i18nConfig.AddNewDatabaseModal);
let { contentEl } = this;
contentEl.empty();
const settingDiv = contentEl.createDiv("setting-div");
const nextTabs = contentEl.createDiv("next-tabs");
new import_obsidian11.Setting(settingDiv).setName(i18nConfig.databaseFormat).setDesc(i18nConfig.databaseFormatDesc).addDropdown((component) => {
component.addOption("none", "").addOption("general", i18nConfig.databaseGeneral).addOption("next", i18nConfig.databaseNext).addOption("custom", i18nConfig.databaseCustom).setValue(this.data.databaseFormat).onChange((value) => __async(this, null, function* () {
this.data.databaseFormat = value;
nextTabs.empty();
this.updateContentBasedOnSelection(value, nextTabs);
}));
this.data.saved ? this.updateContentBasedOnSelection(this.data.databaseFormat, nextTabs) : this.updateContentBasedOnSelection(this.plugin.settings.databaseFormat, nextTabs);
});
let footerEl = contentEl.createDiv("save-button");
let saveButton = new import_obsidian11.Setting(footerEl);
saveButton.addButton(
(button) => {
return button.setTooltip("Save").setIcon("checkmark").onClick(() => __async(this, null, function* () {
this.data.saved = true;
this.data.customProperties = this.properties;
this.close();
}));
}
);
saveButton.addExtraButton(
(button) => {
return button.setTooltip("Cancel").setIcon("cross").onClick(() => {
this.data.saved = false;
this.close();
});
}
);
}
updateContentBasedOnSelection(value, nextTabs) {
nextTabs.empty();
if (value === "general") {
nextTabs.createEl("h3", { text: i18nConfig.NotionGeneralSettingHeader });
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, "text", i18nConfig.databaseFullNameText, this.data.databaseFullName, "data", "databaseFullName");
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, "text", i18nConfig.databaseAbbreviateNameText, this.data.databaseAbbreviateName, "data", "databaseAbbreviateName");
this.createSettingEl(nextTabs, i18nConfig.NotionTagButton, i18nConfig.NotionTagButtonDesc, "toggle", i18nConfig.NotionCustomTitleText, this.data.tagButton, "data", "tagButton");
new import_obsidian11.Setting(nextTabs).setName(i18nConfig.NotionCustomTitle).setDesc(i18nConfig.NotionCustomTitleDesc).addToggle(
(toggle) => toggle.setValue(this.data.customTitleButton).onChange((value2) => __async(this, null, function* () {
this.data.customTitleButton = value2;
this.updateSettingEl(CustomNameEl, value2);
}))
);
const CustomNameEl = this.createStyleDiv("custom-name", this.data.customTitleButton, nextTabs);
this.createSettingEl(CustomNameEl, i18nConfig.NotionCustomTitleName, i18nConfig.NotionCustomTitleNameDesc, "text", i18nConfig.NotionCustomTitleText, this.data.customTitleName, "data", "customTitleName");
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, "password", i18nConfig.NotionAPIText, this.data.notionAPI, "data", "notionAPI");
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, "password", i18nConfig.DatabaseIDText, this.data.databaseID, "data", "databaseID");
} else if (value === "next") {
nextTabs.createEl("h3", { text: i18nConfig.NotionNextSettingHeader });
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, "text", i18nConfig.databaseFullNameText, this.data.databaseFullName, "data", "databaseFullName");
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, "text", i18nConfig.databaseAbbreviateNameText, this.data.databaseAbbreviateName, "data", "databaseAbbreviateName");
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, "password", i18nConfig.NotionAPIText, this.data.notionAPI, "data", "notionAPI");
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, "password", i18nConfig.DatabaseIDText, this.data.databaseID, "data", "databaseID");
} else if (value === "custom") {
nextTabs.createEl("h3", { text: i18nConfig.NotionCustomSettingHeader });
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, "text", i18nConfig.databaseFullNameText, this.data.databaseFullName, "data", "databaseFullName");
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, "text", i18nConfig.databaseAbbreviateNameText, this.data.databaseAbbreviateName, "data", "databaseAbbreviateName");
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, "password", i18nConfig.NotionAPIText, this.data.notionAPI, "data", "notionAPI");
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, "password", i18nConfig.DatabaseIDText, this.data.databaseID, "data", "databaseID");
new import_obsidian11.Setting(nextTabs).setName(i18nConfig.NotionCustomValues).setDesc(i18nConfig.NotionCustomValuesDesc).addButton(
(button) => {
return button.setTooltip("Add one more property").setButtonText("Add New Property").onClick(() => __async(this, null, function* () {
const customTabs = nextTabs.createDiv("custom-tabs");
this.createPropertyLine(customTabs, this.properties);
}));
}
);
}
}
onOpen() {
this.display();
}
createPropertyLine(containerEl, properties) {
const propertyIndex = properties.length;
properties.push({ customName: "", customType: "", index: propertyIndex });
const propertyLine = new import_obsidian11.Setting(containerEl).setName(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${propertyIndex}`).setDesc(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumnDesc : "");
propertyLine.addText((text5) => {
text5.setPlaceholder(i18nConfig.CustomPropertyName).setValue("").onChange((value) => {
let actualIndex = properties.findIndex((p) => p.index === propertyIndex);
if (actualIndex !== -1) {
properties[actualIndex].customName = value;
}
});
});
propertyLine.addDropdown((dropdown) => {
const options = {
"rich_text": "Text",
"number": "Number",
"select": "Select",
"multi_select": "Multi-Select",
"date": "Date",
"files": "Files & Media",
"checkbox": "Checkbox",
"url": "URL",
"email": "Email",
"phone_number": "Phone Number"
// 'formula': 'Formula',
// 'relation': 'Relation',
// 'rollup': 'Rollup',
// 'created_time': 'Created time',
// 'created_by': 'Created by',
// 'last_edited_time': 'Last Edited Time',
// 'last_edited_by': 'Last Edited By',
};
const currentProperty = properties[propertyIndex];
if (propertyIndex === 0) {
dropdown.addOption("title", "Title");
} else {
Object.keys(options).forEach((key) => {
dropdown.addOption(key, options[key]);
});
}
dropdown.setValue("").onChange((value) => {
if (currentProperty) {
currentProperty.customType = value;
const updatedIndex = properties.findIndex((p) => p === currentProperty);
console.log(`Updated value at index ${updatedIndex}: ${value}`);
} else {
console.log("Property not found, may have been deleted.");
}
});
});
if (propertyIndex > 0) {
propertyLine.addButton((button) => {
return button.setTooltip("Delete").setIcon("trash").onClick(() => {
this.deleteProperty(propertyIndex, properties);
});
});
}
this.propertyLines.push(propertyLine);
this.updatePropertyLines();
}
deleteProperty(propertyIndex, properties) {
let actualIndex = properties.findIndex((p) => p.index === propertyIndex);
if (actualIndex !== -1) {
properties.splice(actualIndex, 1);
if (this.propertyLines[actualIndex]) {
this.propertyLines[actualIndex].settingEl.remove();
this.propertyLines.splice(actualIndex, 1);
}
properties.forEach((prop, idx) => {
prop.index = idx;
});
this.updatePropertyLines();
}
}
updatePropertyLines() {
this.propertyLines.forEach((line, idx) => {
line.setName(idx === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${idx}`);
});
}
// create a function to create a div with a style for pop over elements
createStyleDiv(className, commandValue = false, parentEl) {
return parentEl.createDiv(className, (div) => {
this.updateSettingEl(div, commandValue);
});
}
// update the setting display style in the setting tab
updateSettingEl(element2, commandValue) {
element2.style.borderTop = commandValue ? "1px solid var(--background-modifier-border)" : "none";
element2.style.paddingTop = commandValue ? "0.75em" : "0";
element2.style.display = commandValue ? "block" : "none";
element2.style.alignItems = "center";
}
// function to add one setting element in the setting tab.
createSettingEl(contentEl, name, desc, type, placeholder, holderValue, dataRecord, settingsKey) {
if (type === "password") {
return new import_obsidian11.Setting(contentEl).setName(name).setDesc(desc).addText((text5) => {
text5.inputEl.type = type;
return text5.setPlaceholder(placeholder).setValue(holderValue).onChange((value) => __async(this, null, function* () {
this[dataRecord][settingsKey] = value;
}));
});
} else if (type === "toggle") {
return new import_obsidian11.Setting(contentEl).setName(name).setDesc(desc).addToggle(
(toggle) => toggle.setValue(holderValue).onChange((value) => __async(this, null, function* () {
this[dataRecord][settingsKey] = value;
}))
);
} else if (type === "text") {
return new import_obsidian11.Setting(contentEl).setName(name).setDesc(desc).addText(
(text5) => text5.setPlaceholder(placeholder).setValue(holderValue).onChange((value) => __async(this, null, function* () {
this[dataRecord][settingsKey] = value;
}))
);
}
}
};
// src/ui/PreviewModal.ts
var import_obsidian12 = require("obsidian");
var PreviewModal = class extends import_obsidian12.Modal {
constructor(app, plugin, settingTab, dbDetails) {
super(app);
this.plugin = plugin;
this.settingTab = settingTab;
this.dbDetails = dbDetails;
}
display() {
this.containerEl.addClass("preview-modal");
this.titleEl.setText(i18nConfig.Preview);
let { contentEl } = this;
const previewEl = contentEl.createDiv("preview-content");
const dbFormatEl = new import_obsidian12.Setting(previewEl);
dbFormatEl.setName(i18nConfig.DatabaseFormatLabel).addText((text5) => text5.setValue(this.dbDetails.format).setDisabled(true));
const dbFullEl = new import_obsidian12.Setting(previewEl);
dbFullEl.setName(i18nConfig.DatabaseFullNameLabel).addText((text5) => text5.setValue(this.dbDetails.fullName).setDisabled(true));
const dbAbbrEl = new import_obsidian12.Setting(previewEl);
dbAbbrEl.setName(i18nConfig.DatabaseAbbreviateNameLabel).addText((text5) => text5.setValue(this.dbDetails.abName).setDisabled(true));
new import_obsidian12.Setting(previewEl).setName(i18nConfig.NotionAPILabel).addExtraButton((button) => {
let isApiKeyVisible = false;
return button.setTooltip(i18nConfig.ToggleAPIKeyVisibility).setIcon("eye").onClick(() => {
isApiKeyVisible = !isApiKeyVisible;
button.setIcon(isApiKeyVisible ? "eye-off" : "eye");
apiKeySetting.settingEl.style.display = isApiKeyVisible ? "" : "none";
});
});
const apiKeySetting = new import_obsidian12.Setting(previewEl);
apiKeySetting.infoEl.createEl("p", { text: this.dbDetails.notionAPI });
apiKeySetting.addExtraButton((button) => {
return button.setTooltip(i18nConfig.CopyAPIKey).setIcon("clipboard").onClick(() => {
navigator.clipboard.writeText(this.dbDetails.notionAPI);
new import_obsidian12.Notice(i18nConfig.APIKeyCopied);
});
});
apiKeySetting.settingEl.style.display = "none";
new import_obsidian12.Setting(previewEl).setName(i18nConfig.DatabaseIDLabel).addExtraButton((button) => {
let isDbIdVisible = false;
return button.setTooltip(i18nConfig.ToggleDatabaseIDVisibility).setIcon("eye").onClick(() => {
isDbIdVisible = !isDbIdVisible;
button.setIcon(isDbIdVisible ? "eye-off" : "eye");
dbIdSetting.settingEl.style.display = isDbIdVisible ? "" : "none";
});
});
const dbIdSetting = new import_obsidian12.Setting(previewEl);
dbIdSetting.infoEl.createEl("p", { text: this.dbDetails.databaseID });
dbIdSetting.addExtraButton((button) => {
return button.setTooltip(i18nConfig.CopyDatabaseID).setIcon("clipboard").onClick(() => {
navigator.clipboard.writeText(this.dbDetails.databaseID);
new import_obsidian12.Notice(i18nConfig.DatabaseIDCopied);
});
});
dbIdSetting.settingEl.style.display = "none";
if (this.dbDetails.format === "custom") {
const customPrv = previewEl.createDiv("custom-tabs");
this.previewPropertyLine(previewEl, this.dbDetails.customProperties);
}
}
onOpen() {
this.display();
}
previewPropertyLine(containerEl, properties) {
properties.forEach((property, index2) => {
const propertyLine = new import_obsidian12.Setting(containerEl).setName(index2 === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${index2}`).setDesc(index2 === 0 ? i18nConfig.CustomPropertyFirstColumnDesc : "");
propertyLine.addText((text5) => {
text5.setPlaceholder(i18nConfig.CustomPropertyName).setValue(property.customName).setDisabled(true);
});
propertyLine.addDropdown((dropdown) => {
const options = {
"title": "Title",
"rich_text": "Text",
"number": "Number",
"select": "Select",
"multi_select": "Multi-Select",
"date": "Date",
"files": "Files & Media",
"checkbox": "Checkbox",
"url": "URL",
"email": "Email",
"phone_number": "Phone Number"
// Additional options can be added here
};
Object.keys(options).forEach((key) => {
dropdown.addOption(key, options[key]);
});
dropdown.setValue(property.customType).setDisabled(true);
});
});
}
};
// src/ui/EditModal.ts
var import_obsidian13 = require("obsidian");
var EditModal = class extends SettingModal {
constructor(app, plugin, settingTab, dbDetails) {
super(app, plugin, settingTab);
this.propertyLines = [];
// Index signature
this.dataTemp = {
databaseFormatTemp: "",
// databaseFormatTempInd: false,
databaseFullNameTemp: "",
// databaseFullNameTempInd: false,
databaseAbbreviateNameTemp: "",
// databaseAbbreviateNameTempInd: false,
notionAPITemp: "",
// notionAPITempInd: false,
databaseIDTemp: "",
// databaseIDTempInd: false,
tagButtonTemp: false,
// tagButtonTempInd: false,
customTitleButtonTemp: false,
// customTitleButtonTempInd: false,
customTitleNameTemp: "",
customPropertiesTemp: [],
// customTitleNameTempInd: false,
// customValues: '',
savedTemp: false,
savedTempInd: false
};
this.dataPrev = {
databaseFormatPrev: "",
// databaseFormatPrevInd: false,
databaseFullNamePrev: "",
// databaseFullNamePrevInd: false,
databaseAbbreviateNamePrev: "",
// databaseAbbreviateNamePrevInd: false,
notionAPIPrev: "",
// notionAPIPrevInd: false,
databaseIDPrev: "",
// databaseIDPrevInd: false,
tagButtonPrev: false,
// tagButtonPrevInd: false,
customTitleButtonPrev: false,
// customTitleButtonPrevInd: false,
customTitleNamePrev: "",
customPropertiesPrev: [],
// customTitleNamePrevInd: false,
// customValues: '',
savedPrev: false,
savedPrevInd: false
};
this.plugin = plugin;
this.settingTab = settingTab;
if (dbDetails) {
this.dataTemp.databaseFormatTemp = dbDetails.format;
this.dataTemp.databaseFullNameTemp = dbDetails.fullName;
this.dataTemp.databaseAbbreviateNameTemp = dbDetails.abName;
this.dataTemp.notionAPITemp = dbDetails.notionAPI;
this.dataTemp.databaseIDTemp = dbDetails.databaseID;
this.dataTemp.tagButtonTemp = dbDetails.tagButton;
this.dataTemp.customTitleButtonTemp = dbDetails.customTitleButton;
this.dataTemp.customTitleNameTemp = dbDetails.customTitleName;
this.dataTemp.customPropertiesTemp = dbDetails.customProperties.map((prop) => __spreadValues({}, prop));
this.dataTemp.savedTemp = dbDetails.saved;
this.dataPrev.databaseFormatPrev = dbDetails.format;
this.dataPrev.databaseFullNamePrev = dbDetails.fullName;
this.dataPrev.databaseAbbreviateNamePrev = dbDetails.abName;
this.dataPrev.notionAPIPrev = dbDetails.notionAPI;
this.dataPrev.databaseIDPrev = dbDetails.databaseID;
this.dataPrev.tagButtonPrev = dbDetails.tagButton;
this.dataPrev.customTitleButtonPrev = dbDetails.customTitleButton;
this.dataPrev.customTitleNamePrev = dbDetails.customTitleName;
this.dataPrev.customPropertiesPrev = dbDetails.customProperties.map((prop) => __spreadValues({}, prop));
this.dataPrev.savedPrev = dbDetails.saved;
}
}
display() {
this.containerEl.addClass("edit-modal");
this.titleEl.setText(i18nConfig.EditDatabase);
let { contentEl } = this;
contentEl.empty();
const editDiv = contentEl.createDiv("edit-div");
const nextTabs = contentEl.createDiv("next-tabs");
new import_obsidian13.Setting(editDiv).setName(i18nConfig.databaseFormat).setDesc(i18nConfig.databaseFormatDesc).addDropdown((component) => {
component.addOption("none", "").addOption("general", i18nConfig.databaseGeneral).addOption("next", i18nConfig.databaseNext).addOption("custom", i18nConfig.databaseCustom).setValue(this.dataTemp.databaseFormatTemp).onChange((value) => __async(this, null, function* () {
this.dataTemp.databaseFormatTemp = value;
nextTabs.empty();
this.updateContentBasedOnSelection(value, nextTabs);
}));
this.updateContentBasedOnSelection(this.dataTemp.databaseFormatTemp, nextTabs);
});
let footerEl = contentEl.createDiv("save-button");
let saveButton = new import_obsidian13.Setting(footerEl);
saveButton.addButton(
(button) => {
return button.setTooltip("Save").setIcon("checkmark").onClick(() => __async(this, null, function* () {
this.dataTemp.savedTempInd = true;
this.dataTemp.savedTemp = true;
this.close();
}));
}
);
saveButton.addExtraButton(
(button) => {
return button.setTooltip("Cancel").setIcon("cross").onClick(() => {
this.close();
});
}
);
}
onOpen() {
this.display();
}
updateContentBasedOnSelection(value, nextTabs) {
nextTabs.empty();
if (value === "general") {
nextTabs.createEl("h3", { text: i18nConfig.NotionGeneralSettingHeader });
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, "text", i18nConfig.databaseFullNameText, this.dataTemp.databaseFullNameTemp, "dataTemp", "databaseFullNameTemp");
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, "text", i18nConfig.databaseAbbreviateNameText, this.dataTemp.databaseAbbreviateNameTemp, "dataTemp", "databaseAbbreviateNameTemp");
this.createSettingEl(nextTabs, i18nConfig.NotionTagButton, i18nConfig.NotionTagButtonDesc, "toggle", i18nConfig.NotionCustomTitleText, this.dataTemp.tagButtonTemp, "dataTemp", "tagButtonTemp");
new import_obsidian13.Setting(nextTabs).setName(i18nConfig.NotionCustomTitle).setDesc(i18nConfig.NotionCustomTitleDesc).addToggle(
(toggle) => toggle.setValue(this.dataTemp.customTitleButtonTemp).onChange((value2) => __async(this, null, function* () {
this.dataTemp.customTitleButtonTemp = value2;
this.updateSettingEl(CustomNameEl, value2);
}))
);
const CustomNameEl = this.createStyleDiv("custom-name", this.dataTemp.customTitleButtonTemp, nextTabs);
this.createSettingEl(CustomNameEl, i18nConfig.NotionCustomTitleName, i18nConfig.NotionCustomTitleNameDesc, "text", i18nConfig.NotionCustomTitleText, this.dataTemp.customTitleNameTemp, "dataTemp", "customTitleNameTemp");
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, "password", i18nConfig.NotionAPIText, this.dataTemp.notionAPITemp, "dataTemp", "notionAPITemp");
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, "password", i18nConfig.DatabaseIDText, this.dataTemp.databaseIDTemp, "dataTemp", "databaseIDTemp");
} else if (value === "next") {
nextTabs.createEl("h3", { text: i18nConfig.NotionNextSettingHeader });
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, "text", i18nConfig.databaseFullNameText, this.dataTemp.databaseFullNameTemp, "dataTemp", "databaseFullNameTemp");
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, "text", i18nConfig.databaseAbbreviateNameText, this.dataTemp.databaseAbbreviateNameTemp, "dataTemp", "databaseAbbreviateNameTemp");
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, "password", i18nConfig.NotionAPIText, this.dataTemp.notionAPITemp, "dataTemp", "notionAPITemp");
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, "password", i18nConfig.DatabaseIDText, this.dataTemp.databaseIDTemp, "dataTemp", "databaseIDTemp");
} else if (value === "custom") {
nextTabs.createEl("h3", { text: i18nConfig.NotionCustomSettingHeader });
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, "text", i18nConfig.databaseFullNameText, this.dataTemp.databaseFullNameTemp, "dataTemp", "databaseFullNameTemp");
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, "text", i18nConfig.databaseAbbreviateNameText, this.dataTemp.databaseAbbreviateNameTemp, "dataTemp", "databaseAbbreviateNameTemp");
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, "password", i18nConfig.NotionAPIText, this.dataTemp.notionAPITemp, "dataTemp", "notionAPITemp");
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, "password", i18nConfig.DatabaseIDText, this.dataTemp.databaseIDTemp, "dataTemp", "databaseIDTemp");
this.initializePropertyLines(nextTabs, this.dataTemp.customPropertiesTemp);
}
}
initializePropertyLines(containerEl, properties) {
if (!containerEl) {
console.error("Failed to initialize property lines: containerEl is null");
return;
}
new import_obsidian13.Setting(containerEl).setName(i18nConfig.AddNewProperty).setDesc(i18nConfig.AddNewPropertyDesc).addButton((button) => {
return button.setButtonText("Add").setTooltip("Add one more property").onClick(() => {
this.createPropertyLine(containerEl, properties);
});
});
properties.forEach((property) => {
this.updatePropertyLine(containerEl, property, properties);
});
}
updatePropertyLine(containerEl, property, properties) {
let isExistingProperty = property !== null;
const propertyIndex = isExistingProperty ? property.index : properties.length;
const propertyLine = new import_obsidian13.Setting(containerEl).setName(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${propertyIndex}`).setDesc(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumnDesc : "");
propertyLine.addText((text5) => {
text5.setPlaceholder(i18nConfig.CustomPropertyName).setValue(isExistingProperty ? property.customName : "").onChange((value) => {
const actualIndex = properties.findIndex((p) => p.index === propertyIndex);
if (actualIndex !== -1) {
properties[actualIndex].customName = value;
} else {
properties.push({ customName: value, customType: "", index: propertyIndex });
isExistingProperty = true;
}
});
});
propertyLine.addDropdown((dropdown) => {
const options = {
"rich_text": "Text",
"number": "Number",
"select": "Select",
"multi_select": "Multi-Select",
"date": "Date",
"files": "Files & Media",
"checkbox": "Checkbox",
"url": "URL",
"email": "Email",
"phone_number": "Phone Number"
};
if (propertyIndex === 0) {
dropdown.addOption("title", "Title");
} else {
Object.keys(options).forEach((key) => {
dropdown.addOption(key, options[key]);
});
}
dropdown.setValue(isExistingProperty ? property.customType : "").onChange((value) => {
const actualIndex = properties.findIndex((p) => p.index === propertyIndex);
if (actualIndex !== -1) {
properties[actualIndex].customType = value;
} else if (!isExistingProperty) {
properties.push({ customName: "", customType: value, index: propertyIndex });
isExistingProperty = true;
}
});
});
if (propertyIndex > 0) {
propertyLine.addButton((button) => {
return button.setTooltip("Delete").setIcon("trash").onClick(() => {
console.log("Deleting property", properties[propertyIndex]);
this.deleteProperty(propertyIndex, properties);
});
});
}
this.propertyLines.push(propertyLine);
this.updatePropertyLines();
}
createStyleDiv(className, commandValue = false, parentEl) {
return super.createStyleDiv(className, commandValue, parentEl);
}
updateSettingEl(element2, commandValue) {
super.updateSettingEl(element2, commandValue);
}
createSettingEl(contentEl, name, desc, type, placeholder, holderValue, dataRecord, settingsKey) {
return super.createSettingEl(contentEl, name, desc, type, placeholder, holderValue, dataRecord, settingsKey);
}
};
// src/ui/DeleteModal.ts
var import_obsidian14 = require("obsidian");
var DeleteModal = class extends import_obsidian14.Modal {
constructor(app, plugin, settingTab, dbDetails) {
super(app);
this.data = {
deleted: false
};
this.plugin = plugin;
this.settingTab = settingTab;
this.dbDetails = dbDetails;
}
display() {
this.containerEl.addClass("delete-modal");
this.titleEl.setText("Delete Database");
let { contentEl } = this;
contentEl.empty();
const deleteDiv = contentEl.createDiv("delete-div");
deleteDiv.createEl("h4", { text: "Are you sure you want to delete the following database?" });
deleteDiv.createEl("h2", { text: this.dbDetails.fullName + " (" + this.dbDetails.abName + ", " + this.dbDetails.format + ")" });
let footerEl = contentEl.createDiv("save-button");
let deleteButton = new import_obsidian14.Setting(footerEl);
deleteButton.addButton((button) => {
return button.setTooltip("Delete").setIcon("trash").onClick(() => __async(this, null, function* () {
this.data.deleted = true;
this.close();
}));
});
deleteButton.addExtraButton((button) => {
return button.setTooltip("Cancel").setIcon("cross").onClick(() => {
this.data.deleted = false;
this.close();
});
});
}
onOpen() {
this.display();
}
};
// src/ui/settingTabs.ts
var DEFAULT_SETTINGS = {
NextButton: true,
notionAPINext: "",
databaseIDNext: "",
bannerUrl: "",
notionUser: "",
NotionLinkDisplay: true,
autoCopyNotionLink: true,
autoSync: false,
autoSyncDelay: 5,
autoSyncSuccessNotice: false,
autoSyncFrontmatterKey: DEFAULT_AUTO_SYNC_DATABASE_KEY,
proxy: "",
GeneralButton: true,
tagButton: true,
customTitleButton: false,
customTitleName: "",
notionAPIGeneral: "",
databaseIDGeneral: "",
CustomButton: false,
CustomValues: "",
notionAPICustom: "",
databaseIDCustom: "",
databaseDetails: {}
};
var ObsidianSettingTab = class extends import_obsidian15.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.autoSyncDelayContainer = null;
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: i18nConfig.GeneralSetting });
this.createSettingEl(containerEl, i18nConfig.BannerUrl, i18nConfig.BannerUrlDesc, "text", i18nConfig.BannerUrlText, this.plugin.settings.bannerUrl, "bannerUrl");
this.createSettingEl(containerEl, i18nConfig.NotionUser, i18nConfig.NotionUserDesc, "text", i18nConfig.NotionUserText, this.plugin.settings.notionUser, "notionUser");
this.createSettingEl(containerEl, i18nConfig.NotionLinkDisplay, i18nConfig.NotionLinkDisplayDesc, "toggle", i18nConfig.NotionLinkDisplay, this.plugin.settings.NotionLinkDisplay, "NotionLinkDisplay");
this.createSettingEl(containerEl, i18nConfig.AutoCopyNotionLink, i18nConfig.AutoCopyNotionLinkDesc, "toggle", i18nConfig.AutoCopyNotionLink, this.plugin.settings.autoCopyNotionLink, "autoCopyNotionLink");
this.createSettingEl(containerEl, i18nConfig.AutoSync, i18nConfig.AutoSyncDesc, "toggle", i18nConfig.AutoSync, this.plugin.settings.autoSync, "autoSync");
this.createSettingEl(
containerEl,
i18nConfig.AutoSyncSuccessNotice,
i18nConfig.AutoSyncSuccessNoticeDesc,
"toggle",
i18nConfig.AutoSyncSuccessNotice,
this.plugin.settings.autoSyncSuccessNotice,
"autoSyncSuccessNotice"
);
new import_obsidian15.Setting(containerEl).setName(i18nConfig.AutoSyncFrontmatterKey).setDesc(i18nConfig.AutoSyncFrontmatterKeyDesc).addText(
(text5) => {
var _a;
return text5.setPlaceholder(DEFAULT_AUTO_SYNC_DATABASE_KEY).setValue((_a = this.plugin.settings.autoSyncFrontmatterKey) != null ? _a : "").onChange((value) => __async(this, null, function* () {
this.plugin.settings.autoSyncFrontmatterKey = value;
yield this.plugin.saveSettings();
}));
}
);
this.autoSyncDelayContainer = containerEl.createDiv();
new import_obsidian15.Setting(this.autoSyncDelayContainer).setName(i18nConfig.AutoSyncDelay).setDesc(i18nConfig.AutoSyncDelayDesc).addText(
(text5) => text5.setPlaceholder(i18nConfig.AutoSyncDelayText).setValue(String(this.plugin.settings.autoSyncDelay)).onChange((value) => __async(this, null, function* () {
const delay = parseFloat(value);
if (!isNaN(delay) && delay >= 2) {
this.plugin.settings.autoSyncDelay = delay;
yield this.plugin.saveSettings();
} else if (!isNaN(delay) && delay < 2) {
this.plugin.settings.autoSyncDelay = 2;
yield this.plugin.saveSettings();
text5.setValue("2");
}
}))
);
this.updateAutoSyncDelayVisibility();
new import_obsidian15.Setting(containerEl).setName(i18nConfig.AddNewDatabase).setDesc(i18nConfig.AddNewDatabaseDesc).addButton((button) => {
return button.setTooltip(i18nConfig.AddNewDatabaseTooltip).setIcon("plus").onClick(() => __async(this, null, function* () {
let modal = new SettingModal(this.app, this.plugin, this);
modal.onClose = () => {
if (modal.data.saved) {
const dbDetails = {
format: modal.data.databaseFormat,
fullName: modal.data.databaseFullName,
abName: modal.data.databaseAbbreviateName,
notionAPI: modal.data.notionAPI,
databaseID: modal.data.databaseID,
tagButton: modal.data.tagButton,
customTitleButton: modal.data.customTitleButton,
customTitleName: modal.data.customTitleName,
customProperties: modal.data.customProperties,
// customValues: modal.data.customValues,
saved: modal.data.saved
};
this.plugin.addDatabaseDetails(dbDetails);
this.plugin.commands.updateCommand();
this.display();
}
};
modal.open();
}));
});
containerEl.createEl("h2", { text: "Database List" });
this.databaseEl = containerEl.createDiv("database-list");
this.showDatabase();
}
// create a function to create a div with a style for pop over elements
// public createStyleDiv(className: string, commandValue: boolean = false) {
// return this.containerEl.createDiv(className, (div) => {
// this.updateSettingEl(div, commandValue);
// });
// }
// update the setting display style in the setting tab
updateSettingEl(element2, commandValue) {
element2.style.borderTop = commandValue ? "1px solid var(--background-modifier-border)" : "none";
element2.style.paddingTop = commandValue ? "0.75em" : "0";
element2.style.display = commandValue ? "block" : "none";
element2.style.alignItems = "center";
}
// Update visibility of autoSyncDelay setting based on autoSync toggle
updateAutoSyncDelayVisibility() {
if (this.autoSyncDelayContainer) {
this.autoSyncDelayContainer.style.display = this.plugin.settings.autoSync ? "block" : "none";
}
}
// function to add one setting element in the setting tab.
createSettingEl(containerEl, name, desc, type, placeholder, holderValue, settingsKey) {
if (type === "password") {
return new import_obsidian15.Setting(containerEl).setName(name).setDesc(desc).addText((text5) => {
text5.inputEl.type = type;
return text5.setPlaceholder(placeholder).setValue(holderValue).onChange((value) => __async(this, null, function* () {
this.plugin.settings[settingsKey] = value;
yield this.plugin.saveSettings();
}));
});
} else if (type === "toggle") {
return new import_obsidian15.Setting(containerEl).setName(name).setDesc(desc).addToggle(
(toggle) => toggle.setValue(holderValue).onChange((value) => __async(this, null, function* () {
this.plugin.settings[settingsKey] = value;
yield this.plugin.saveSettings();
yield this.plugin.commands.updateCommand();
if (settingsKey === "autoSync") {
this.plugin.setupAutoSync();
this.updateAutoSyncDelayVisibility();
}
}))
);
} else if (type === "text") {
return new import_obsidian15.Setting(containerEl).setName(name).setDesc(desc).addText(
(text5) => text5.setPlaceholder(placeholder).setValue(holderValue).onChange((value) => __async(this, null, function* () {
this.plugin.settings[settingsKey] = value;
yield this.plugin.saveSettings();
yield this.plugin.commands.updateCommand();
}))
);
}
}
// function to show all the database details
showDatabase() {
this.databaseEl.empty();
for (let key in this.plugin.settings.databaseDetails) {
let dbDetails = this.plugin.settings.databaseDetails[key];
const databaseDiv = this.databaseEl.createDiv("database-div");
let settingEl = new import_obsidian15.Setting(databaseDiv).setName(`${dbDetails.fullName} (${dbDetails.abName})`).setDesc(dbDetails.format);
settingEl.addButton((button) => {
return button.setTooltip("Preview Database").setIcon("eye").onClick(() => __async(this, null, function* () {
let modal = new PreviewModal(this.app, this.plugin, this, dbDetails);
modal.open();
}));
});
settingEl.addButton((button) => {
return button.setTooltip("Edit Database").setIcon("pencil").onClick(() => __async(this, null, function* () {
let modal = new EditModal(this.app, this.plugin, this, dbDetails);
modal.onClose = () => {
if (modal.dataTemp.savedTempInd) {
const dbDetailsNew = {
format: modal.dataTemp.databaseFormatTemp,
fullName: modal.dataTemp.databaseFullNameTemp,
abName: modal.dataTemp.databaseAbbreviateNameTemp,
notionAPI: modal.dataTemp.notionAPITemp,
databaseID: modal.dataTemp.databaseIDTemp,
tagButton: modal.dataTemp.tagButtonTemp,
customTitleButton: modal.dataTemp.customTitleButtonTemp,
customTitleName: modal.dataTemp.customTitleNameTemp,
customProperties: modal.dataTemp.customPropertiesTemp,
// customValues: modal.data.customValues,
saved: modal.dataTemp.savedTemp
};
const dbDetailsPrev = {
format: modal.dataPrev.databaseFormatPrev,
fullName: modal.dataPrev.databaseFullNamePrev,
abName: modal.dataPrev.databaseAbbreviateNamePrev,
notionAPI: modal.dataPrev.notionAPIPrev,
databaseID: modal.dataPrev.databaseIDPrev,
tagButton: modal.dataPrev.tagButtonPrev,
customTitleButton: modal.dataPrev.customTitleButtonPrev,
customTitleName: modal.dataPrev.customTitleNamePrev,
customProperties: modal.dataPrev.customPropertiesPrev,
// customValues: modal.data.customValues,
saved: modal.dataPrev.savedPrev
};
this.plugin.deleteDatabaseDetails(dbDetailsPrev);
this.plugin.updateDatabaseDetails(dbDetailsNew);
this.plugin.commands.updateCommand();
this.display();
}
};
modal.open();
}));
});
settingEl.addButton((button) => {
return button.setTooltip("Delete Database").setIcon("trash").onClick(() => __async(this, null, function* () {
let modal = new DeleteModal(this.app, this.plugin, this, dbDetails);
modal.onClose = () => {
if (modal.data.deleted) {
this.plugin.deleteDatabaseDetails(dbDetails);
console.log(dbDetails.fullName + " deleted");
this.plugin.commands.updateCommand();
this.display();
}
};
modal.open();
}));
});
}
}
};
// src/main.ts
var ObsidianSyncNotionPlugin = class extends import_obsidian16.Plugin {
constructor() {
super(...arguments);
this.modifyEventRef = null;
this.autoSyncTimeout = null;
this.syncingFiles = /* @__PURE__ */ new Set();
this.lastFrontmatterCache = /* @__PURE__ */ new Map();
this.lastContentHashCache = /* @__PURE__ */ new Map();
this.autoSyncAttachmentBlocked = /* @__PURE__ */ new Set();
}
onload() {
return __async(this, null, function* () {
yield this.loadSettings();
console.log("[Plugin] Loaded settings:", {
autoSync: this.settings.autoSync,
autoSyncDelay: this.settings.autoSyncDelay,
NotionLinkDisplay: this.settings.NotionLinkDisplay,
bannerUrl: this.settings.bannerUrl ? "set" : "empty",
notionUser: this.settings.notionUser ? "set" : "empty",
databaseCount: Object.keys(this.settings.databaseDetails || {}).length
});
this.commands = new RibbonCommands(this);
addIcons();
this.addRibbonIcon(
"notion-logo",
i18nConfig.ribbonIcon,
(evt) => __async(this, null, function* () {
yield this.commands.ribbonDisplay();
})
);
this.addSettingTab(new ObsidianSettingTab(this.app, this));
this.setupAutoSync();
});
}
onunload() {
if (this.modifyEventRef) {
this.app.vault.offref(this.modifyEventRef);
}
if (this.autoSyncTimeout) {
clearTimeout(this.autoSyncTimeout);
}
this.lastFrontmatterCache.clear();
this.lastContentHashCache.clear();
this.autoSyncAttachmentBlocked.clear();
}
loadSettings() {
return __async(this, null, function* () {
const loadedData = yield this.loadData();
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
loadedData || {}
);
if (typeof this.settings.autoSync !== "boolean") {
this.settings.autoSync = DEFAULT_SETTINGS.autoSync;
}
if (typeof this.settings.autoSyncDelay !== "number" || this.settings.autoSyncDelay < 2) {
this.settings.autoSyncDelay = DEFAULT_SETTINGS.autoSyncDelay;
}
if (typeof this.settings.autoSyncSuccessNotice !== "boolean") {
this.settings.autoSyncSuccessNotice = DEFAULT_SETTINGS.autoSyncSuccessNotice;
}
if (typeof this.settings.NotionLinkDisplay !== "boolean") {
this.settings.NotionLinkDisplay = DEFAULT_SETTINGS.NotionLinkDisplay;
}
if (typeof this.settings.autoCopyNotionLink !== "boolean") {
this.settings.autoCopyNotionLink = DEFAULT_SETTINGS.autoCopyNotionLink;
}
if (typeof this.settings.autoSyncFrontmatterKey !== "string") {
this.settings.autoSyncFrontmatterKey = DEFAULT_AUTO_SYNC_DATABASE_KEY;
}
this.settings.autoSyncFrontmatterKey = resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
if (!this.settings.databaseDetails || typeof this.settings.databaseDetails !== "object") {
this.settings.databaseDetails = {};
}
const needsSave = !loadedData || loadedData.autoSync === void 0 || loadedData.autoSyncDelay === void 0 || loadedData.autoSyncSuccessNotice === void 0 || loadedData.NotionLinkDisplay === void 0 || loadedData.autoCopyNotionLink === void 0 || loadedData.autoSyncFrontmatterKey === void 0;
if (needsSave) {
const migratedFields = [];
if (!loadedData) {
console.log("[Settings] First-time setup, creating default settings");
} else {
if (loadedData.autoSync === void 0)
migratedFields.push("autoSync");
if (loadedData.autoSyncDelay === void 0)
migratedFields.push("autoSyncDelay");
if (loadedData.autoSyncSuccessNotice === void 0)
migratedFields.push("autoSyncSuccessNotice");
if (loadedData.NotionLinkDisplay === void 0)
migratedFields.push("NotionLinkDisplay");
if (loadedData.autoCopyNotionLink === void 0)
migratedFields.push("autoCopyNotionLink");
console.log("[Settings] Migrating settings, adding fields:", migratedFields.join(", "));
}
yield this.saveSettings();
if (loadedData && Object.keys(loadedData).length > 0 && migratedFields.length > 0) {
new import_obsidian16.Notice(i18nConfig.SettingsMigrated, 6e3);
console.log("[Settings] Migration notice shown to user");
}
}
});
}
saveSettings() {
return __async(this, null, function* () {
this.validateSettings();
yield this.saveData(this.settings);
console.log("[Settings] Settings saved successfully", {
autoSync: this.settings.autoSync,
autoSyncDelay: this.settings.autoSyncDelay,
autoSyncSuccessNotice: this.settings.autoSyncSuccessNotice,
NotionLinkDisplay: this.settings.NotionLinkDisplay,
autoSyncFrontmatterKey: this.settings.autoSyncFrontmatterKey,
databaseCount: Object.keys(this.settings.databaseDetails || {}).length
});
});
}
validateSettings() {
if (typeof this.settings.autoSync !== "boolean") {
console.warn("[Settings] Invalid autoSync value, resetting to default");
this.settings.autoSync = DEFAULT_SETTINGS.autoSync;
}
if (typeof this.settings.autoSyncDelay !== "number" || this.settings.autoSyncDelay < 2) {
console.warn("[Settings] Invalid autoSyncDelay value, resetting to default");
this.settings.autoSyncDelay = DEFAULT_SETTINGS.autoSyncDelay;
}
if (typeof this.settings.autoSyncSuccessNotice !== "boolean") {
console.warn("[Settings] Invalid autoSyncSuccessNotice value, resetting to default");
this.settings.autoSyncSuccessNotice = DEFAULT_SETTINGS.autoSyncSuccessNotice;
}
if (typeof this.settings.NotionLinkDisplay !== "boolean") {
console.warn("[Settings] Invalid NotionLinkDisplay value, resetting to default");
this.settings.NotionLinkDisplay = DEFAULT_SETTINGS.NotionLinkDisplay;
}
if (typeof this.settings.autoCopyNotionLink !== "boolean") {
console.warn("[Settings] Invalid autoCopyNotionLink value, resetting to default");
this.settings.autoCopyNotionLink = DEFAULT_SETTINGS.autoCopyNotionLink;
}
if (!this.settings.databaseDetails || typeof this.settings.databaseDetails !== "object") {
console.warn("[Settings] Invalid databaseDetails, resetting to empty object");
this.settings.databaseDetails = {};
}
if (typeof this.settings.autoSyncFrontmatterKey !== "string" || this.settings.autoSyncFrontmatterKey.trim().length === 0) {
console.warn("[Settings] Invalid autoSyncFrontmatterKey, resetting to default");
this.settings.autoSyncFrontmatterKey = DEFAULT_AUTO_SYNC_DATABASE_KEY;
} else {
this.settings.autoSyncFrontmatterKey = resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
}
}
getAutoSyncFrontmatterKey() {
return resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
}
addDatabaseDetails(dbDetails) {
return __async(this, null, function* () {
this.settings.databaseDetails = __spreadProps(__spreadValues({}, this.settings.databaseDetails), {
[dbDetails.abName]: dbDetails
});
yield this.saveSettings();
});
}
deleteDatabaseDetails(dbDetails) {
return __async(this, null, function* () {
delete this.settings.databaseDetails[dbDetails.abName];
yield this.saveSettings();
});
}
updateDatabaseDetails(dbDetails) {
return __async(this, null, function* () {
delete this.settings.databaseDetails[dbDetails.abName];
this.settings.databaseDetails = __spreadProps(__spreadValues({}, this.settings.databaseDetails), {
[dbDetails.abName]: dbDetails
});
yield this.saveSettings();
});
}
setupAutoSync() {
if (this.modifyEventRef) {
this.app.vault.offref(this.modifyEventRef);
}
if (!this.settings.autoSync) {
return;
}
this.modifyEventRef = this.app.vault.on("modify", (file) => __async(this, null, function* () {
if (!(file instanceof import_obsidian16.TFile) || file.extension !== "md") {
return;
}
if (this.autoSyncTimeout) {
clearTimeout(this.autoSyncTimeout);
}
const delayMs = (this.settings.autoSyncDelay || 2) * 1e3;
this.autoSyncTimeout = window.setTimeout(() => __async(this, null, function* () {
yield this.autoSyncFile(file);
}), delayMs);
}));
}
onlyNotionIDChanged(oldFrontmatter, newFrontmatter) {
const oldKeys = Object.keys(oldFrontmatter || {});
const newKeys = Object.keys(newFrontmatter || {});
const isIgnoredKey = (key) => {
return key.startsWith("NotionID-") || key === "NotionID" || key === "position";
};
const oldNonNotionKeys = oldKeys.filter((k) => !isIgnoredKey(k)).sort();
const newNonNotionKeys = newKeys.filter((k) => !isIgnoredKey(k)).sort();
if (oldNonNotionKeys.length !== newNonNotionKeys.length) {
console.log("[AutoSync] Frontmatter: Key count changed:", oldNonNotionKeys.length, "->", newNonNotionKeys.length);
return false;
}
for (const key of oldNonNotionKeys) {
if (!newNonNotionKeys.includes(key)) {
console.log("[AutoSync] Frontmatter: Key removed or added:", key);
return false;
}
const oldValue = JSON.stringify(oldFrontmatter[key]);
const newValue = JSON.stringify(newFrontmatter[key]);
if (oldValue !== newValue) {
console.log('[AutoSync] Frontmatter: Value changed for key "' + key + '"');
console.log(" Old:", oldValue.substring(0, 100));
console.log(" New:", newValue.substring(0, 100));
return false;
}
}
for (const key of newNonNotionKeys) {
if (!oldNonNotionKeys.includes(key)) {
console.log("[AutoSync] Frontmatter: New key added:", key);
return false;
}
}
return true;
}
simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash;
}
return hash.toString();
}
autoSyncFile(file) {
return __async(this, null, function* () {
var _a;
if (this.syncingFiles.has(file.path)) {
console.log(`[AutoSync] File ${file.path} is already being synced, skipping`);
return;
}
try {
this.syncingFiles.add(file.path);
const frontMatter = (_a = this.app.metadataCache.getFileCache(file)) == null ? void 0 : _a.frontmatter;
if (!frontMatter) {
return;
}
const autoSyncKey = this.getAutoSyncFrontmatterKey();
const autoSyncTargets = parseAutoSyncDatabaseList(frontMatter[autoSyncKey]);
if (autoSyncTargets.length === 0) {
return;
}
const content3 = yield this.app.vault.read(file);
const contentHash = this.simpleHash(content3);
const lastContentHash = this.lastContentHashCache.get(file.path);
const lastFrontmatter = this.lastFrontmatterCache.get(file.path);
if (lastFrontmatter && lastContentHash) {
const frontmatterOnlyNotionIDChanged = this.onlyNotionIDChanged(lastFrontmatter, frontMatter);
const contentUnchanged = contentHash === lastContentHash;
if (frontmatterOnlyNotionIDChanged && contentUnchanged) {
this.lastFrontmatterCache.set(file.path, __spreadValues({}, frontMatter));
this.lastContentHashCache.set(file.path, contentHash);
return;
}
}
const dbByShortName = /* @__PURE__ */ new Map();
for (const key in this.settings.databaseDetails) {
const dbDetails = this.settings.databaseDetails[key];
dbByShortName.set(dbDetails.abName.toLowerCase(), dbDetails);
}
const foundDatabases = [];
const unresolvedTargets = [];
for (const target of autoSyncTargets) {
const lookupKey = target.toLowerCase();
const dbDetails = dbByShortName.get(lookupKey);
if (!dbDetails) {
unresolvedTargets.push(target);
continue;
}
const notionIDKey = `NotionID-${dbDetails.abName}`;
foundDatabases.push({
dbDetails,
notionId: frontMatter[notionIDKey] ? String(frontMatter[notionIDKey]) : void 0
});
}
if (unresolvedTargets.length > 0) {
console.log(`[AutoSync] Frontmatter auto sync targets not found in settings: ${unresolvedTargets.join(", ")}`);
}
if (foundDatabases.length === 0) {
console.log(`[AutoSync] No matching databases found in settings for ${file.path}, skipping auto sync`);
return;
}
const attachmentProcessor = new AttachmentProcessor(this, foundDatabases[0].dbDetails);
if (attachmentProcessor.hasInternalAttachments(content3, file)) {
if (!this.autoSyncAttachmentBlocked.has(file.path)) {
const message = i18nConfig.AutoSyncSkippedAttachments.replace("{filename}", file.basename);
new import_obsidian16.Notice(message, 6e3);
this.autoSyncAttachmentBlocked.add(file.path);
}
console.log(`[AutoSync] Internal attachments detected in ${file.path}, auto-sync skipped`);
return;
}
this.autoSyncAttachmentBlocked.delete(file.path);
if (foundDatabases.length > 1) {
const message = i18nConfig.AutoSyncMultipleSync.replace("{count}", String(foundDatabases.length));
new import_obsidian16.Notice(message, 3e3);
console.log(`[AutoSync] Found ${foundDatabases.length} database targets in ${file.path}`);
}
for (const { dbDetails, notionId } of foundDatabases) {
const isFirstSync = !notionId;
console.log(`[AutoSync] ${(/* @__PURE__ */ new Date()).toISOString()} Auto syncing ${file.basename} to ${dbDetails.fullName} (${dbDetails.abName})${isFirstSync ? " [First Upload]" : ""}`);
try {
if (dbDetails.format === "next") {
yield uploadCommandNext(this, this.settings, dbDetails, this.app, { isAutoSync: true });
} else if (dbDetails.format === "general") {
yield uploadCommandGeneral(this, this.settings, dbDetails, this.app, { isAutoSync: true });
} else if (dbDetails.format === "custom") {
yield uploadCommandCustom(this, this.settings, dbDetails, this.app, { isAutoSync: true });
}
} catch (error) {
console.error(`[AutoSync] Error syncing to ${dbDetails.fullName}:`, error);
const message = i18nConfig.AutoSyncFailed.replace("{database}", dbDetails.fullName).replace("{error}", error.message);
new import_obsidian16.Notice(message, 5e3);
}
}
window.setTimeout(() => __async(this, null, function* () {
var _a2;
const updatedFrontmatter = (_a2 = this.app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.frontmatter;
const updatedContent = yield this.app.vault.read(file);
const updatedHash = this.simpleHash(updatedContent);
if (updatedFrontmatter) {
this.lastFrontmatterCache.set(file.path, __spreadValues({}, updatedFrontmatter));
this.lastContentHashCache.set(file.path, updatedHash);
console.log(`[AutoSync] Cached updated frontmatter and content hash for ${file.path}`);
}
}), 500);
} catch (error) {
console.error(`[AutoSync] Error syncing file ${file.path}:`, error);
const message = i18nConfig.AutoSyncError.replace("{filename}", file.basename).replace("{error}", error.message);
new import_obsidian16.Notice(message);
} finally {
this.syncingFiles.delete(file.path);
}
});
}
};
/* nosourcemap */