block — the same encoding as the tool list at the top of this prompt.
Query forms:
- "select:Read,Edit,Grep" — fetch these exact tools by name
- "notebook jupyter" — keyword search, up to max_results best matches
- "+slack send" — require "slack" in the name, rank by remaining terms`;
var init_prompt7 = __esm(() => {
init_state();
init_growthbook();
init_constants3();
});
// src/tools/PowerShellTool/toolName.ts
var POWERSHELL_TOOL_NAME = "PowerShell";
// src/utils/shell/shellToolUtils.ts
function isPowerShellToolEnabled() {
if (getPlatform() !== "windows")
return false;
return process.env.USER_TYPE === "ant" ? !isEnvDefinedFalsy(process.env.CLAUDE_CODE_USE_POWERSHELL_TOOL) : isEnvTruthy(process.env.CLAUDE_CODE_USE_POWERSHELL_TOOL);
}
var SHELL_TOOL_NAMES;
var init_shellToolUtils = __esm(() => {
init_envUtils();
init_platform2();
SHELL_TOOL_NAMES = [BASH_TOOL_NAME, POWERSHELL_TOOL_NAME];
});
// node_modules/.pnpm/diff@8.0.4/node_modules/diff/libesm/diff/base.js
class Diff {
diff(oldStr, newStr, options = {}) {
let callback;
if (typeof options === "function") {
callback = options;
options = {};
} else if ("callback" in options) {
callback = options.callback;
}
const oldString = this.castInput(oldStr, options);
const newString = this.castInput(newStr, options);
const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
const newTokens = this.removeEmpty(this.tokenize(newString, options));
return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
}
diffWithOptionsObj(oldTokens, newTokens, options, callback) {
var _a4;
const done = (value) => {
value = this.postProcess(value, options);
if (callback) {
setTimeout(function() {
callback(value);
}, 0);
return;
} else {
return value;
}
};
const newLen = newTokens.length, oldLen = oldTokens.length;
let editLength = 1;
let maxEditLength = newLen + oldLen;
if (options.maxEditLength != null) {
maxEditLength = Math.min(maxEditLength, options.maxEditLength);
}
const maxExecutionTime = (_a4 = options.timeout) !== null && _a4 !== undefined ? _a4 : Infinity;
const abortAfterTimestamp = Date.now() + maxExecutionTime;
const bestPath = [{ oldPos: -1, lastComponent: undefined }];
let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
}
let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
const execEditLength = () => {
for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength);diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
let basePath;
const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
if (removePath) {
bestPath[diagonalPath - 1] = undefined;
}
let canAdd = false;
if (addPath) {
const addPathNewPos = addPath.oldPos - diagonalPath;
canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
}
const canRemove = removePath && removePath.oldPos + 1 < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
basePath = this.addToPath(addPath, true, false, 0, options);
} else {
basePath = this.addToPath(removePath, false, true, 1, options);
}
newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
} else {
bestPath[diagonalPath] = basePath;
if (basePath.oldPos + 1 >= oldLen) {
maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
}
if (newPos + 1 >= newLen) {
minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
}
}
}
editLength++;
};
if (callback) {
(function exec3() {
setTimeout(function() {
if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
return callback(undefined);
}
if (!execEditLength()) {
exec3();
}
}, 0);
})();
} else {
while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
const ret = execEditLength();
if (ret) {
return ret;
}
}
}
}
addToPath(path14, added, removed, oldPosInc, options) {
const last2 = path14.lastComponent;
if (last2 && !options.oneChangePerToken && last2.added === added && last2.removed === removed) {
return {
oldPos: path14.oldPos + oldPosInc,
lastComponent: { count: last2.count + 1, added, removed, previousComponent: last2.previousComponent }
};
} else {
return {
oldPos: path14.oldPos + oldPosInc,
lastComponent: { count: 1, added, removed, previousComponent: last2 }
};
}
}
extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
const newLen = newTokens.length, oldLen = oldTokens.length;
let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
newPos++;
oldPos++;
commonCount++;
if (options.oneChangePerToken) {
basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
}
}
if (commonCount && !options.oneChangePerToken) {
basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
}
basePath.oldPos = oldPos;
return newPos;
}
equals(left, right, options) {
if (options.comparator) {
return options.comparator(left, right);
} else {
return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
}
}
removeEmpty(array2) {
const ret = [];
for (let i4 = 0;i4 < array2.length; i4++) {
if (array2[i4]) {
ret.push(array2[i4]);
}
}
return ret;
}
castInput(value, options) {
return value;
}
tokenize(value, options) {
return Array.from(value);
}
join(chars) {
return chars.join("");
}
postProcess(changeObjects, options) {
return changeObjects;
}
get useLongestToken() {
return false;
}
buildValues(lastComponent, newTokens, oldTokens) {
const components = [];
let nextComponent;
while (lastComponent) {
components.push(lastComponent);
nextComponent = lastComponent.previousComponent;
delete lastComponent.previousComponent;
lastComponent = nextComponent;
}
components.reverse();
const componentLen = components.length;
let componentPos = 0, newPos = 0, oldPos = 0;
for (;componentPos < componentLen; componentPos++) {
const component = components[componentPos];
if (!component.removed) {
if (!component.added && this.useLongestToken) {
let value = newTokens.slice(newPos, newPos + component.count);
value = value.map(function(value2, i4) {
const oldValue = oldTokens[oldPos + i4];
return oldValue.length > value2.length ? oldValue : value2;
});
component.value = this.join(value);
} else {
component.value = this.join(newTokens.slice(newPos, newPos + component.count));
}
newPos += component.count;
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
oldPos += component.count;
}
}
return components;
}
}
// node_modules/.pnpm/diff@8.0.4/node_modules/diff/libesm/util/string.js
function longestCommonPrefix(str1, str2) {
let i4;
for (i4 = 0;i4 < str1.length && i4 < str2.length; i4++) {
if (str1[i4] != str2[i4]) {
return str1.slice(0, i4);
}
}
return str1.slice(0, i4);
}
function longestCommonSuffix(str1, str2) {
let i4;
if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
return "";
}
for (i4 = 0;i4 < str1.length && i4 < str2.length; i4++) {
if (str1[str1.length - (i4 + 1)] != str2[str2.length - (i4 + 1)]) {
return str1.slice(-i4);
}
}
return str1.slice(-i4);
}
function replacePrefix(string4, oldPrefix, newPrefix) {
if (string4.slice(0, oldPrefix.length) != oldPrefix) {
throw Error(`string ${JSON.stringify(string4)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);
}
return newPrefix + string4.slice(oldPrefix.length);
}
function replaceSuffix(string4, oldSuffix, newSuffix) {
if (!oldSuffix) {
return string4 + newSuffix;
}
if (string4.slice(-oldSuffix.length) != oldSuffix) {
throw Error(`string ${JSON.stringify(string4)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);
}
return string4.slice(0, -oldSuffix.length) + newSuffix;
}
function removePrefix(string4, oldPrefix) {
return replacePrefix(string4, oldPrefix, "");
}
function removeSuffix(string4, oldSuffix) {
return replaceSuffix(string4, oldSuffix, "");
}
function maximumOverlap(string1, string22) {
return string22.slice(0, overlapCount(string1, string22));
}
function overlapCount(a2, b) {
let startA = 0;
if (a2.length > b.length) {
startA = a2.length - b.length;
}
let endB = b.length;
if (a2.length < b.length) {
endB = a2.length;
}
const map3 = Array(endB);
let k = 0;
map3[0] = 0;
for (let j = 1;j < endB; j++) {
if (b[j] == b[k]) {
map3[j] = map3[k];
} else {
map3[j] = k;
}
while (k > 0 && b[j] != b[k]) {
k = map3[k];
}
if (b[j] == b[k]) {
k++;
}
}
k = 0;
for (let i4 = startA;i4 < a2.length; i4++) {
while (k > 0 && a2[i4] != b[k]) {
k = map3[k];
}
if (a2[i4] == b[k]) {
k++;
}
}
return k;
}
function segment(string4, segmenter4) {
const parts = [];
for (const segmentObj of Array.from(segmenter4.segment(string4))) {
const segment2 = segmentObj.segment;
if (parts.length && /\s/.test(parts[parts.length - 1]) && /\s/.test(segment2)) {
parts[parts.length - 1] += segment2;
} else {
parts.push(segment2);
}
}
return parts;
}
function trailingWs(string4, segmenter4) {
if (segmenter4) {
return leadingAndTrailingWs(string4, segmenter4)[1];
}
let i4;
for (i4 = string4.length - 1;i4 >= 0; i4--) {
if (!string4[i4].match(/\s/)) {
break;
}
}
return string4.substring(i4 + 1);
}
function leadingWs(string4, segmenter4) {
if (segmenter4) {
return leadingAndTrailingWs(string4, segmenter4)[0];
}
const match = string4.match(/^\s*/);
return match ? match[0] : "";
}
function leadingAndTrailingWs(string4, segmenter4) {
if (!segmenter4) {
return [leadingWs(string4), trailingWs(string4)];
}
if (segmenter4.resolvedOptions().granularity != "word") {
throw new Error('The segmenter passed must have a granularity of "word"');
}
const segments = segment(string4, segmenter4);
const firstSeg = segments[0];
const lastSeg = segments[segments.length - 1];
const head = /\s/.test(firstSeg) ? firstSeg : "";
const tail = /\s/.test(lastSeg) ? lastSeg : "";
return [head, tail];
}
// node_modules/.pnpm/diff@8.0.4/node_modules/diff/libesm/diff/word.js
function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep, segmenter4) {
if (deletion && insertion) {
const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter4);
const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter4);
if (startKeep) {
const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);
startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);
deletion.value = removePrefix(deletion.value, commonWsPrefix);
insertion.value = removePrefix(insertion.value, commonWsPrefix);
}
if (endKeep) {
const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);
endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);
deletion.value = removeSuffix(deletion.value, commonWsSuffix);
insertion.value = removeSuffix(insertion.value, commonWsSuffix);
}
} else if (insertion) {
if (startKeep) {
const ws = leadingWs(insertion.value, segmenter4);
insertion.value = insertion.value.substring(ws.length);
}
if (endKeep) {
const ws = leadingWs(endKeep.value, segmenter4);
endKeep.value = endKeep.value.substring(ws.length);
}
} else if (startKeep && endKeep) {
const newWsFull = leadingWs(endKeep.value, segmenter4), [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion.value, segmenter4);
const newWsStart = longestCommonPrefix(newWsFull, delWsStart);
deletion.value = removePrefix(deletion.value, newWsStart);
const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);
deletion.value = removeSuffix(deletion.value, newWsEnd);
endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);
startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));
} else if (endKeep) {
const endKeepWsPrefix = leadingWs(endKeep.value, segmenter4);
const deletionWsSuffix = trailingWs(deletion.value, segmenter4);
const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
deletion.value = removeSuffix(deletion.value, overlap);
} else if (startKeep) {
const startKeepWsSuffix = trailingWs(startKeep.value, segmenter4);
const deletionWsPrefix = leadingWs(deletion.value, segmenter4);
const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);
deletion.value = removePrefix(deletion.value, overlap);
}
}
function diffWordsWithSpace(oldStr, newStr, options) {
return wordsWithSpaceDiff.diff(oldStr, newStr, options);
}
var extendedWordChars = "a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}", tokenizeIncludingWhitespace, WordDiff, wordDiff, WordsWithSpaceDiff, wordsWithSpaceDiff;
var init_word = __esm(() => {
tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, "ug");
WordDiff = class WordDiff extends Diff {
equals(left, right, options) {
if (options.ignoreCase) {
left = left.toLowerCase();
right = right.toLowerCase();
}
return left.trim() === right.trim();
}
tokenize(value, options = {}) {
let parts;
if (options.intlSegmenter) {
const segmenter4 = options.intlSegmenter;
if (segmenter4.resolvedOptions().granularity != "word") {
throw new Error('The segmenter passed must have a granularity of "word"');
}
parts = segment(value, segmenter4);
} else {
parts = value.match(tokenizeIncludingWhitespace) || [];
}
const tokens = [];
let prevPart = null;
parts.forEach((part) => {
if (/\s/.test(part)) {
if (prevPart == null) {
tokens.push(part);
} else {
tokens.push(tokens.pop() + part);
}
} else if (prevPart != null && /\s/.test(prevPart)) {
if (tokens[tokens.length - 1] == prevPart) {
tokens.push(tokens.pop() + part);
} else {
tokens.push(prevPart + part);
}
} else {
tokens.push(part);
}
prevPart = part;
});
return tokens;
}
join(tokens) {
return tokens.map((token, i4) => {
if (i4 == 0) {
return token;
} else {
return token.replace(/^\s+/, "");
}
}).join("");
}
postProcess(changes, options) {
if (!changes || options.oneChangePerToken) {
return changes;
}
let lastKeep = null;
let insertion = null;
let deletion = null;
changes.forEach((change) => {
if (change.added) {
insertion = change;
} else if (change.removed) {
deletion = change;
} else {
if (insertion || deletion) {
dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change, options.intlSegmenter);
}
lastKeep = change;
insertion = null;
deletion = null;
}
});
if (insertion || deletion) {
dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter);
}
return changes;
}
};
wordDiff = new WordDiff;
WordsWithSpaceDiff = class WordsWithSpaceDiff extends Diff {
tokenize(value) {
const regex2 = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, "ug");
return value.match(regex2) || [];
}
};
wordsWithSpaceDiff = new WordsWithSpaceDiff;
});
// node_modules/.pnpm/diff@8.0.4/node_modules/diff/libesm/diff/line.js
function diffLines(oldStr, newStr, options) {
return lineDiff.diff(oldStr, newStr, options);
}
function tokenize5(value, options) {
if (options.stripTrailingCr) {
value = value.replace(/\r\n/g, `
`);
}
const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
for (let i4 = 0;i4 < linesAndNewlines.length; i4++) {
const line = linesAndNewlines[i4];
if (i4 % 2 && !options.newlineIsToken) {
retLines[retLines.length - 1] += line;
} else {
retLines.push(line);
}
}
return retLines;
}
var LineDiff, lineDiff;
var init_line2 = __esm(() => {
LineDiff = class LineDiff extends Diff {
constructor() {
super(...arguments);
this.tokenize = tokenize5;
}
equals(left, right, options) {
if (options.ignoreWhitespace) {
if (!options.newlineIsToken || !left.includes(`
`)) {
left = left.trim();
}
if (!options.newlineIsToken || !right.includes(`
`)) {
right = right.trim();
}
} else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
if (left.endsWith(`
`)) {
left = left.slice(0, -1);
}
if (right.endsWith(`
`)) {
right = right.slice(0, -1);
}
}
return super.equals(left, right, options);
}
};
lineDiff = new LineDiff;
});
// node_modules/.pnpm/diff@8.0.4/node_modules/diff/libesm/patch/create.js
function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
let optionsObj;
if (!options) {
optionsObj = {};
} else if (typeof options === "function") {
optionsObj = { callback: options };
} else {
optionsObj = options;
}
if (typeof optionsObj.context === "undefined") {
optionsObj.context = 4;
}
const context3 = optionsObj.context;
if (optionsObj.newlineIsToken) {
throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
}
if (!optionsObj.callback) {
return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
} else {
const { callback } = optionsObj;
diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff2) => {
const patch = diffLinesResultToPatch(diff2);
callback(patch);
} }));
}
function diffLinesResultToPatch(diff2) {
if (!diff2) {
return;
}
diff2.push({ value: "", lines: [] });
function contextLines(lines) {
return lines.map(function(entry) {
return " " + entry;
});
}
const hunks = [];
let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
for (let i4 = 0;i4 < diff2.length; i4++) {
const current = diff2[i4], lines = current.lines || splitLines(current.value);
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
const prev = diff2[i4 - 1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = context3 > 0 ? contextLines(prev.lines.slice(-context3)) : [];
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
for (const line of lines) {
curRange.push((current.added ? "+" : "-") + line);
}
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
if (lines.length <= context3 * 2 && i4 < diff2.length - 2) {
for (const line of contextLines(lines)) {
curRange.push(line);
}
} else {
const contextSize = Math.min(lines.length, context3);
for (const line of contextLines(lines.slice(0, contextSize))) {
curRange.push(line);
}
const hunk = {
oldStart: oldRangeStart,
oldLines: oldLine - oldRangeStart + contextSize,
newStart: newRangeStart,
newLines: newLine - newRangeStart + contextSize,
lines: curRange
};
hunks.push(hunk);
oldRangeStart = 0;
newRangeStart = 0;
curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
for (const hunk of hunks) {
for (let i4 = 0;i4 < hunk.lines.length; i4++) {
if (hunk.lines[i4].endsWith(`
`)) {
hunk.lines[i4] = hunk.lines[i4].slice(0, -1);
} else {
hunk.lines.splice(i4 + 1, 0, "\\ No newline at end of file");
i4++;
}
}
}
return {
oldFileName,
newFileName,
oldHeader,
newHeader,
hunks
};
}
}
function splitLines(text) {
const hasTrailingNl = text.endsWith(`
`);
const result = text.split(`
`).map((line) => line + `
`);
if (hasTrailingNl) {
result.pop();
} else {
result.push(result.pop().slice(0, -1));
}
return result;
}
var init_create2 = __esm(() => {
init_line2();
});
// node_modules/.pnpm/diff@8.0.4/node_modules/diff/libesm/index.js
var init_libesm = __esm(() => {
init_word();
init_line2();
init_create2();
});
// src/services/api/promptCacheBreakDetection.ts
function resetPromptCacheBreakDetection() {
previousStateBySource.clear();
}
var previousStateBySource, CACHE_TTL_5MIN_MS, CACHE_TTL_1HOUR_MS;
var init_promptCacheBreakDetection = __esm(() => {
init_debug();
init_log3();
init_filesystem();
init_slowOperations();
init_analytics();
previousStateBySource = new Map;
CACHE_TTL_5MIN_MS = 5 * 60 * 1000;
CACHE_TTL_1HOUR_MS = 60 * 60 * 1000;
});
// src/services/compact/compactWarningState.ts
function suppressCompactWarning() {
compactWarningStore.setState(() => true);
}
function clearCompactWarningSuppression() {
compactWarningStore.setState(() => false);
}
var compactWarningStore;
var init_compactWarningState = __esm(() => {
compactWarningStore = createStore(false);
});
// src/services/compact/timeBasedMCConfig.ts
function getTimeBasedMCConfig() {
return getFeatureValue_CACHED_MAY_BE_STALE("tengu_slate_heron", TIME_BASED_MC_CONFIG_DEFAULTS);
}
var TIME_BASED_MC_CONFIG_DEFAULTS;
var init_timeBasedMCConfig = __esm(() => {
init_growthbook();
TIME_BASED_MC_CONFIG_DEFAULTS = {
enabled: false,
gapThresholdMinutes: 60,
keepRecent: 5
};
});
// src/services/compact/microCompact.ts
function consumePendingCacheEdits() {
const edits = pendingCacheEdits;
pendingCacheEdits = null;
return edits;
}
function getPinnedCacheEdits() {
if (!cachedMCState) {
return [];
}
return cachedMCState.pinnedEdits;
}
function pinCacheEdits(userMessageIndex, block) {
if (cachedMCState) {
cachedMCState.pinnedEdits.push({ userMessageIndex, block });
}
}
function resetMicrocompactState() {
if (cachedMCState && cachedMCModule) {
cachedMCModule.resetCachedMCState(cachedMCState);
}
pendingCacheEdits = null;
}
function calculateToolResultTokens(block) {
if (!block.content) {
return 0;
}
if (typeof block.content === "string") {
return roughTokenCountEstimation(block.content);
}
return block.content.reduce((sum, item) => {
if (item.type === "text") {
return sum + roughTokenCountEstimation(item.text);
} else if (item.type === "image" || item.type === "document") {
return sum + IMAGE_MAX_TOKEN_SIZE;
}
return sum;
}, 0);
}
function estimateMessageTokens(messages) {
let totalTokens = 0;
for (const message of messages) {
if (message.type !== "user" && message.type !== "assistant") {
continue;
}
if (!Array.isArray(message.message.content)) {
continue;
}
for (const block of message.message.content) {
if (block.type === "text") {
totalTokens += roughTokenCountEstimation(block.text);
} else if (block.type === "tool_result") {
totalTokens += calculateToolResultTokens(block);
} else if (block.type === "image" || block.type === "document") {
totalTokens += IMAGE_MAX_TOKEN_SIZE;
} else if (block.type === "thinking") {
totalTokens += roughTokenCountEstimation(block.thinking);
} else if (block.type === "redacted_thinking") {
totalTokens += roughTokenCountEstimation(block.data);
} else if (block.type === "tool_use") {
totalTokens += roughTokenCountEstimation(block.name + jsonStringify(block.input ?? {}));
} else {
totalTokens += roughTokenCountEstimation(jsonStringify(block));
}
}
}
return Math.ceil(totalTokens * 1.3333333333333333);
}
function collectCompactableToolIds(messages) {
const ids = [];
for (const message of messages) {
if (message.type === "assistant" && Array.isArray(message.message.content)) {
for (const block of message.message.content) {
if (block.type === "tool_use" && COMPACTABLE_TOOLS.has(block.name)) {
ids.push(block.id);
}
}
}
}
return ids;
}
function isMainThreadSource(querySource) {
return !querySource || querySource.startsWith("repl_main_thread");
}
async function microcompactMessages(messages, toolUseContext, querySource) {
clearCompactWarningSuppression();
const timeBasedResult = maybeTimeBasedMicrocompact(messages, querySource);
if (timeBasedResult) {
return timeBasedResult;
}
if (false) {}
return { messages };
}
function evaluateTimeBasedTrigger(messages, querySource) {
const config2 = getTimeBasedMCConfig();
if (!config2.enabled || !querySource || !isMainThreadSource(querySource)) {
return null;
}
const lastAssistant = messages.findLast((m2) => m2.type === "assistant");
if (!lastAssistant) {
return null;
}
const gapMinutes = (Date.now() - new Date(lastAssistant.timestamp).getTime()) / 60000;
if (!Number.isFinite(gapMinutes) || gapMinutes < config2.gapThresholdMinutes) {
return null;
}
return { gapMinutes, config: config2 };
}
function maybeTimeBasedMicrocompact(messages, querySource) {
const trigger = evaluateTimeBasedTrigger(messages, querySource);
if (!trigger) {
return null;
}
const { gapMinutes, config: config2 } = trigger;
const compactableIds = collectCompactableToolIds(messages);
const keepRecent = Math.max(1, config2.keepRecent);
const keepSet = new Set(compactableIds.slice(-keepRecent));
const clearSet = new Set(compactableIds.filter((id) => !keepSet.has(id)));
if (clearSet.size === 0) {
return null;
}
let tokensSaved = 0;
const result = messages.map((message) => {
if (message.type !== "user" || !Array.isArray(message.message.content)) {
return message;
}
let touched = false;
const newContent = message.message.content.map((block) => {
if (block.type === "tool_result" && clearSet.has(block.tool_use_id) && block.content !== TIME_BASED_MC_CLEARED_MESSAGE) {
tokensSaved += calculateToolResultTokens(block);
touched = true;
return { ...block, content: TIME_BASED_MC_CLEARED_MESSAGE };
}
return block;
});
if (!touched)
return message;
return {
...message,
message: { ...message.message, content: newContent }
};
});
if (tokensSaved === 0) {
return null;
}
logEvent("tengu_time_based_microcompact", {
gapMinutes: Math.round(gapMinutes),
gapThresholdMinutes: config2.gapThresholdMinutes,
toolsCleared: clearSet.size,
toolsKept: keepSet.size,
keepRecent: config2.keepRecent,
tokensSaved
});
logForDebugging(`[TIME-BASED MC] gap ${Math.round(gapMinutes)}min > ${config2.gapThresholdMinutes}min, cleared ${clearSet.size} tool results (~${tokensSaved} tokens), kept last ${keepSet.size}`);
suppressCompactWarning();
resetMicrocompactState();
if (false) {}
return { messages: result };
}
var TIME_BASED_MC_CLEARED_MESSAGE = "[Old tool result content cleared]", IMAGE_MAX_TOKEN_SIZE = 2000, COMPACTABLE_TOOLS, cachedMCModule = null, cachedMCState = null, pendingCacheEdits = null;
var init_microCompact = __esm(() => {
init_prompt2();
init_prompt3();
init_prompt();
init_prompt5();
init_debug();
init_model();
init_shellToolUtils();
init_slowOperations();
init_analytics();
init_promptCacheBreakDetection();
init_tokenEstimation();
init_compactWarningState();
init_timeBasedMCConfig();
COMPACTABLE_TOOLS = new Set([
FILE_READ_TOOL_NAME,
...SHELL_TOOL_NAMES,
GREP_TOOL_NAME,
GLOB_TOOL_NAME,
WEB_SEARCH_TOOL_NAME,
WEB_FETCH_TOOL_NAME,
FILE_EDIT_TOOL_NAME,
FILE_WRITE_TOOL_NAME
]);
});
// node_modules/.pnpm/marked@17.0.5/node_modules/marked/lib/marked.esm.js
function M2() {
return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null };
}
function G3(u2) {
T = u2;
}
function k(u2, e2 = "") {
let t2 = typeof u2 == "string" ? u2 : u2.source, n2 = { replace: (r2, i4) => {
let s2 = typeof i4 == "string" ? i4 : i4.source;
return s2 = s2.replace(m2.caret, "$1"), t2 = t2.replace(r2, s2), n2;
}, getRegex: () => new RegExp(t2, e2) };
return n2;
}
function O(u2, e2) {
if (e2) {
if (m2.escapeTest.test(u2))
return u2.replace(m2.escapeReplace, ke);
} else if (m2.escapeTestNoEncode.test(u2))
return u2.replace(m2.escapeReplaceNoEncode, ke);
return u2;
}
function J(u2) {
try {
u2 = encodeURI(u2).replace(m2.percentDecode, "%");
} catch {
return null;
}
return u2;
}
function V(u2, e2) {
let t2 = u2.replace(m2.findPipe, (i4, s2, a2) => {
let o2 = false, l = s2;
for (;--l >= 0 && a2[l] === "\\"; )
o2 = !o2;
return o2 ? "|" : " |";
}), n2 = t2.split(m2.splitPipe), r2 = 0;
if (n2[0].trim() || n2.shift(), n2.length > 0 && !n2.at(-1)?.trim() && n2.pop(), e2)
if (n2.length > e2)
n2.splice(e2);
else
for (;n2.length < e2; )
n2.push("");
for (;r2 < n2.length; r2++)
n2[r2] = n2[r2].trim().replace(m2.slashPipe, "|");
return n2;
}
function I2(u2, e2, t2) {
let n2 = u2.length;
if (n2 === 0)
return "";
let r2 = 0;
for (;r2 < n2; ) {
let i4 = u2.charAt(n2 - r2 - 1);
if (i4 === e2 && !t2)
r2++;
else if (i4 !== e2 && t2)
r2++;
else
break;
}
return u2.slice(0, n2 - r2);
}
function de(u2, e2) {
if (u2.indexOf(e2[1]) === -1)
return -1;
let t2 = 0;
for (let n2 = 0;n2 < u2.length; n2++)
if (u2[n2] === "\\")
n2++;
else if (u2[n2] === e2[0])
t2++;
else if (u2[n2] === e2[1] && (t2--, t2 < 0))
return n2;
return t2 > 0 ? -2 : -1;
}
function ge(u2, e2 = 0) {
let t2 = e2, n2 = "";
for (let r2 of u2)
if (r2 === "\t") {
let i4 = 4 - t2 % 4;
n2 += " ".repeat(i4), t2 += i4;
} else
n2 += r2, t2++;
return n2;
}
function fe(u2, e2, t2, n2, r2) {
let i4 = e2.href, s2 = e2.title || null, a2 = u2[1].replace(r2.other.outputLinkReplace, "$1");
n2.state.inLink = true;
let o2 = { type: u2[0].charAt(0) === "!" ? "image" : "link", raw: t2, href: i4, title: s2, text: a2, tokens: n2.inlineTokens(a2) };
return n2.state.inLink = false, o2;
}
function nt(u2, e2, t2) {
let n2 = u2.match(t2.other.indentCodeCompensation);
if (n2 === null)
return e2;
let r2 = n2[1];
return e2.split(`
`).map((i4) => {
let s2 = i4.match(t2.other.beginningSpace);
if (s2 === null)
return i4;
let [a2] = s2;
return a2.length >= r2.length ? i4.slice(r2.length) : i4;
}).join(`
`);
}
function g(u4, e2) {
return L2.parse(u4, e2);
}
var T, _, be, m2, Re, Te, Oe, C2, we, Q, se, ie, ye, j, Pe, F2, Se, $e, v = "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|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul", U2, _e, oe, Le, K, ne, Me, ze, Ee, Ie, ae, Ae, z3, H2, W2, Ce, le, Be, De, qe, ue, ve, He, pe = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", Ze, Ge, Ne, Qe, je = "^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)", Fe, Ue, Ke, We, Xe, q, Je, ce, he, Ve, re, X, Ye, N, et2, B, E, tt, ke = (u2) => tt[u2], w = class {
options;
rules;
lexer;
constructor(e2) {
this.options = e2 || T;
}
space(e2) {
let t2 = this.rules.block.newline.exec(e2);
if (t2 && t2[0].length > 0)
return { type: "space", raw: t2[0] };
}
code(e2) {
let t2 = this.rules.block.code.exec(e2);
if (t2) {
let n2 = t2[0].replace(this.rules.other.codeRemoveIndent, "");
return { type: "code", raw: t2[0], codeBlockStyle: "indented", text: this.options.pedantic ? n2 : I2(n2, `
`) };
}
}
fences(e2) {
let t2 = this.rules.block.fences.exec(e2);
if (t2) {
let n2 = t2[0], r2 = nt(n2, t2[3] || "", this.rules);
return { type: "code", raw: n2, lang: t2[2] ? t2[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t2[2], text: r2 };
}
}
heading(e2) {
let t2 = this.rules.block.heading.exec(e2);
if (t2) {
let n2 = t2[2].trim();
if (this.rules.other.endingHash.test(n2)) {
let r2 = I2(n2, "#");
(this.options.pedantic || !r2 || this.rules.other.endingSpaceChar.test(r2)) && (n2 = r2.trim());
}
return { type: "heading", raw: t2[0], depth: t2[1].length, text: n2, tokens: this.lexer.inline(n2) };
}
}
hr(e2) {
let t2 = this.rules.block.hr.exec(e2);
if (t2)
return { type: "hr", raw: I2(t2[0], `
`) };
}
blockquote(e2) {
let t2 = this.rules.block.blockquote.exec(e2);
if (t2) {
let n2 = I2(t2[0], `
`).split(`
`), r2 = "", i4 = "", s2 = [];
for (;n2.length > 0; ) {
let a2 = false, o2 = [], l;
for (l = 0;l < n2.length; l++)
if (this.rules.other.blockquoteStart.test(n2[l]))
o2.push(n2[l]), a2 = true;
else if (!a2)
o2.push(n2[l]);
else
break;
n2 = n2.slice(l);
let p = o2.join(`
`), c6 = p.replace(this.rules.other.blockquoteSetextReplace, `
$1`).replace(this.rules.other.blockquoteSetextReplace2, "");
r2 = r2 ? `${r2}
${p}` : p, i4 = i4 ? `${i4}
${c6}` : c6;
let d = this.lexer.state.top;
if (this.lexer.state.top = true, this.lexer.blockTokens(c6, s2, true), this.lexer.state.top = d, n2.length === 0)
break;
let h3 = s2.at(-1);
if (h3?.type === "code")
break;
if (h3?.type === "blockquote") {
let R2 = h3, f3 = R2.raw + `
` + n2.join(`
`), S2 = this.blockquote(f3);
s2[s2.length - 1] = S2, r2 = r2.substring(0, r2.length - R2.raw.length) + S2.raw, i4 = i4.substring(0, i4.length - R2.text.length) + S2.text;
break;
} else if (h3?.type === "list") {
let R2 = h3, f3 = R2.raw + `
` + n2.join(`
`), S2 = this.list(f3);
s2[s2.length - 1] = S2, r2 = r2.substring(0, r2.length - h3.raw.length) + S2.raw, i4 = i4.substring(0, i4.length - R2.raw.length) + S2.raw, n2 = f3.substring(s2.at(-1).raw.length).split(`
`);
continue;
}
}
return { type: "blockquote", raw: r2, tokens: s2, text: i4 };
}
}
list(e2) {
let t2 = this.rules.block.list.exec(e2);
if (t2) {
let n2 = t2[1].trim(), r2 = n2.length > 1, i4 = { type: "list", raw: "", ordered: r2, start: r2 ? +n2.slice(0, -1) : "", loose: false, items: [] };
n2 = r2 ? `\\d{1,9}\\${n2.slice(-1)}` : `\\${n2}`, this.options.pedantic && (n2 = r2 ? n2 : "[*+-]");
let s2 = this.rules.other.listItemRegex(n2), a2 = false;
for (;e2; ) {
let l = false, p = "", c6 = "";
if (!(t2 = s2.exec(e2)) || this.rules.block.hr.test(e2))
break;
p = t2[0], e2 = e2.substring(p.length);
let d = ge(t2[2].split(`
`, 1)[0], t2[1].length), h3 = e2.split(`
`, 1)[0], R2 = !d.trim(), f3 = 0;
if (this.options.pedantic ? (f3 = 2, c6 = d.trimStart()) : R2 ? f3 = t2[1].length + 1 : (f3 = d.search(this.rules.other.nonSpaceChar), f3 = f3 > 4 ? 1 : f3, c6 = d.slice(f3), f3 += t2[1].length), R2 && this.rules.other.blankLine.test(h3) && (p += h3 + `
`, e2 = e2.substring(h3.length + 1), l = true), !l) {
let S2 = this.rules.other.nextBulletRegex(f3), Y = this.rules.other.hrRegex(f3), ee = this.rules.other.fencesBeginRegex(f3), te2 = this.rules.other.headingBeginRegex(f3), me = this.rules.other.htmlBeginRegex(f3), xe = this.rules.other.blockquoteBeginRegex(f3);
for (;e2; ) {
let Z2 = e2.split(`
`, 1)[0], A2;
if (h3 = Z2, this.options.pedantic ? (h3 = h3.replace(this.rules.other.listReplaceNesting, " "), A2 = h3) : A2 = h3.replace(this.rules.other.tabCharGlobal, " "), ee.test(h3) || te2.test(h3) || me.test(h3) || xe.test(h3) || S2.test(h3) || Y.test(h3))
break;
if (A2.search(this.rules.other.nonSpaceChar) >= f3 || !h3.trim())
c6 += `
` + A2.slice(f3);
else {
if (R2 || d.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4 || ee.test(d) || te2.test(d) || Y.test(d))
break;
c6 += `
` + h3;
}
R2 = !h3.trim(), p += Z2 + `
`, e2 = e2.substring(Z2.length + 1), d = A2.slice(f3);
}
}
i4.loose || (a2 ? i4.loose = true : this.rules.other.doubleBlankLine.test(p) && (a2 = true)), i4.items.push({ type: "list_item", raw: p, task: !!this.options.gfm && this.rules.other.listIsTask.test(c6), loose: false, text: c6, tokens: [] }), i4.raw += p;
}
let o2 = i4.items.at(-1);
if (o2)
o2.raw = o2.raw.trimEnd(), o2.text = o2.text.trimEnd();
else
return;
i4.raw = i4.raw.trimEnd();
for (let l of i4.items) {
if (this.lexer.state.top = false, l.tokens = this.lexer.blockTokens(l.text, []), l.task) {
if (l.text = l.text.replace(this.rules.other.listReplaceTask, ""), l.tokens[0]?.type === "text" || l.tokens[0]?.type === "paragraph") {
l.tokens[0].raw = l.tokens[0].raw.replace(this.rules.other.listReplaceTask, ""), l.tokens[0].text = l.tokens[0].text.replace(this.rules.other.listReplaceTask, "");
for (let c6 = this.lexer.inlineQueue.length - 1;c6 >= 0; c6--)
if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[c6].src)) {
this.lexer.inlineQueue[c6].src = this.lexer.inlineQueue[c6].src.replace(this.rules.other.listReplaceTask, "");
break;
}
}
let p = this.rules.other.listTaskCheckbox.exec(l.raw);
if (p) {
let c6 = { type: "checkbox", raw: p[0] + " ", checked: p[0] !== "[ ]" };
l.checked = c6.checked, i4.loose ? l.tokens[0] && ["paragraph", "text"].includes(l.tokens[0].type) && "tokens" in l.tokens[0] && l.tokens[0].tokens ? (l.tokens[0].raw = c6.raw + l.tokens[0].raw, l.tokens[0].text = c6.raw + l.tokens[0].text, l.tokens[0].tokens.unshift(c6)) : l.tokens.unshift({ type: "paragraph", raw: c6.raw, text: c6.raw, tokens: [c6] }) : l.tokens.unshift(c6);
}
}
if (!i4.loose) {
let p = l.tokens.filter((d) => d.type === "space"), c6 = p.length > 0 && p.some((d) => this.rules.other.anyLine.test(d.raw));
i4.loose = c6;
}
}
if (i4.loose)
for (let l of i4.items) {
l.loose = true;
for (let p of l.tokens)
p.type === "text" && (p.type = "paragraph");
}
return i4;
}
}
html(e2) {
let t2 = this.rules.block.html.exec(e2);
if (t2)
return { type: "html", block: true, raw: t2[0], pre: t2[1] === "pre" || t2[1] === "script" || t2[1] === "style", text: t2[0] };
}
def(e2) {
let t2 = this.rules.block.def.exec(e2);
if (t2) {
let n2 = t2[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), r2 = t2[2] ? t2[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", i4 = t2[3] ? t2[3].substring(1, t2[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t2[3];
return { type: "def", tag: n2, raw: t2[0], href: r2, title: i4 };
}
}
table(e2) {
let t2 = this.rules.block.table.exec(e2);
if (!t2 || !this.rules.other.tableDelimiter.test(t2[2]))
return;
let n2 = V(t2[1]), r2 = t2[2].replace(this.rules.other.tableAlignChars, "").split("|"), i4 = t2[3]?.trim() ? t2[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [], s2 = { type: "table", raw: t2[0], header: [], align: [], rows: [] };
if (n2.length === r2.length) {
for (let a2 of r2)
this.rules.other.tableAlignRight.test(a2) ? s2.align.push("right") : this.rules.other.tableAlignCenter.test(a2) ? s2.align.push("center") : this.rules.other.tableAlignLeft.test(a2) ? s2.align.push("left") : s2.align.push(null);
for (let a2 = 0;a2 < n2.length; a2++)
s2.header.push({ text: n2[a2], tokens: this.lexer.inline(n2[a2]), header: true, align: s2.align[a2] });
for (let a2 of i4)
s2.rows.push(V(a2, s2.header.length).map((o2, l) => ({ text: o2, tokens: this.lexer.inline(o2), header: false, align: s2.align[l] })));
return s2;
}
}
lheading(e2) {
let t2 = this.rules.block.lheading.exec(e2);
if (t2) {
let n2 = t2[1].trim();
return { type: "heading", raw: t2[0], depth: t2[2].charAt(0) === "=" ? 1 : 2, text: n2, tokens: this.lexer.inline(n2) };
}
}
paragraph(e2) {
let t2 = this.rules.block.paragraph.exec(e2);
if (t2) {
let n2 = t2[1].charAt(t2[1].length - 1) === `
` ? t2[1].slice(0, -1) : t2[1];
return { type: "paragraph", raw: t2[0], text: n2, tokens: this.lexer.inline(n2) };
}
}
text(e2) {
let t2 = this.rules.block.text.exec(e2);
if (t2)
return { type: "text", raw: t2[0], text: t2[0], tokens: this.lexer.inline(t2[0]) };
}
escape(e2) {
let t2 = this.rules.inline.escape.exec(e2);
if (t2)
return { type: "escape", raw: t2[0], text: t2[1] };
}
tag(e2) {
let t2 = this.rules.inline.tag.exec(e2);
if (t2)
return !this.lexer.state.inLink && this.rules.other.startATag.test(t2[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t2[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t2[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t2[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t2[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t2[0] };
}
link(e2) {
let t2 = this.rules.inline.link.exec(e2);
if (t2) {
let n2 = t2[2].trim();
if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n2)) {
if (!this.rules.other.endAngleBracket.test(n2))
return;
let s2 = I2(n2.slice(0, -1), "\\");
if ((n2.length - s2.length) % 2 === 0)
return;
} else {
let s2 = de(t2[2], "()");
if (s2 === -2)
return;
if (s2 > -1) {
let o2 = (t2[0].indexOf("!") === 0 ? 5 : 4) + t2[1].length + s2;
t2[2] = t2[2].substring(0, s2), t2[0] = t2[0].substring(0, o2).trim(), t2[3] = "";
}
}
let r2 = t2[2], i4 = "";
if (this.options.pedantic) {
let s2 = this.rules.other.pedanticHrefTitle.exec(r2);
s2 && (r2 = s2[1], i4 = s2[3]);
} else
i4 = t2[3] ? t2[3].slice(1, -1) : "";
return r2 = r2.trim(), this.rules.other.startAngleBracket.test(r2) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n2) ? r2 = r2.slice(1) : r2 = r2.slice(1, -1)), fe(t2, { href: r2 && r2.replace(this.rules.inline.anyPunctuation, "$1"), title: i4 && i4.replace(this.rules.inline.anyPunctuation, "$1") }, t2[0], this.lexer, this.rules);
}
}
reflink(e2, t2) {
let n2;
if ((n2 = this.rules.inline.reflink.exec(e2)) || (n2 = this.rules.inline.nolink.exec(e2))) {
let r2 = (n2[2] || n2[1]).replace(this.rules.other.multipleSpaceGlobal, " "), i4 = t2[r2.toLowerCase()];
if (!i4) {
let s2 = n2[0].charAt(0);
return { type: "text", raw: s2, text: s2 };
}
return fe(n2, i4, n2[0], this.lexer, this.rules);
}
}
emStrong(e2, t2, n2 = "") {
let r2 = this.rules.inline.emStrongLDelim.exec(e2);
if (!r2 || !r2[1] && !r2[2] && !r2[3] && !r2[4] || r2[4] && n2.match(this.rules.other.unicodeAlphaNumeric))
return;
if (!(r2[1] || r2[3] || "") || !n2 || this.rules.inline.punctuation.exec(n2)) {
let s2 = [...r2[0]].length - 1, a2, o2, l = s2, p = 0, c6 = r2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
for (c6.lastIndex = 0, t2 = t2.slice(-1 * e2.length + s2);(r2 = c6.exec(t2)) != null; ) {
if (a2 = r2[1] || r2[2] || r2[3] || r2[4] || r2[5] || r2[6], !a2)
continue;
if (o2 = [...a2].length, r2[3] || r2[4]) {
l += o2;
continue;
} else if ((r2[5] || r2[6]) && s2 % 3 && !((s2 + o2) % 3)) {
p += o2;
continue;
}
if (l -= o2, l > 0)
continue;
o2 = Math.min(o2, o2 + l + p);
let d = [...r2[0]][0].length, h3 = e2.slice(0, s2 + r2.index + d + o2);
if (Math.min(s2, o2) % 2) {
let f3 = h3.slice(1, -1);
return { type: "em", raw: h3, text: f3, tokens: this.lexer.inlineTokens(f3) };
}
let R2 = h3.slice(2, -2);
return { type: "strong", raw: h3, text: R2, tokens: this.lexer.inlineTokens(R2) };
}
}
}
codespan(e2) {
let t2 = this.rules.inline.code.exec(e2);
if (t2) {
let n2 = t2[2].replace(this.rules.other.newLineCharGlobal, " "), r2 = this.rules.other.nonSpaceChar.test(n2), i4 = this.rules.other.startingSpaceChar.test(n2) && this.rules.other.endingSpaceChar.test(n2);
return r2 && i4 && (n2 = n2.substring(1, n2.length - 1)), { type: "codespan", raw: t2[0], text: n2 };
}
}
br(e2) {
let t2 = this.rules.inline.br.exec(e2);
if (t2)
return { type: "br", raw: t2[0] };
}
del(e2, t2, n2 = "") {
let r2 = this.rules.inline.delLDelim.exec(e2);
if (!r2)
return;
if (!(r2[1] || "") || !n2 || this.rules.inline.punctuation.exec(n2)) {
let s2 = [...r2[0]].length - 1, a2, o2, l = s2, p = this.rules.inline.delRDelim;
for (p.lastIndex = 0, t2 = t2.slice(-1 * e2.length + s2);(r2 = p.exec(t2)) != null; ) {
if (a2 = r2[1] || r2[2] || r2[3] || r2[4] || r2[5] || r2[6], !a2 || (o2 = [...a2].length, o2 !== s2))
continue;
if (r2[3] || r2[4]) {
l += o2;
continue;
}
if (l -= o2, l > 0)
continue;
o2 = Math.min(o2, o2 + l);
let c6 = [...r2[0]][0].length, d = e2.slice(0, s2 + r2.index + c6 + o2), h3 = d.slice(s2, -s2);
return { type: "del", raw: d, text: h3, tokens: this.lexer.inlineTokens(h3) };
}
}
}
autolink(e2) {
let t2 = this.rules.inline.autolink.exec(e2);
if (t2) {
let n2, r2;
return t2[2] === "@" ? (n2 = t2[1], r2 = "mailto:" + n2) : (n2 = t2[1], r2 = n2), { type: "link", raw: t2[0], text: n2, href: r2, tokens: [{ type: "text", raw: n2, text: n2 }] };
}
}
url(e2) {
let t2;
if (t2 = this.rules.inline.url.exec(e2)) {
let n2, r2;
if (t2[2] === "@")
n2 = t2[0], r2 = "mailto:" + n2;
else {
let i4;
do
i4 = t2[0], t2[0] = this.rules.inline._backpedal.exec(t2[0])?.[0] ?? "";
while (i4 !== t2[0]);
n2 = t2[0], t2[1] === "www." ? r2 = "http://" + t2[0] : r2 = t2[0];
}
return { type: "link", raw: t2[0], text: n2, href: r2, tokens: [{ type: "text", raw: n2, text: n2 }] };
}
}
inlineText(e2) {
let t2 = this.rules.inline.text.exec(e2);
if (t2) {
let n2 = this.lexer.state.inRawBlock;
return { type: "text", raw: t2[0], text: t2[0], escaped: n2 };
}
}
}, x4 = class u2 {
tokens;
options;
state;
inlineQueue;
tokenizer;
constructor(e2) {
this.tokens = [], this.tokens.links = Object.create(null), this.options = e2 || T, this.options.tokenizer = this.options.tokenizer || new w, this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, top: true };
let t2 = { other: m2, block: B.normal, inline: E.normal };
this.options.pedantic ? (t2.block = B.pedantic, t2.inline = E.pedantic) : this.options.gfm && (t2.block = B.gfm, this.options.breaks ? t2.inline = E.breaks : t2.inline = E.gfm), this.tokenizer.rules = t2;
}
static get rules() {
return { block: B, inline: E };
}
static lex(e2, t2) {
return new u2(t2).lex(e2);
}
static lexInline(e2, t2) {
return new u2(t2).inlineTokens(e2);
}
lex(e2) {
e2 = e2.replace(m2.carriageReturn, `
`), this.blockTokens(e2, this.tokens);
for (let t2 = 0;t2 < this.inlineQueue.length; t2++) {
let n2 = this.inlineQueue[t2];
this.inlineTokens(n2.src, n2.tokens);
}
return this.inlineQueue = [], this.tokens;
}
blockTokens(e2, t2 = [], n2 = false) {
for (this.tokenizer.lexer = this, this.options.pedantic && (e2 = e2.replace(m2.tabCharGlobal, " ").replace(m2.spaceLine, ""));e2; ) {
let r2;
if (this.options.extensions?.block?.some((s2) => (r2 = s2.call({ lexer: this }, e2, t2)) ? (e2 = e2.substring(r2.raw.length), t2.push(r2), true) : false))
continue;
if (r2 = this.tokenizer.space(e2)) {
e2 = e2.substring(r2.raw.length);
let s2 = t2.at(-1);
r2.raw.length === 1 && s2 !== undefined ? s2.raw += `
` : t2.push(r2);
continue;
}
if (r2 = this.tokenizer.code(e2)) {
e2 = e2.substring(r2.raw.length);
let s2 = t2.at(-1);
s2?.type === "paragraph" || s2?.type === "text" ? (s2.raw += (s2.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s2.text += `
` + r2.text, this.inlineQueue.at(-1).src = s2.text) : t2.push(r2);
continue;
}
if (r2 = this.tokenizer.fences(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
if (r2 = this.tokenizer.heading(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
if (r2 = this.tokenizer.hr(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
if (r2 = this.tokenizer.blockquote(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
if (r2 = this.tokenizer.list(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
if (r2 = this.tokenizer.html(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
if (r2 = this.tokenizer.def(e2)) {
e2 = e2.substring(r2.raw.length);
let s2 = t2.at(-1);
s2?.type === "paragraph" || s2?.type === "text" ? (s2.raw += (s2.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s2.text += `
` + r2.raw, this.inlineQueue.at(-1).src = s2.text) : this.tokens.links[r2.tag] || (this.tokens.links[r2.tag] = { href: r2.href, title: r2.title }, t2.push(r2));
continue;
}
if (r2 = this.tokenizer.table(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
if (r2 = this.tokenizer.lheading(e2)) {
e2 = e2.substring(r2.raw.length), t2.push(r2);
continue;
}
let i4 = e2;
if (this.options.extensions?.startBlock) {
let s2 = 1 / 0, a2 = e2.slice(1), o2;
this.options.extensions.startBlock.forEach((l) => {
o2 = l.call({ lexer: this }, a2), typeof o2 == "number" && o2 >= 0 && (s2 = Math.min(s2, o2));
}), s2 < 1 / 0 && s2 >= 0 && (i4 = e2.substring(0, s2 + 1));
}
if (this.state.top && (r2 = this.tokenizer.paragraph(i4))) {
let s2 = t2.at(-1);
n2 && s2?.type === "paragraph" ? (s2.raw += (s2.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s2.text += `
` + r2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s2.text) : t2.push(r2), n2 = i4.length !== e2.length, e2 = e2.substring(r2.raw.length);
continue;
}
if (r2 = this.tokenizer.text(e2)) {
e2 = e2.substring(r2.raw.length);
let s2 = t2.at(-1);
s2?.type === "text" ? (s2.raw += (s2.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s2.text += `
` + r2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s2.text) : t2.push(r2);
continue;
}
if (e2) {
let s2 = "Infinite loop on byte: " + e2.charCodeAt(0);
if (this.options.silent) {
console.error(s2);
break;
} else
throw new Error(s2);
}
}
return this.state.top = true, t2;
}
inline(e2, t2 = []) {
return this.inlineQueue.push({ src: e2, tokens: t2 }), t2;
}
inlineTokens(e2, t2 = []) {
this.tokenizer.lexer = this;
let n2 = e2, r2 = null;
if (this.tokens.links) {
let o2 = Object.keys(this.tokens.links);
if (o2.length > 0)
for (;(r2 = this.tokenizer.rules.inline.reflinkSearch.exec(n2)) != null; )
o2.includes(r2[0].slice(r2[0].lastIndexOf("[") + 1, -1)) && (n2 = n2.slice(0, r2.index) + "[" + "a".repeat(r2[0].length - 2) + "]" + n2.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
}
for (;(r2 = this.tokenizer.rules.inline.anyPunctuation.exec(n2)) != null; )
n2 = n2.slice(0, r2.index) + "++" + n2.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
let i4;
for (;(r2 = this.tokenizer.rules.inline.blockSkip.exec(n2)) != null; )
i4 = r2[2] ? r2[2].length : 0, n2 = n2.slice(0, r2.index + i4) + "[" + "a".repeat(r2[0].length - i4 - 2) + "]" + n2.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
n2 = this.options.hooks?.emStrongMask?.call({ lexer: this }, n2) ?? n2;
let s2 = false, a2 = "";
for (;e2; ) {
s2 || (a2 = ""), s2 = false;
let o2;
if (this.options.extensions?.inline?.some((p) => (o2 = p.call({ lexer: this }, e2, t2)) ? (e2 = e2.substring(o2.raw.length), t2.push(o2), true) : false))
continue;
if (o2 = this.tokenizer.escape(e2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (o2 = this.tokenizer.tag(e2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (o2 = this.tokenizer.link(e2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (o2 = this.tokenizer.reflink(e2, this.tokens.links)) {
e2 = e2.substring(o2.raw.length);
let p = t2.at(-1);
o2.type === "text" && p?.type === "text" ? (p.raw += o2.raw, p.text += o2.text) : t2.push(o2);
continue;
}
if (o2 = this.tokenizer.emStrong(e2, n2, a2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (o2 = this.tokenizer.codespan(e2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (o2 = this.tokenizer.br(e2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (o2 = this.tokenizer.del(e2, n2, a2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (o2 = this.tokenizer.autolink(e2)) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
if (!this.state.inLink && (o2 = this.tokenizer.url(e2))) {
e2 = e2.substring(o2.raw.length), t2.push(o2);
continue;
}
let l = e2;
if (this.options.extensions?.startInline) {
let p = 1 / 0, c6 = e2.slice(1), d;
this.options.extensions.startInline.forEach((h3) => {
d = h3.call({ lexer: this }, c6), typeof d == "number" && d >= 0 && (p = Math.min(p, d));
}), p < 1 / 0 && p >= 0 && (l = e2.substring(0, p + 1));
}
if (o2 = this.tokenizer.inlineText(l)) {
e2 = e2.substring(o2.raw.length), o2.raw.slice(-1) !== "_" && (a2 = o2.raw.slice(-1)), s2 = true;
let p = t2.at(-1);
p?.type === "text" ? (p.raw += o2.raw, p.text += o2.text) : t2.push(o2);
continue;
}
if (e2) {
let p = "Infinite loop on byte: " + e2.charCodeAt(0);
if (this.options.silent) {
console.error(p);
break;
} else
throw new Error(p);
}
}
return t2;
}
}, y2 = class {
options;
parser;
constructor(e2) {
this.options = e2 || T;
}
space(e2) {
return "";
}
code({ text: e2, lang: t2, escaped: n2 }) {
let r2 = (t2 || "").match(m2.notSpaceStart)?.[0], i4 = e2.replace(m2.endingNewline, "") + `
`;
return r2 ? '' + (n2 ? i4 : O(i4, true)) + `
` : "" + (n2 ? i4 : O(i4, true)) + `
`;
}
blockquote({ tokens: e2 }) {
return `
${this.parser.parse(e2)}
`;
}
html({ text: e2 }) {
return e2;
}
def(e2) {
return "";
}
heading({ tokens: e2, depth: t2 }) {
return `${this.parser.parseInline(e2)}
`;
}
hr(e2) {
return `
`;
}
list(e2) {
let { ordered: t2, start: n2 } = e2, r2 = "";
for (let a2 = 0;a2 < e2.items.length; a2++) {
let o2 = e2.items[a2];
r2 += this.listitem(o2);
}
let i4 = t2 ? "ol" : "ul", s2 = t2 && n2 !== 1 ? ' start="' + n2 + '"' : "";
return "<" + i4 + s2 + `>
` + r2 + "" + i4 + `>
`;
}
listitem(e2) {
return `${this.parser.parse(e2.tokens)}
`;
}
checkbox({ checked: e2 }) {
return " ';
}
paragraph({ tokens: e2 }) {
return `${this.parser.parseInline(e2)}
`;
}
table(e2) {
let t2 = "", n2 = "";
for (let i4 = 0;i4 < e2.header.length; i4++)
n2 += this.tablecell(e2.header[i4]);
t2 += this.tablerow({ text: n2 });
let r2 = "";
for (let i4 = 0;i4 < e2.rows.length; i4++) {
let s2 = e2.rows[i4];
n2 = "";
for (let a2 = 0;a2 < s2.length; a2++)
n2 += this.tablecell(s2[a2]);
r2 += this.tablerow({ text: n2 });
}
return r2 && (r2 = `${r2}`), `
`;
}
tablerow({ text: e2 }) {
return `
${e2}
`;
}
tablecell(e2) {
let t2 = this.parser.parseInline(e2.tokens), n2 = e2.header ? "th" : "td";
return (e2.align ? `<${n2} align="${e2.align}">` : `<${n2}>`) + t2 + `${n2}>
`;
}
strong({ tokens: e2 }) {
return `${this.parser.parseInline(e2)}`;
}
em({ tokens: e2 }) {
return `${this.parser.parseInline(e2)}`;
}
codespan({ text: e2 }) {
return `${O(e2, true)}`;
}
br(e2) {
return "
";
}
del({ tokens: e2 }) {
return `${this.parser.parseInline(e2)}`;
}
link({ href: e2, title: t2, tokens: n2 }) {
let r2 = this.parser.parseInline(n2), i4 = J(e2);
if (i4 === null)
return r2;
e2 = i4;
let s2 = '" + r2 + "", s2;
}
image({ href: e2, title: t2, text: n2, tokens: r2 }) {
r2 && (n2 = this.parser.parseInline(r2, this.parser.textRenderer));
let i4 = J(e2);
if (i4 === null)
return O(n2);
e2 = i4;
let s2 = `
", s2;
}
text(e2) {
return "tokens" in e2 && e2.tokens ? this.parser.parseInline(e2.tokens) : ("escaped" in e2) && e2.escaped ? e2.text : O(e2.text);
}
}, $2 = class {
strong({ text: e2 }) {
return e2;
}
em({ text: e2 }) {
return e2;
}
codespan({ text: e2 }) {
return e2;
}
del({ text: e2 }) {
return e2;
}
html({ text: e2 }) {
return e2;
}
text({ text: e2 }) {
return e2;
}
link({ text: e2 }) {
return "" + e2;
}
image({ text: e2 }) {
return "" + e2;
}
br() {
return "";
}
checkbox({ raw: e2 }) {
return e2;
}
}, b = class u3 {
options;
renderer;
textRenderer;
constructor(e2) {
this.options = e2 || T, this.options.renderer = this.options.renderer || new y2, this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new $2;
}
static parse(e2, t2) {
return new u3(t2).parse(e2);
}
static parseInline(e2, t2) {
return new u3(t2).parseInline(e2);
}
parse(e2) {
this.renderer.parser = this;
let t2 = "";
for (let n2 = 0;n2 < e2.length; n2++) {
let r2 = e2[n2];
if (this.options.extensions?.renderers?.[r2.type]) {
let s2 = r2, a2 = this.options.extensions.renderers[s2.type].call({ parser: this }, s2);
if (a2 !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "def", "paragraph", "text"].includes(s2.type)) {
t2 += a2 || "";
continue;
}
}
let i4 = r2;
switch (i4.type) {
case "space": {
t2 += this.renderer.space(i4);
break;
}
case "hr": {
t2 += this.renderer.hr(i4);
break;
}
case "heading": {
t2 += this.renderer.heading(i4);
break;
}
case "code": {
t2 += this.renderer.code(i4);
break;
}
case "table": {
t2 += this.renderer.table(i4);
break;
}
case "blockquote": {
t2 += this.renderer.blockquote(i4);
break;
}
case "list": {
t2 += this.renderer.list(i4);
break;
}
case "checkbox": {
t2 += this.renderer.checkbox(i4);
break;
}
case "html": {
t2 += this.renderer.html(i4);
break;
}
case "def": {
t2 += this.renderer.def(i4);
break;
}
case "paragraph": {
t2 += this.renderer.paragraph(i4);
break;
}
case "text": {
t2 += this.renderer.text(i4);
break;
}
default: {
let s2 = 'Token with "' + i4.type + '" type was not found.';
if (this.options.silent)
return console.error(s2), "";
throw new Error(s2);
}
}
}
return t2;
}
parseInline(e2, t2 = this.renderer) {
this.renderer.parser = this;
let n2 = "";
for (let r2 = 0;r2 < e2.length; r2++) {
let i4 = e2[r2];
if (this.options.extensions?.renderers?.[i4.type]) {
let a2 = this.options.extensions.renderers[i4.type].call({ parser: this }, i4);
if (a2 !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(i4.type)) {
n2 += a2 || "";
continue;
}
}
let s2 = i4;
switch (s2.type) {
case "escape": {
n2 += t2.text(s2);
break;
}
case "html": {
n2 += t2.html(s2);
break;
}
case "link": {
n2 += t2.link(s2);
break;
}
case "image": {
n2 += t2.image(s2);
break;
}
case "checkbox": {
n2 += t2.checkbox(s2);
break;
}
case "strong": {
n2 += t2.strong(s2);
break;
}
case "em": {
n2 += t2.em(s2);
break;
}
case "codespan": {
n2 += t2.codespan(s2);
break;
}
case "br": {
n2 += t2.br(s2);
break;
}
case "del": {
n2 += t2.del(s2);
break;
}
case "text": {
n2 += t2.text(s2);
break;
}
default: {
let a2 = 'Token with "' + s2.type + '" type was not found.';
if (this.options.silent)
return console.error(a2), "";
throw new Error(a2);
}
}
}
return n2;
}
}, P, D2 = class {
defaults = M2();
options = this.setOptions;
parse = this.parseMarkdown(true);
parseInline = this.parseMarkdown(false);
Parser = b;
Renderer = y2;
TextRenderer = $2;
Lexer = x4;
Tokenizer = w;
Hooks = P;
constructor(...e2) {
this.use(...e2);
}
walkTokens(e2, t2) {
let n2 = [];
for (let r2 of e2)
switch (n2 = n2.concat(t2.call(this, r2)), r2.type) {
case "table": {
let i4 = r2;
for (let s2 of i4.header)
n2 = n2.concat(this.walkTokens(s2.tokens, t2));
for (let s2 of i4.rows)
for (let a2 of s2)
n2 = n2.concat(this.walkTokens(a2.tokens, t2));
break;
}
case "list": {
let i4 = r2;
n2 = n2.concat(this.walkTokens(i4.items, t2));
break;
}
default: {
let i4 = r2;
this.defaults.extensions?.childTokens?.[i4.type] ? this.defaults.extensions.childTokens[i4.type].forEach((s2) => {
let a2 = i4[s2].flat(1 / 0);
n2 = n2.concat(this.walkTokens(a2, t2));
}) : i4.tokens && (n2 = n2.concat(this.walkTokens(i4.tokens, t2)));
}
}
return n2;
}
use(...e2) {
let t2 = this.defaults.extensions || { renderers: {}, childTokens: {} };
return e2.forEach((n2) => {
let r2 = { ...n2 };
if (r2.async = this.defaults.async || r2.async || false, n2.extensions && (n2.extensions.forEach((i4) => {
if (!i4.name)
throw new Error("extension name required");
if ("renderer" in i4) {
let s2 = t2.renderers[i4.name];
s2 ? t2.renderers[i4.name] = function(...a2) {
let o2 = i4.renderer.apply(this, a2);
return o2 === false && (o2 = s2.apply(this, a2)), o2;
} : t2.renderers[i4.name] = i4.renderer;
}
if ("tokenizer" in i4) {
if (!i4.level || i4.level !== "block" && i4.level !== "inline")
throw new Error("extension level must be 'block' or 'inline'");
let s2 = t2[i4.level];
s2 ? s2.unshift(i4.tokenizer) : t2[i4.level] = [i4.tokenizer], i4.start && (i4.level === "block" ? t2.startBlock ? t2.startBlock.push(i4.start) : t2.startBlock = [i4.start] : i4.level === "inline" && (t2.startInline ? t2.startInline.push(i4.start) : t2.startInline = [i4.start]));
}
"childTokens" in i4 && i4.childTokens && (t2.childTokens[i4.name] = i4.childTokens);
}), r2.extensions = t2), n2.renderer) {
let i4 = this.defaults.renderer || new y2(this.defaults);
for (let s2 in n2.renderer) {
if (!(s2 in i4))
throw new Error(`renderer '${s2}' does not exist`);
if (["options", "parser"].includes(s2))
continue;
let a2 = s2, o2 = n2.renderer[a2], l = i4[a2];
i4[a2] = (...p) => {
let c6 = o2.apply(i4, p);
return c6 === false && (c6 = l.apply(i4, p)), c6 || "";
};
}
r2.renderer = i4;
}
if (n2.tokenizer) {
let i4 = this.defaults.tokenizer || new w(this.defaults);
for (let s2 in n2.tokenizer) {
if (!(s2 in i4))
throw new Error(`tokenizer '${s2}' does not exist`);
if (["options", "rules", "lexer"].includes(s2))
continue;
let a2 = s2, o2 = n2.tokenizer[a2], l = i4[a2];
i4[a2] = (...p) => {
let c6 = o2.apply(i4, p);
return c6 === false && (c6 = l.apply(i4, p)), c6;
};
}
r2.tokenizer = i4;
}
if (n2.hooks) {
let i4 = this.defaults.hooks || new P;
for (let s2 in n2.hooks) {
if (!(s2 in i4))
throw new Error(`hook '${s2}' does not exist`);
if (["options", "block"].includes(s2))
continue;
let a2 = s2, o2 = n2.hooks[a2], l = i4[a2];
P.passThroughHooks.has(s2) ? i4[a2] = (p) => {
if (this.defaults.async && P.passThroughHooksRespectAsync.has(s2))
return (async () => {
let d = await o2.call(i4, p);
return l.call(i4, d);
})();
let c6 = o2.call(i4, p);
return l.call(i4, c6);
} : i4[a2] = (...p) => {
if (this.defaults.async)
return (async () => {
let d = await o2.apply(i4, p);
return d === false && (d = await l.apply(i4, p)), d;
})();
let c6 = o2.apply(i4, p);
return c6 === false && (c6 = l.apply(i4, p)), c6;
};
}
r2.hooks = i4;
}
if (n2.walkTokens) {
let i4 = this.defaults.walkTokens, s2 = n2.walkTokens;
r2.walkTokens = function(a2) {
let o2 = [];
return o2.push(s2.call(this, a2)), i4 && (o2 = o2.concat(i4.call(this, a2))), o2;
};
}
this.defaults = { ...this.defaults, ...r2 };
}), this;
}
setOptions(e2) {
return this.defaults = { ...this.defaults, ...e2 }, this;
}
lexer(e2, t2) {
return x4.lex(e2, t2 ?? this.defaults);
}
parser(e2, t2) {
return b.parse(e2, t2 ?? this.defaults);
}
parseMarkdown(e2) {
return (n2, r2) => {
let i4 = { ...r2 }, s2 = { ...this.defaults, ...i4 }, a2 = this.onError(!!s2.silent, !!s2.async);
if (this.defaults.async === true && i4.async === false)
return a2(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
if (typeof n2 > "u" || n2 === null)
return a2(new Error("marked(): input parameter is undefined or null"));
if (typeof n2 != "string")
return a2(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n2) + ", string expected"));
if (s2.hooks && (s2.hooks.options = s2, s2.hooks.block = e2), s2.async)
return (async () => {
let o2 = s2.hooks ? await s2.hooks.preprocess(n2) : n2, p = await (s2.hooks ? await s2.hooks.provideLexer() : e2 ? x4.lex : x4.lexInline)(o2, s2), c6 = s2.hooks ? await s2.hooks.processAllTokens(p) : p;
s2.walkTokens && await Promise.all(this.walkTokens(c6, s2.walkTokens));
let h3 = await (s2.hooks ? await s2.hooks.provideParser() : e2 ? b.parse : b.parseInline)(c6, s2);
return s2.hooks ? await s2.hooks.postprocess(h3) : h3;
})().catch(a2);
try {
s2.hooks && (n2 = s2.hooks.preprocess(n2));
let l = (s2.hooks ? s2.hooks.provideLexer() : e2 ? x4.lex : x4.lexInline)(n2, s2);
s2.hooks && (l = s2.hooks.processAllTokens(l)), s2.walkTokens && this.walkTokens(l, s2.walkTokens);
let c6 = (s2.hooks ? s2.hooks.provideParser() : e2 ? b.parse : b.parseInline)(l, s2);
return s2.hooks && (c6 = s2.hooks.postprocess(c6)), c6;
} catch (o2) {
return a2(o2);
}
};
}
onError(e2, t2) {
return (n2) => {
if (n2.message += `
Please report this to https://github.com/markedjs/marked.`, e2) {
let r2 = "An error occurred:
" + O(n2.message + "", true) + "
";
return t2 ? Promise.resolve(r2) : r2;
}
if (t2)
return Promise.reject(n2);
throw n2;
};
}
}, L2, Qt, jt, Ft, Ut, Kt, Xt, Jt;
var init_marked_esm = __esm(() => {
T = M2();
_ = { exec: () => null };
be = (() => {
try {
return !!new RegExp("(?<=1)(?/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^, endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (u2) => new RegExp(`^( {0,3}${u2})((?:[ ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (u2) => new RegExp(`^ {0,${Math.min(3, u2 - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`), hrRegex: (u2) => new RegExp(`^ {0,${Math.min(3, u2 - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (u2) => new RegExp(`^ {0,${Math.min(3, u2 - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (u2) => new RegExp(`^ {0,${Math.min(3, u2 - 1)}}#`), htmlBeginRegex: (u2) => new RegExp(`^ {0,${Math.min(3, u2 - 1)}}<(?:[a-z].*>|!--)`, "i"), blockquoteBeginRegex: (u2) => new RegExp(`^ {0,${Math.min(3, u2 - 1)}}>`) };
Re = /^(?:[ \t]*(?:\n|$))+/;
Te = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
Oe = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
C2 = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
we = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
Q = / {0,3}(?:[*+-]|\d{1,9}[.)])/;
se = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
ie = k(se).replace(/bull/g, Q).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
ye = k(se).replace(/bull/g, Q).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
j = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
Pe = /^[^\n]+/;
F2 = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/;
Se = k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", F2).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
$e = k(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, Q).getRegex();
U2 = /|$))/;
_e = k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))", "i").replace("comment", U2).replace("tag", v).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
oe = k(j).replace("hr", C2).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex();
Le = k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", oe).getRegex();
K = { blockquote: Le, code: Te, def: Se, fences: Oe, heading: we, hr: C2, html: _e, lheading: ie, list: $e, newline: Re, paragraph: oe, table: _, text: Pe };
ne = k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", C2).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}\t)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex();
Me = { ...K, lheading: ye, table: ne, paragraph: k(j).replace("hr", C2).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", ne).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex() };
ze = { ...K, html: k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?\\1> *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", U2).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: _, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: k(j).replace("hr", C2).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", ie).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() };
Ee = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
Ie = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
ae = /^( {2,}|\\)\n(?!\s*$)/;
Ae = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", be ? "(?`+)[^`]+\k(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex();
ue = /^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/;
ve = k(ue, "u").replace(/punct/g, z3).getRegex();
He = k(ue, "u").replace(/punct/g, le).getRegex();
Ze = k(pe, "gu").replace(/notPunctSpace/g, W2).replace(/punctSpace/g, H2).replace(/punct/g, z3).getRegex();
Ge = k(pe, "gu").replace(/notPunctSpace/g, De).replace(/punctSpace/g, Be).replace(/punct/g, le).getRegex();
Ne = k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, W2).replace(/punctSpace/g, H2).replace(/punct/g, z3).getRegex();
Qe = k(/^~~?(?:((?!~)punct)|[^\s~])/, "u").replace(/punct/g, z3).getRegex();
Fe = k(je, "gu").replace(/notPunctSpace/g, W2).replace(/punctSpace/g, H2).replace(/punct/g, z3).getRegex();
Ue = k(/\\(punct)/, "gu").replace(/punct/g, z3).getRegex();
Ke = k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
We = k(U2).replace("(?:-->|$)", "-->").getRegex();
Xe = k("^comment|^[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment", We).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
q = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/;
Je = k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label", q).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
ce = k(/^!?\[(label)\]\[(ref)\]/).replace("label", q).replace("ref", F2).getRegex();
he = k(/^!?\[(ref)\](?:\[\])?/).replace("ref", F2).getRegex();
Ve = k("reflink|nolink(?!\\()", "g").replace("reflink", ce).replace("nolink", he).getRegex();
re = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;
X = { _backpedal: _, anyPunctuation: Ue, autolink: Ke, blockSkip: qe, br: ae, code: Ie, del: _, delLDelim: _, delRDelim: _, emStrongLDelim: ve, emStrongRDelimAst: Ze, emStrongRDelimUnd: Ne, escape: Ee, link: Je, nolink: he, punctuation: Ce, reflink: ce, reflinkSearch: Ve, tag: Xe, text: Ae, url: _ };
Ye = { ...X, link: k(/^!?\[(label)\]\((.*?)\)/).replace("label", q).getRegex(), reflink: k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", q).getRegex() };
N = { ...X, emStrongRDelimAst: Ge, emStrongLDelim: He, delLDelim: Qe, delRDelim: Fe, url: k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", re).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: k(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\": ">", '"': """, "'": "'" };
P = class {
options;
block;
constructor(e2) {
this.options = e2 || T;
}
static passThroughHooks = new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"]);
static passThroughHooksRespectAsync = new Set(["preprocess", "postprocess", "processAllTokens"]);
preprocess(e2) {
return e2;
}
postprocess(e2) {
return e2;
}
processAllTokens(e2) {
return e2;
}
emStrongMask(e2) {
return e2;
}
provideLexer() {
return this.block ? x4.lex : x4.lexInline;
}
provideParser() {
return this.block ? b.parse : b.parseInline;
}
};
L2 = new D2;
g.options = g.setOptions = function(u4) {
return L2.setOptions(u4), g.defaults = L2.defaults, G3(g.defaults), g;
};
g.getDefaults = M2;
g.defaults = T;
g.use = function(...u4) {
return L2.use(...u4), g.defaults = L2.defaults, G3(g.defaults), g;
};
g.walkTokens = function(u4, e2) {
return L2.walkTokens(u4, e2);
};
g.parseInline = L2.parseInline;
g.Parser = b;
g.parser = b.parse;
g.Renderer = y2;
g.TextRenderer = $2;
g.Lexer = x4;
g.lexer = x4.lex;
g.Tokenizer = w;
g.Hooks = P;
g.parse = g;
Qt = g.options;
jt = g.setOptions;
Ft = g.use;
Ut = g.walkTokens;
Kt = g.parseInline;
Xt = b.parse;
Jt = x4.lex;
});
// node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/constants.js
var require_constants10 = __commonJS((exports, module) => {
var WIN_SLASH = "\\\\/";
var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
var DEFAULT_MAX_EXTGLOB_RECURSION = 0;
var DOT_LITERAL = "\\.";
var PLUS_LITERAL = "\\+";
var QMARK_LITERAL = "\\?";
var SLASH_LITERAL = "\\/";
var ONE_CHAR = "(?=.)";
var QMARK = "[^/]";
var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
var START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
var NO_DOT = `(?!${DOT_LITERAL})`;
var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
var STAR = `${QMARK}*?`;
var SEP2 = "/";
var POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR,
SEP: SEP2
};
var WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
SEP: "\\"
};
var POSIX_REGEX_SOURCE = {
__proto__: null,
alnum: "a-zA-Z0-9",
alpha: "a-zA-Z",
ascii: "\\x00-\\x7F",
blank: " \\t",
cntrl: "\\x00-\\x1F\\x7F",
digit: "0-9",
graph: "\\x21-\\x7E",
lower: "a-z",
print: "\\x20-\\x7E ",
punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
space: " \\t\\r\\n\\v\\f",
upper: "A-Z",
word: "A-Za-z0-9_",
xdigit: "A-Fa-f0-9"
};
module.exports = {
DEFAULT_MAX_EXTGLOB_RECURSION,
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
REPLACEMENTS: {
__proto__: null,
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
CHAR_0: 48,
CHAR_9: 57,
CHAR_UPPERCASE_A: 65,
CHAR_LOWERCASE_A: 97,
CHAR_UPPERCASE_Z: 90,
CHAR_LOWERCASE_Z: 122,
CHAR_LEFT_PARENTHESES: 40,
CHAR_RIGHT_PARENTHESES: 41,
CHAR_ASTERISK: 42,
CHAR_AMPERSAND: 38,
CHAR_AT: 64,
CHAR_BACKWARD_SLASH: 92,
CHAR_CARRIAGE_RETURN: 13,
CHAR_CIRCUMFLEX_ACCENT: 94,
CHAR_COLON: 58,
CHAR_COMMA: 44,
CHAR_DOT: 46,
CHAR_DOUBLE_QUOTE: 34,
CHAR_EQUAL: 61,
CHAR_EXCLAMATION_MARK: 33,
CHAR_FORM_FEED: 12,
CHAR_FORWARD_SLASH: 47,
CHAR_GRAVE_ACCENT: 96,
CHAR_HASH: 35,
CHAR_HYPHEN_MINUS: 45,
CHAR_LEFT_ANGLE_BRACKET: 60,
CHAR_LEFT_CURLY_BRACE: 123,
CHAR_LEFT_SQUARE_BRACKET: 91,
CHAR_LINE_FEED: 10,
CHAR_NO_BREAK_SPACE: 160,
CHAR_PERCENT: 37,
CHAR_PLUS: 43,
CHAR_QUESTION_MARK: 63,
CHAR_RIGHT_ANGLE_BRACKET: 62,
CHAR_RIGHT_CURLY_BRACE: 125,
CHAR_RIGHT_SQUARE_BRACKET: 93,
CHAR_SEMICOLON: 59,
CHAR_SINGLE_QUOTE: 39,
CHAR_SPACE: 32,
CHAR_TAB: 9,
CHAR_UNDERSCORE: 95,
CHAR_VERTICAL_LINE: 124,
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
extglobChars(chars) {
return {
"!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
"?": { type: "qmark", open: "(?:", close: ")?" },
"+": { type: "plus", open: "(?:", close: ")+" },
"*": { type: "star", open: "(?:", close: ")*" },
"@": { type: "at", open: "(?:", close: ")" }
};
},
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
});
// node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/utils.js
var require_utils9 = __commonJS((exports) => {
var {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = require_constants10();
exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
exports.isWindows = () => {
if (typeof navigator !== "undefined" && navigator.platform) {
const platform3 = navigator.platform.toLowerCase();
return platform3 === "win32" || platform3 === "windows";
}
if (typeof process !== "undefined" && process.platform) {
return process.platform === "win32";
}
return false;
};
exports.removeBackslashes = (str) => {
return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
return match === "\\" ? "" : match;
});
};
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1)
return input;
if (input[idx - 1] === "\\")
return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state3 = {}) => {
let output = input;
if (output.startsWith("./")) {
output = output.slice(2);
state3.prefix = "./";
}
return output;
};
exports.wrapOutput = (input, state3 = {}, options = {}) => {
const prepend = options.contains ? "" : "^";
const append2 = options.contains ? "" : "$";
let output = `${prepend}(?:${input})${append2}`;
if (state3.negated === true) {
output = `(?:^(?!${output}).*$)`;
}
return output;
};
exports.basename = (path14, { windows: windows2 } = {}) => {
const segs = path14.split(windows2 ? /[\\/]/ : "/");
const last2 = segs[segs.length - 1];
if (last2 === "") {
return segs[segs.length - 2];
}
return last2;
};
});
// node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/scan.js
var require_scan = __commonJS((exports, module) => {
var utils = require_utils9();
var {
CHAR_ASTERISK,
CHAR_AT,
CHAR_BACKWARD_SLASH,
CHAR_COMMA,
CHAR_DOT,
CHAR_EXCLAMATION_MARK,
CHAR_FORWARD_SLASH,
CHAR_LEFT_CURLY_BRACE,
CHAR_LEFT_PARENTHESES,
CHAR_LEFT_SQUARE_BRACKET,
CHAR_PLUS,
CHAR_QUESTION_MARK,
CHAR_RIGHT_CURLY_BRACE,
CHAR_RIGHT_PARENTHESES,
CHAR_RIGHT_SQUARE_BRACKET
} = require_constants10();
var isPathSeparator = (code) => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
var depth = (token) => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
}
};
var scan = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished7 = false;
let braces = 0;
let prev;
let code;
let token = { value: "", depth: 0, isGlob: false };
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) {
braceEscaped = true;
}
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished7 = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished7 = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished7 = true;
break;
}
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = { value: "", depth: 0, isGlob: false };
if (finished7 === true)
continue;
if (prev === CHAR_DOT && index === start + 1) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished7 = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) {
negatedExtglob = true;
}
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished7 = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK)
isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished7 = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished7 = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished7 = true;
break;
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished7 = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished7 = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base2 = str;
let prefix = "";
let glob = "";
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base2 && isGlob === true && lastIndex > 0) {
base2 = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base2 = "";
glob = str;
} else {
base2 = str;
}
if (base2 && base2 !== "" && base2 !== "/" && base2 !== str) {
if (isPathSeparator(base2.charCodeAt(base2.length - 1))) {
base2 = base2.slice(0, -1);
}
}
if (opts.unescape === true) {
if (glob)
glob = utils.removeBackslashes(glob);
if (base2 && backslashes === true) {
base2 = utils.removeBackslashes(base2);
}
}
const state3 = {
prefix,
input,
start,
base: base2,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state3.maxDepth = 0;
if (!isPathSeparator(code)) {
tokens.push(token);
}
state3.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0;idx < slashes.length; idx++) {
const n2 = prevIndex ? prevIndex + 1 : start;
const i4 = slashes[idx];
const value = input.slice(n2, i4);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value;
}
depth(tokens[idx]);
state3.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== "") {
parts.push(value);
}
prevIndex = i4;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state3.maxDepth += tokens[tokens.length - 1].depth;
}
}
state3.slashes = slashes;
state3.parts = parts;
}
return state3;
};
module.exports = scan;
});
// node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/parse.js
var require_parse6 = __commonJS((exports, module) => {
var constants5 = require_constants10();
var utils = require_utils9();
var {
MAX_LENGTH,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants5;
var expandRange = (args, options) => {
if (typeof options.expandRange === "function") {
return options.expandRange(...args, options);
}
args.sort();
const value = `[${args.join("-")}]`;
try {
new RegExp(value);
} catch (ex) {
return args.map((v2) => utils.escapeRegex(v2)).join("..");
}
return value;
};
var syntaxError = (type, char) => {
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
};
var splitTopLevel = (input) => {
const parts = [];
let bracket = 0;
let paren = 0;
let quote = 0;
let value = "";
let escaped = false;
for (const ch2 of input) {
if (escaped === true) {
value += ch2;
escaped = false;
continue;
}
if (ch2 === "\\") {
value += ch2;
escaped = true;
continue;
}
if (ch2 === '"') {
quote = quote === 1 ? 0 : 1;
value += ch2;
continue;
}
if (quote === 0) {
if (ch2 === "[") {
bracket++;
} else if (ch2 === "]" && bracket > 0) {
bracket--;
} else if (bracket === 0) {
if (ch2 === "(") {
paren++;
} else if (ch2 === ")" && paren > 0) {
paren--;
} else if (ch2 === "|" && paren === 0) {
parts.push(value);
value = "";
continue;
}
}
}
value += ch2;
}
parts.push(value);
return parts;
};
var isPlainBranch = (branch) => {
let escaped = false;
for (const ch2 of branch) {
if (escaped === true) {
escaped = false;
continue;
}
if (ch2 === "\\") {
escaped = true;
continue;
}
if (/[?*+@!()[\]{}]/.test(ch2)) {
return false;
}
}
return true;
};
var normalizeSimpleBranch = (branch) => {
let value = branch.trim();
let changed = true;
while (changed === true) {
changed = false;
if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
value = value.slice(2, -1);
changed = true;
}
}
if (!isPlainBranch(value)) {
return;
}
return value.replace(/\\(.)/g, "$1");
};
var hasRepeatedCharPrefixOverlap = (branches) => {
const values2 = branches.map(normalizeSimpleBranch).filter(Boolean);
for (let i4 = 0;i4 < values2.length; i4++) {
for (let j2 = i4 + 1;j2 < values2.length; j2++) {
const a2 = values2[i4];
const b3 = values2[j2];
const char = a2[0];
if (!char || a2 !== char.repeat(a2.length) || b3 !== char.repeat(b3.length)) {
continue;
}
if (a2 === b3 || a2.startsWith(b3) || b3.startsWith(a2)) {
return true;
}
}
}
return false;
};
var parseRepeatedExtglob = (pattern, requireEnd = true) => {
if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") {
return;
}
let bracket = 0;
let paren = 0;
let quote = 0;
let escaped = false;
for (let i4 = 1;i4 < pattern.length; i4++) {
const ch2 = pattern[i4];
if (escaped === true) {
escaped = false;
continue;
}
if (ch2 === "\\") {
escaped = true;
continue;
}
if (ch2 === '"') {
quote = quote === 1 ? 0 : 1;
continue;
}
if (quote === 1) {
continue;
}
if (ch2 === "[") {
bracket++;
continue;
}
if (ch2 === "]" && bracket > 0) {
bracket--;
continue;
}
if (bracket > 0) {
continue;
}
if (ch2 === "(") {
paren++;
continue;
}
if (ch2 === ")") {
paren--;
if (paren === 0) {
if (requireEnd === true && i4 !== pattern.length - 1) {
return;
}
return {
type: pattern[0],
body: pattern.slice(2, i4),
end: i4
};
}
}
}
};
var getStarExtglobSequenceOutput = (pattern) => {
let index = 0;
const chars = [];
while (index < pattern.length) {
const match = parseRepeatedExtglob(pattern.slice(index), false);
if (!match || match.type !== "*") {
return;
}
const branches = splitTopLevel(match.body).map((branch2) => branch2.trim());
if (branches.length !== 1) {
return;
}
const branch = normalizeSimpleBranch(branches[0]);
if (!branch || branch.length !== 1) {
return;
}
chars.push(branch);
index += match.end + 1;
}
if (chars.length < 1) {
return;
}
const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch2) => utils.escapeRegex(ch2)).join("")}]`;
return `${source}*`;
};
var repeatedExtglobRecursion = (pattern) => {
let depth = 0;
let value = pattern.trim();
let match = parseRepeatedExtglob(value);
while (match) {
depth++;
value = match.body.trim();
match = parseRepeatedExtglob(value);
}
return depth;
};
var analyzeRepeatedExtglob = (body, options) => {
if (options.maxExtglobRecursion === false) {
return { risky: false };
}
const max2 = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants5.DEFAULT_MAX_EXTGLOB_RECURSION;
const branches = splitTopLevel(body).map((branch) => branch.trim());
if (branches.length > 1) {
if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) {
return { risky: true };
}
}
for (const branch of branches) {
const safeOutput = getStarExtglobSequenceOutput(branch);
if (safeOutput) {
return { risky: true, safeOutput };
}
if (repeatedExtglobRecursion(branch) > max2) {
return { risky: true };
}
}
return { risky: false };
};
var parse9 = (input, options) => {
if (typeof input !== "string") {
throw new TypeError("Expected a string");
}
input = REPLACEMENTS[input] || input;
const opts = { ...options };
const max2 = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
let len = input.length;
if (len > max2) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max2}`);
}
const bos = { type: "bos", value: "", output: opts.prepend || "" };
const tokens = [bos];
const capture = opts.capture ? "" : "?:";
const PLATFORM_CHARS = constants5.globChars(opts.windows);
const EXTGLOB_CHARS = constants5.extglobChars(PLATFORM_CHARS);
const {
DOT_LITERAL,
PLUS_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK,
QMARK_NO_DOT,
STAR,
START_ANCHOR
} = PLATFORM_CHARS;
const globstar = (opts2) => {
return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
const nodot = opts.dot ? "" : NO_DOT;
const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
let star = opts.bash === true ? globstar(opts) : STAR;
if (opts.capture) {
star = `(${star})`;
}
if (typeof opts.noext === "boolean") {
opts.noextglob = opts.noext;
}
const state3 = {
input,
index: -1,
start: 0,
dot: opts.dot === true,
consumed: "",
output: "",
prefix: "",
backtrack: false,
negated: false,
brackets: 0,
braces: 0,
parens: 0,
quotes: 0,
globstar: false,
tokens
};
input = utils.removePrefix(input, state3);
len = input.length;
const extglobs = [];
const braces = [];
const stack = [];
let prev = bos;
let value;
const eos = () => state3.index === len - 1;
const peek = state3.peek = (n2 = 1) => input[state3.index + n2];
const advance = state3.advance = () => input[++state3.index] || "";
const remaining = () => input.slice(state3.index + 1);
const consume = (value2 = "", num = 0) => {
state3.consumed += value2;
state3.index += num;
};
const append2 = (token) => {
state3.output += token.output != null ? token.output : token.value;
consume(token.value);
};
const negate = () => {
let count3 = 1;
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
advance();
state3.start++;
count3++;
}
if (count3 % 2 === 0) {
return false;
}
state3.negated = true;
state3.start++;
return true;
};
const increment2 = (type) => {
state3[type]++;
stack.push(type);
};
const decrement = (type) => {
state3[type]--;
stack.pop();
};
const push = (tok) => {
if (prev.type === "globstar") {
const isBrace = state3.braces > 0 && (tok.type === "comma" || tok.type === "brace");
const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
state3.output = state3.output.slice(0, -prev.output.length);
prev.type = "star";
prev.value = "*";
prev.output = star;
state3.output += prev.output;
}
}
if (extglobs.length && tok.type !== "paren") {
extglobs[extglobs.length - 1].inner += tok.value;
}
if (tok.value || tok.output)
append2(tok);
if (prev && prev.type === "text" && tok.type === "text") {
prev.output = (prev.output || prev.value) + tok.value;
prev.value += tok.value;
return;
}
tok.prev = prev;
tokens.push(tok);
prev = tok;
};
const extglobOpen = (type, value2) => {
const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
token.prev = prev;
token.parens = state3.parens;
token.output = state3.output;
token.startIndex = state3.index;
token.tokensIndex = tokens.length;
const output = (opts.capture ? "(" : "") + token.open;
increment2("parens");
push({ type, value: value2, output: state3.output ? "" : ONE_CHAR });
push({ type: "paren", extglob: true, value: advance(), output });
extglobs.push(token);
};
const extglobClose = (token) => {
const literal2 = input.slice(token.startIndex, state3.index + 1);
const body = input.slice(token.startIndex + 2, state3.index);
const analysis = analyzeRepeatedExtglob(body, opts);
if ((token.type === "plus" || token.type === "star") && analysis.risky) {
const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : undefined;
const open6 = tokens[token.tokensIndex];
open6.type = "text";
open6.value = literal2;
open6.output = safeOutput || utils.escapeRegex(literal2);
for (let i4 = token.tokensIndex + 1;i4 < tokens.length; i4++) {
tokens[i4].value = "";
tokens[i4].output = "";
delete tokens[i4].suffix;
}
state3.output = token.output + open6.output;
state3.backtrack = true;
push({ type: "paren", extglob: true, value, output: "" });
decrement("parens");
return;
}
let output = token.close + (opts.capture ? ")" : "");
let rest;
if (token.type === "negate") {
let extglobStar = star;
if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
extglobStar = globstar(opts);
}
if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
output = token.close = `)$))${extglobStar}`;
}
if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
const expression = parse9(rest, { ...options, fastpaths: false }).output;
output = token.close = `)${expression})${extglobStar})`;
}
if (token.prev.type === "bos") {
state3.negatedExtglob = true;
}
}
push({ type: "paren", extglob: true, value, output });
decrement("parens");
};
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m3, esc2, chars, first, rest, index) => {
if (first === "\\") {
backslashes = true;
return m3;
}
if (first === "?") {
if (esc2) {
return esc2 + first + (rest ? QMARK.repeat(rest.length) : "");
}
if (index === 0) {
return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
}
return QMARK.repeat(chars.length);
}
if (first === ".") {
return DOT_LITERAL.repeat(chars.length);
}
if (first === "*") {
if (esc2) {
return esc2 + first + (rest ? star : "");
}
return star;
}
return esc2 ? m3 : `\\${m3}`;
});
if (backslashes === true) {
if (opts.unescape === true) {
output = output.replace(/\\/g, "");
} else {
output = output.replace(/\\+/g, (m3) => {
return m3.length % 2 === 0 ? "\\\\" : m3 ? "\\" : "";
});
}
}
if (output === input && opts.contains === true) {
state3.output = input;
return state3;
}
state3.output = utils.wrapOutput(output, state3, options);
return state3;
}
while (!eos()) {
value = advance();
if (value === "\x00") {
continue;
}
if (value === "\\") {
const next = peek();
if (next === "/" && opts.bash !== true) {
continue;
}
if (next === "." || next === ";") {
continue;
}
if (!next) {
value += "\\";
push({ type: "text", value });
continue;
}
const match = /^\\+/.exec(remaining());
let slashes = 0;
if (match && match[0].length > 2) {
slashes = match[0].length;
state3.index += slashes;
if (slashes % 2 !== 0) {
value += "\\";
}
}
if (opts.unescape === true) {
value = advance();
} else {
value += advance();
}
if (state3.brackets === 0) {
push({ type: "text", value });
continue;
}
}
if (state3.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
if (opts.posix !== false && value === ":") {
const inner = prev.value.slice(1);
if (inner.includes("[")) {
prev.posix = true;
if (inner.includes(":")) {
const idx = prev.value.lastIndexOf("[");
const pre = prev.value.slice(0, idx);
const rest2 = prev.value.slice(idx + 2);
const posix = POSIX_REGEX_SOURCE[rest2];
if (posix) {
prev.value = pre + posix;
state3.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) {
bos.output = ONE_CHAR;
}
continue;
}
}
}
}
if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
value = `\\${value}`;
}
if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
value = `\\${value}`;
}
if (opts.posix === true && value === "!" && prev.value === "[") {
value = "^";
}
prev.value += value;
append2({ value });
continue;
}
if (state3.quotes === 1 && value !== '"') {
value = utils.escapeRegex(value);
prev.value += value;
append2({ value });
continue;
}
if (value === '"') {
state3.quotes = state3.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) {
push({ type: "text", value });
}
continue;
}
if (value === "(") {
increment2("parens");
push({ type: "paren", value });
continue;
}
if (value === ")") {
if (state3.parens === 0 && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("opening", "("));
}
const extglob = extglobs[extglobs.length - 1];
if (extglob && state3.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
}
push({ type: "paren", value, output: state3.parens ? ")" : "\\)" });
decrement("parens");
continue;
}
if (value === "[") {
if (opts.nobracket === true || !remaining().includes("]")) {
if (opts.nobracket !== true && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("closing", "]"));
}
value = `\\${value}`;
} else {
increment2("brackets");
}
push({ type: "bracket", value });
continue;
}
if (value === "]") {
if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
push({ type: "text", value, output: `\\${value}` });
continue;
}
if (state3.brackets === 0) {
if (opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("opening", "["));
}
push({ type: "text", value, output: `\\${value}` });
continue;
}
decrement("brackets");
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
value = `/${value}`;
}
prev.value += value;
append2({ value });
if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
continue;
}
const escaped = utils.escapeRegex(prev.value);
state3.output = state3.output.slice(0, -prev.value.length);
if (opts.literalBrackets === true) {
state3.output += escaped;
prev.value = escaped;
continue;
}
prev.value = `(${capture}${escaped}|${prev.value})`;
state3.output += prev.value;
continue;
}
if (value === "{" && opts.nobrace !== true) {
increment2("braces");
const open6 = {
type: "brace",
value,
output: "(",
outputIndex: state3.output.length,
tokensIndex: state3.tokens.length
};
braces.push(open6);
push(open6);
continue;
}
if (value === "}") {
const brace = braces[braces.length - 1];
if (opts.nobrace === true || !brace) {
push({ type: "text", value, output: value });
continue;
}
let output = ")";
if (brace.dots === true) {
const arr = tokens.slice();
const range = [];
for (let i4 = arr.length - 1;i4 >= 0; i4--) {
tokens.pop();
if (arr[i4].type === "brace") {
break;
}
if (arr[i4].type !== "dots") {
range.unshift(arr[i4].value);
}
}
output = expandRange(range, opts);
state3.backtrack = true;
}
if (brace.comma !== true && brace.dots !== true) {
const out = state3.output.slice(0, brace.outputIndex);
const toks = state3.tokens.slice(brace.tokensIndex);
brace.value = brace.output = "\\{";
value = output = "\\}";
state3.output = out;
for (const t2 of toks) {
state3.output += t2.output || t2.value;
}
}
push({ type: "brace", value, output });
decrement("braces");
braces.pop();
continue;
}
if (value === "|") {
if (extglobs.length > 0) {
extglobs[extglobs.length - 1].conditions++;
}
push({ type: "text", value });
continue;
}
if (value === ",") {
let output = value;
const brace = braces[braces.length - 1];
if (brace && stack[stack.length - 1] === "braces") {
brace.comma = true;
output = "|";
}
push({ type: "comma", value, output });
continue;
}
if (value === "/") {
if (prev.type === "dot" && state3.index === state3.start + 1) {
state3.start = state3.index + 1;
state3.consumed = "";
state3.output = "";
tokens.pop();
prev = bos;
continue;
}
push({ type: "slash", value, output: SLASH_LITERAL });
continue;
}
if (value === ".") {
if (state3.braces > 0 && prev.type === "dot") {
if (prev.value === ".")
prev.output = DOT_LITERAL;
const brace = braces[braces.length - 1];
prev.type = "dots";
prev.output += value;
prev.value += value;
brace.dots = true;
continue;
}
if (state3.braces + state3.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
push({ type: "text", value, output: DOT_LITERAL });
continue;
}
push({ type: "dot", value, output: DOT_LITERAL });
continue;
}
if (value === "?") {
const isGroup = prev && prev.value === "(";
if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("qmark", value);
continue;
}
if (prev && prev.type === "paren") {
const next = peek();
let output = value;
if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
output = `\\${value}`;
}
push({ type: "text", value, output });
continue;
}
if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
push({ type: "qmark", value, output: QMARK_NO_DOT });
continue;
}
push({ type: "qmark", value, output: QMARK });
continue;
}
if (value === "!") {
if (opts.noextglob !== true && peek() === "(") {
if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
extglobOpen("negate", value);
continue;
}
}
if (opts.nonegate !== true && state3.index === 0) {
negate();
continue;
}
}
if (value === "+") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("plus", value);
continue;
}
if (prev && prev.value === "(" || opts.regex === false) {
push({ type: "plus", value, output: PLUS_LITERAL });
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state3.parens > 0) {
push({ type: "plus", value });
continue;
}
push({ type: "plus", value: PLUS_LITERAL });
continue;
}
if (value === "@") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
push({ type: "at", extglob: true, value, output: "" });
continue;
}
push({ type: "text", value });
continue;
}
if (value !== "*") {
if (value === "$" || value === "^") {
value = `\\${value}`;
}
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match) {
value += match[0];
state3.index += match[0].length;
}
push({ type: "text", value });
continue;
}
if (prev && (prev.type === "globstar" || prev.star === true)) {
prev.type = "star";
prev.star = true;
prev.value += value;
prev.output = star;
state3.backtrack = true;
state3.globstar = true;
consume(value);
continue;
}
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen("star", value);
continue;
}
if (prev.type === "star") {
if (opts.noglobstar === true) {
consume(value);
continue;
}
const prior = prev.prev;
const before = prior.prev;
const isStart = prior.type === "slash" || prior.type === "bos";
const afterStar = before && (before.type === "star" || before.type === "globstar");
if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
push({ type: "star", value, output: "" });
continue;
}
const isBrace = state3.braces > 0 && (prior.type === "comma" || prior.type === "brace");
const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
push({ type: "star", value, output: "" });
continue;
}
while (rest.slice(0, 3) === "/**") {
const after = input[state3.index + 4];
if (after && after !== "/") {
break;
}
rest = rest.slice(3);
consume("/**", 3);
}
if (prior.type === "bos" && eos()) {
prev.type = "globstar";
prev.value += value;
prev.output = globstar(opts);
state3.output = prev.output;
state3.globstar = true;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
state3.output = state3.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
prev.value += value;
state3.globstar = true;
state3.output += prior.output + prev.output;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
const end = rest[1] !== undefined ? "|$" : "";
state3.output = state3.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
prev.value += value;
state3.output += prior.output + prev.output;
state3.globstar = true;
consume(value + advance());
push({ type: "slash", value: "/", output: "" });
continue;
}
if (prior.type === "bos" && rest[0] === "/") {
prev.type = "globstar";
prev.value += value;
prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
state3.output = prev.output;
state3.globstar = true;
consume(value + advance());
push({ type: "slash", value: "/", output: "" });
continue;
}
state3.output = state3.output.slice(0, -prev.output.length);
prev.type = "globstar";
prev.output = globstar(opts);
prev.value += value;
state3.output += prev.output;
state3.globstar = true;
consume(value);
continue;
}
const token = { type: "star", value, output: star };
if (opts.bash === true) {
token.output = ".*?";
if (prev.type === "bos" || prev.type === "slash") {
token.output = nodot + token.output;
}
push(token);
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
token.output = value;
push(token);
continue;
}
if (state3.index === state3.start || prev.type === "slash" || prev.type === "dot") {
if (prev.type === "dot") {
state3.output += NO_DOT_SLASH;
prev.output += NO_DOT_SLASH;
} else if (opts.dot === true) {
state3.output += NO_DOTS_SLASH;
prev.output += NO_DOTS_SLASH;
} else {
state3.output += nodot;
prev.output += nodot;
}
if (peek() !== "*") {
state3.output += ONE_CHAR;
prev.output += ONE_CHAR;
}
}
push(token);
}
while (state3.brackets > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", "]"));
state3.output = utils.escapeLast(state3.output, "[");
decrement("brackets");
}
while (state3.parens > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", ")"));
state3.output = utils.escapeLast(state3.output, "(");
decrement("parens");
}
while (state3.braces > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", "}"));
state3.output = utils.escapeLast(state3.output, "{");
decrement("braces");
}
if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` });
}
if (state3.backtrack === true) {
state3.output = "";
for (const token of state3.tokens) {
state3.output += token.output != null ? token.output : token.value;
if (token.suffix) {
state3.output += token.suffix;
}
}
}
return state3;
};
parse9.fastpaths = (input, options) => {
const opts = { ...options };
const max2 = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
const len = input.length;
if (len > max2) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max2}`);
}
input = REPLACEMENTS[input] || input;
const {
DOT_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOTS_SLASH,
STAR,
START_ANCHOR
} = constants5.globChars(opts.windows);
const nodot = opts.dot ? NO_DOTS : NO_DOT;
const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
const capture = opts.capture ? "" : "?:";
const state3 = { negated: false, prefix: "" };
let star = opts.bash === true ? ".*?" : STAR;
if (opts.capture) {
star = `(${star})`;
}
const globstar = (opts2) => {
if (opts2.noglobstar === true)
return star;
return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
const create = (str) => {
switch (str) {
case "*":
return `${nodot}${ONE_CHAR}${star}`;
case ".*":
return `${DOT_LITERAL}${ONE_CHAR}${star}`;
case "*.*":
return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case "*/*":
return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
case "**":
return nodot + globstar(opts);
case "**/*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
case "**/*.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case "**/.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
default: {
const match = /^(.*?)\.(\w+)$/.exec(str);
if (!match)
return;
const source2 = create(match[1]);
if (!source2)
return;
return source2 + DOT_LITERAL + match[2];
}
}
};
const output = utils.removePrefix(input, state3);
let source = create(output);
if (source && opts.strictSlashes !== true) {
source += `${SLASH_LITERAL}?`;
}
return source;
};
module.exports = parse9;
});
// node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/picomatch.js
var require_picomatch = __commonJS((exports, module) => {
var scan = require_scan();
var parse9 = require_parse6();
var utils = require_utils9();
var constants5 = require_constants10();
var isObject6 = (val) => val && typeof val === "object" && !Array.isArray(val);
var picomatch = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map((input) => picomatch(input, options, returnState));
const arrayMatcher = (str) => {
for (const isMatch of fns) {
const state4 = isMatch(str);
if (state4)
return state4;
}
return false;
};
return arrayMatcher;
}
const isState = isObject6(glob) && glob.tokens && glob.input;
if (glob === "" || typeof glob !== "string" && !isState) {
throw new TypeError("Expected pattern to be a non-empty string");
}
const opts = options || {};
const posix = opts.windows;
const regex2 = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
const state3 = regex2.state;
delete regex2.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.test(input, regex2, options, { glob, posix });
const result = { glob, state: state3, regex: regex2, posix, input, output, match, isMatch };
if (typeof opts.onResult === "function") {
opts.onResult(result);
}
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
if (isIgnored(input)) {
if (typeof opts.onIgnore === "function") {
opts.onIgnore(result);
}
result.isMatch = false;
return returnObject ? result : false;
}
if (typeof opts.onMatch === "function") {
opts.onMatch(result);
}
return returnObject ? result : true;
};
if (returnState) {
matcher.state = state3;
}
return matcher;
};
picomatch.test = (input, regex2, options, { glob, posix } = {}) => {
if (typeof input !== "string") {
throw new TypeError("Expected input to be a string");
}
if (input === "") {
return { isMatch: false, output: "" };
}
const opts = options || {};
const format4 = opts.format || (posix ? utils.toPosixSlashes : null);
let match = input === glob;
let output = match && format4 ? format4(input) : input;
if (match === false) {
output = format4 ? format4(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match = picomatch.matchBase(input, regex2, options, posix);
} else {
match = regex2.exec(output);
}
}
return { isMatch: Boolean(match), match, output };
};
picomatch.matchBase = (input, glob, options) => {
const regex2 = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex2.test(utils.basename(input));
};
picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
picomatch.parse = (pattern, options) => {
if (Array.isArray(pattern))
return pattern.map((p) => picomatch.parse(p, options));
return parse9(pattern, { ...options, fastpaths: false });
};
picomatch.scan = (input, options) => scan(input, options);
picomatch.compileRe = (state3, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state3.output;
}
const opts = options || {};
const prepend = opts.contains ? "" : "^";
const append2 = opts.contains ? "" : "$";
let source = `${prepend}(?:${state3.output})${append2}`;
if (state3 && state3.negated === true) {
source = `^(?!${source}).*$`;
}
const regex2 = picomatch.toRegex(source, options);
if (returnState === true) {
regex2.state = state3;
}
return regex2;
};
picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== "string") {
throw new TypeError("Expected a non-empty string");
}
let parsed = { negated: false, fastpaths: true };
if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
parsed.output = parse9.fastpaths(input, options);
}
if (!parsed.output) {
parsed = parse9(input, options);
}
return picomatch.compileRe(parsed, options, returnOutput, returnState);
};
picomatch.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err2) {
if (options && options.debug === true)
throw err2;
return /$^/;
}
};
picomatch.constants = constants5;
module.exports = picomatch;
});
// node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/index.js
var require_picomatch2 = __commonJS((exports, module) => {
var pico = require_picomatch();
var utils = require_utils9();
function picomatch(glob, options, returnState = false) {
if (options && (options.windows === null || options.windows === undefined)) {
options = { ...options, windows: utils.isWindows() };
}
return pico(glob, options, returnState);
}
Object.assign(picomatch, pico);
module.exports = picomatch;
});
// src/utils/fileStateCache.ts
import { normalize as normalize7 } from "path";
class FileStateCache {
cache;
constructor(maxEntries, maxSizeBytes) {
this.cache = new L({
max: maxEntries,
maxSize: maxSizeBytes,
sizeCalculation: (value) => Math.max(1, Buffer.byteLength(value.content))
});
}
get(key) {
return this.cache.get(normalize7(key));
}
set(key, value) {
this.cache.set(normalize7(key), value);
return this;
}
has(key) {
return this.cache.has(normalize7(key));
}
delete(key) {
return this.cache.delete(normalize7(key));
}
clear() {
this.cache.clear();
}
get size() {
return this.cache.size;
}
get max() {
return this.cache.max;
}
get maxSize() {
return this.cache.maxSize;
}
get calculatedSize() {
return this.cache.calculatedSize;
}
keys() {
return this.cache.keys();
}
entries() {
return this.cache.entries();
}
dump() {
return this.cache.dump();
}
load(entries) {
this.cache.load(entries);
}
}
function createFileStateCacheWithSizeLimit(maxEntries, maxSizeBytes = DEFAULT_MAX_CACHE_SIZE_BYTES) {
return new FileStateCache(maxEntries, maxSizeBytes);
}
function cacheToObject(cache3) {
return Object.fromEntries(cache3.entries());
}
function cacheKeys(cache3) {
return Array.from(cache3.keys());
}
function cloneFileStateCache(cache3) {
const cloned = createFileStateCacheWithSizeLimit(cache3.max, cache3.maxSize);
cloned.load(cache3.dump());
return cloned;
}
function mergeFileStateCaches(first, second) {
const merged = cloneFileStateCache(first);
for (const [filePath, fileState] of second.entries()) {
const existing = merged.get(filePath);
if (!existing || fileState.timestamp > existing.timestamp) {
merged.set(filePath, fileState);
}
}
return merged;
}
var READ_FILE_STATE_CACHE_SIZE = 100, DEFAULT_MAX_CACHE_SIZE_BYTES;
var init_fileStateCache = __esm(() => {
init_index_min();
DEFAULT_MAX_CACHE_SIZE_BYTES = 25 * 1024 * 1024;
});
// src/utils/claudemd.ts
import {
basename as basename10,
dirname as dirname19,
extname as extname4,
isAbsolute as isAbsolute8,
join as join36,
parse as parse9,
relative as relative5,
sep as sep8
} from "path";
function pathInOriginalCwd(path14) {
return pathInWorkingPath(path14, getOriginalCwd());
}
function parseFrontmatterPaths(rawContent2) {
const { frontmatter, content } = parseFrontmatter(rawContent2);
if (!frontmatter.paths) {
return { content };
}
const patterns = splitPathInFrontmatter(frontmatter.paths).map((pattern) => {
return pattern.endsWith("/**") ? pattern.slice(0, -3) : pattern;
}).filter((p) => p.length > 0);
if (patterns.length === 0 || patterns.every((p) => p === "**")) {
return { content };
}
return { content, paths: patterns };
}
function stripHtmlCommentsFromTokens(tokens) {
let result = "";
let stripped = false;
const commentSpan = //g;
for (const token of tokens) {
if (token.type === "html") {
const trimmed = token.raw.trimStart();
if (trimmed.startsWith("")) {
const residue = token.raw.replace(commentSpan, "");
stripped = true;
if (residue.trim().length > 0) {
result += residue;
}
continue;
}
}
result += token.raw;
}
return { content: result, stripped };
}
function parseMemoryFileContent(rawContent2, filePath, type, includeBasePath) {
const ext = extname4(filePath).toLowerCase();
if (ext && !TEXT_FILE_EXTENSIONS.has(ext)) {
logForDebugging(`Skipping non-text file in @include: ${filePath}`);
return { info: null, includePaths: [] };
}
const { content: withoutFrontmatter, paths: paths2 } = parseFrontmatterPaths(rawContent2);
const hasComment = withoutFrontmatter.includes("")) {
const commentSpan = //g;
const residue = raw.replace(commentSpan, "");
if (residue.trim().length > 0) {
extractPathsFromText(residue);
}
}
continue;
}
if (element.type === "text") {
extractPathsFromText(element.text || "");
}
if (element.tokens) {
processElements(element.tokens);
}
if (element.items) {
processElements(element.items);
}
}
}
processElements(tokens);
return [...absolutePaths];
}
function isClaudeMdExcluded(filePath, type) {
if (type !== "User" && type !== "Project" && type !== "Local") {
return false;
}
const patterns = getInitialSettings().claudeMdExcludes;
if (!patterns || patterns.length === 0) {
return false;
}
const matchOpts = { dot: true };
const normalizedPath = filePath.replaceAll("\\", "/");
const expandedPatterns = resolveExcludePatterns(patterns).filter((p) => p.length > 0);
if (expandedPatterns.length === 0) {
return false;
}
return import_picomatch.default.isMatch(normalizedPath, expandedPatterns, matchOpts);
}
function resolveExcludePatterns(patterns) {
const fs8 = getFsImplementation();
const expanded = patterns.map((p) => p.replaceAll("\\", "/"));
for (const normalized of expanded) {
if (!normalized.startsWith("/")) {
continue;
}
const globStart = normalized.search(/[*?{[]/);
const staticPrefix = globStart === -1 ? normalized : normalized.slice(0, globStart);
const dirToResolve = dirname19(staticPrefix);
try {
const resolvedDir = fs8.realpathSync(dirToResolve).replaceAll("\\", "/");
if (resolvedDir !== dirToResolve) {
const resolvedPattern = resolvedDir + normalized.slice(dirToResolve.length);
expanded.push(resolvedPattern);
}
} catch {}
}
return expanded;
}
async function processMemoryFile(filePath, type, processedPaths, includeExternal, depth = 0, parent) {
const normalizedPath = normalizePathForComparison(filePath);
if (processedPaths.has(normalizedPath) || depth >= MAX_INCLUDE_DEPTH) {
return [];
}
if (isClaudeMdExcluded(filePath, type)) {
return [];
}
const { resolvedPath, isSymlink } = safeResolvePath(getFsImplementation(), filePath);
processedPaths.add(normalizedPath);
if (isSymlink) {
processedPaths.add(normalizePathForComparison(resolvedPath));
}
const { info: memoryFile, includePaths: resolvedIncludePaths } = await safelyReadMemoryFileAsync(filePath, type, resolvedPath);
if (!memoryFile || !memoryFile.content.trim()) {
return [];
}
if (parent) {
memoryFile.parent = parent;
}
const result = [];
result.push(memoryFile);
for (const resolvedIncludePath of resolvedIncludePaths) {
const isExternal = !pathInOriginalCwd(resolvedIncludePath);
if (isExternal && !includeExternal) {
continue;
}
const includedFiles = await processMemoryFile(resolvedIncludePath, type, processedPaths, includeExternal, depth + 1, filePath);
result.push(...includedFiles);
}
return result;
}
async function processMdRules({
rulesDir,
type,
processedPaths,
includeExternal,
conditionalRule,
visitedDirs = new Set
}) {
if (visitedDirs.has(rulesDir)) {
return [];
}
try {
const fs8 = getFsImplementation();
const { resolvedPath: resolvedRulesDir, isSymlink } = safeResolvePath(fs8, rulesDir);
visitedDirs.add(rulesDir);
if (isSymlink) {
visitedDirs.add(resolvedRulesDir);
}
const result = [];
let entries;
try {
entries = await fs8.readdir(resolvedRulesDir);
} catch (e2) {
const code = getErrnoCode(e2);
if (code === "ENOENT" || code === "EACCES" || code === "ENOTDIR") {
return [];
}
throw e2;
}
for (const entry of entries) {
const entryPath = join36(rulesDir, entry.name);
const { resolvedPath: resolvedEntryPath, isSymlink: isSymlink2 } = safeResolvePath(fs8, entryPath);
const stats = isSymlink2 ? await fs8.stat(resolvedEntryPath) : null;
const isDirectory = stats ? stats.isDirectory() : entry.isDirectory();
const isFile2 = stats ? stats.isFile() : entry.isFile();
if (isDirectory) {
result.push(...await processMdRules({
rulesDir: resolvedEntryPath,
type,
processedPaths,
includeExternal,
conditionalRule,
visitedDirs
}));
} else if (isFile2 && entry.name.endsWith(".md")) {
const files = await processMemoryFile(resolvedEntryPath, type, processedPaths, includeExternal);
result.push(...files.filter((f3) => conditionalRule ? f3.globs : !f3.globs));
}
}
return result;
} catch (error52) {
if (error52 instanceof Error && error52.message.includes("EACCES")) {
logEvent("tengu_claude_rules_md_permission_error", {
is_access_error: 1,
has_home_dir: rulesDir.includes(getClaudeConfigHomeDir()) ? 1 : 0
});
}
return [];
}
}
function isInstructionsMemoryType(type) {
return type === "User" || type === "Project" || type === "Local" || type === "Managed";
}
function consumeNextEagerLoadReason() {
if (!shouldFireHook)
return;
shouldFireHook = false;
const reason = nextEagerLoadReason;
nextEagerLoadReason = "session_start";
return reason;
}
function clearMemoryFileCaches() {
getMemoryFiles.cache?.clear?.();
}
function resetGetMemoryFilesCache(reason = "session_start") {
nextEagerLoadReason = reason;
shouldFireHook = true;
clearMemoryFileCaches();
}
function getLargeMemoryFiles(files) {
return files.filter((f3) => f3.content.length > MAX_MEMORY_CHARACTER_COUNT);
}
function filterInjectedMemoryFiles(files) {
const skipMemoryIndex = getFeatureValue_CACHED_MAY_BE_STALE("tengu_moth_copse", false);
if (!skipMemoryIndex)
return files;
return files.filter((f3) => f3.type !== "AutoMem" && f3.type !== "TeamMem");
}
async function getManagedAndUserConditionalRules(targetPath, processedPaths) {
const result = [];
const managedClaudeRulesDir = getManagedClaudeRulesDir();
result.push(...await processConditionedMdRules(targetPath, managedClaudeRulesDir, "Managed", processedPaths, false));
if (isSettingSourceEnabled("userSettings")) {
const userClaudeRulesDir = getUserClaudeRulesDir();
result.push(...await processConditionedMdRules(targetPath, userClaudeRulesDir, "User", processedPaths, true));
}
return result;
}
async function getMemoryFilesForNestedDirectory(dir, targetPath, processedPaths) {
const result = [];
if (isSettingSourceEnabled("projectSettings")) {
const projectPath = join36(dir, "CLAUDE.md");
result.push(...await processMemoryFile(projectPath, "Project", processedPaths, false));
const dotClaudePath = join36(dir, ".claude", "CLAUDE.md");
result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, false));
}
if (isSettingSourceEnabled("localSettings")) {
const localPath = join36(dir, "CLAUDE.local.md");
result.push(...await processMemoryFile(localPath, "Local", processedPaths, false));
}
const rulesDir = join36(dir, ".claude", "rules");
const unconditionalProcessedPaths = new Set(processedPaths);
result.push(...await processMdRules({
rulesDir,
type: "Project",
processedPaths: unconditionalProcessedPaths,
includeExternal: false,
conditionalRule: false
}));
result.push(...await processConditionedMdRules(targetPath, rulesDir, "Project", processedPaths, false));
for (const path14 of unconditionalProcessedPaths) {
processedPaths.add(path14);
}
return result;
}
async function getConditionalRulesForCwdLevelDirectory(dir, targetPath, processedPaths) {
const rulesDir = join36(dir, ".claude", "rules");
return processConditionedMdRules(targetPath, rulesDir, "Project", processedPaths, false);
}
async function processConditionedMdRules(targetPath, rulesDir, type, processedPaths, includeExternal) {
const conditionedRuleMdFiles = await processMdRules({
rulesDir,
type,
processedPaths,
includeExternal,
conditionalRule: true
});
return conditionedRuleMdFiles.filter((file2) => {
if (!file2.globs || file2.globs.length === 0) {
return false;
}
const baseDir = type === "Project" ? dirname19(dirname19(rulesDir)) : getOriginalCwd();
const relativePath = isAbsolute8(targetPath) ? relative5(baseDir, targetPath) : targetPath;
if (!relativePath || relativePath.startsWith("..") || isAbsolute8(relativePath)) {
return false;
}
return import_ignore.default().add(file2.globs).ignores(relativePath);
});
}
function getExternalClaudeMdIncludes(files) {
const externals = [];
for (const file2 of files) {
if (file2.type !== "User" && file2.parent && !pathInOriginalCwd(file2.path)) {
externals.push({ path: file2.path, parent: file2.parent });
}
}
return externals;
}
function hasExternalClaudeMdIncludes(files) {
return getExternalClaudeMdIncludes(files).length > 0;
}
async function shouldShowClaudeMdExternalIncludesWarning() {
const config2 = getCurrentProjectConfig();
if (config2.hasClaudeMdExternalIncludesApproved || config2.hasClaudeMdExternalIncludesWarningShown) {
return false;
}
return hasExternalClaudeMdIncludes(await getMemoryFiles(true));
}
var import_ignore, import_picomatch, hasLoggedInitialLoad = false, MEMORY_INSTRUCTION_PROMPT = "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.", MAX_MEMORY_CHARACTER_COUNT = 40000, TEXT_FILE_EXTENSIONS, MAX_INCLUDE_DEPTH = 5, getMemoryFiles, nextEagerLoadReason = "session_start", shouldFireHook = true, getClaudeMds = (memoryFiles, filter2) => {
const memories = [];
const skipProjectLevel = getFeatureValue_CACHED_MAY_BE_STALE("tengu_paper_halyard", false);
for (const file2 of memoryFiles) {
if (filter2 && !filter2(file2.type))
continue;
if (skipProjectLevel && (file2.type === "Project" || file2.type === "Local"))
continue;
if (file2.content) {
const description = file2.type === "Project" ? " (project instructions, checked into the codebase)" : file2.type === "Local" ? " (user's private project instructions, not checked in)" : file2.type === "AutoMem" ? " (user's auto-memory, persists across conversations)" : " (user's private global instructions for all projects)";
const content = file2.content.trim();
if (false) {} else {
memories.push(`Contents of ${file2.path}${description}:
${content}`);
}
}
}
if (memories.length === 0) {
return "";
}
return `${MEMORY_INSTRUCTION_PROMPT}
${memories.join(`
`)}`;
};
var init_claudemd = __esm(() => {
init_memoize();
init_marked_esm();
init_analytics();
init_state();
init_memdir();
init_paths();
init_growthbook();
init_config2();
init_debug();
init_diagLogs();
init_envUtils();
init_errors();
init_file();
init_fileStateCache();
init_frontmatterParser();
init_fsOperations();
init_git();
init_hooks5();
init_path2();
init_filesystem();
init_constants2();
init_settings2();
import_ignore = __toESM(require_ignore(), 1);
import_picomatch = __toESM(require_picomatch2(), 1);
TEXT_FILE_EXTENSIONS = new Set([
".md",
".txt",
".text",
".json",
".yaml",
".yml",
".toml",
".xml",
".csv",
".html",
".htm",
".css",
".scss",
".sass",
".less",
".js",
".ts",
".tsx",
".jsx",
".mjs",
".cjs",
".mts",
".cts",
".py",
".pyi",
".pyw",
".rb",
".erb",
".rake",
".go",
".rs",
".java",
".kt",
".kts",
".scala",
".c",
".cpp",
".cc",
".cxx",
".h",
".hpp",
".hxx",
".cs",
".swift",
".sh",
".bash",
".zsh",
".fish",
".ps1",
".bat",
".cmd",
".env",
".ini",
".cfg",
".conf",
".config",
".properties",
".sql",
".graphql",
".gql",
".proto",
".vue",
".svelte",
".astro",
".ejs",
".hbs",
".pug",
".jade",
".php",
".pl",
".pm",
".lua",
".r",
".R",
".dart",
".ex",
".exs",
".erl",
".hrl",
".clj",
".cljs",
".cljc",
".edn",
".hs",
".lhs",
".elm",
".ml",
".mli",
".f",
".f90",
".f95",
".for",
".cmake",
".make",
".makefile",
".gradle",
".sbt",
".rst",
".adoc",
".asciidoc",
".org",
".tex",
".latex",
".lock",
".log",
".diff",
".patch"
]);
getMemoryFiles = memoize_default(async (forceIncludeExternal = false) => {
const startTime = Date.now();
logForDiagnosticsNoPII("info", "memory_files_started");
const result = [];
const processedPaths = new Set;
const config2 = getCurrentProjectConfig();
const includeExternal = forceIncludeExternal || config2.hasClaudeMdExternalIncludesApproved || false;
const managedClaudeMd = getMemoryPath("Managed");
result.push(...await processMemoryFile(managedClaudeMd, "Managed", processedPaths, includeExternal));
const managedClaudeRulesDir = getManagedClaudeRulesDir();
result.push(...await processMdRules({
rulesDir: managedClaudeRulesDir,
type: "Managed",
processedPaths,
includeExternal,
conditionalRule: false
}));
if (isSettingSourceEnabled("userSettings")) {
const userClaudeMd = getMemoryPath("User");
result.push(...await processMemoryFile(userClaudeMd, "User", processedPaths, true));
const userClaudeRulesDir = getUserClaudeRulesDir();
result.push(...await processMdRules({
rulesDir: userClaudeRulesDir,
type: "User",
processedPaths,
includeExternal: true,
conditionalRule: false
}));
}
const dirs = [];
const originalCwd = getOriginalCwd();
let currentDir = originalCwd;
while (currentDir !== parse9(currentDir).root) {
dirs.push(currentDir);
currentDir = dirname19(currentDir);
}
const gitRoot = findGitRoot(originalCwd);
const canonicalRoot = findCanonicalGitRoot(originalCwd);
const isNestedWorktree = gitRoot !== null && canonicalRoot !== null && normalizePathForComparison(gitRoot) !== normalizePathForComparison(canonicalRoot) && pathInWorkingPath(gitRoot, canonicalRoot);
for (const dir of dirs.reverse()) {
const skipProject = isNestedWorktree && pathInWorkingPath(dir, canonicalRoot) && !pathInWorkingPath(dir, gitRoot);
if (isSettingSourceEnabled("projectSettings") && !skipProject) {
const projectPath = join36(dir, "CLAUDE.md");
result.push(...await processMemoryFile(projectPath, "Project", processedPaths, includeExternal));
const dotClaudePath = join36(dir, ".claude", "CLAUDE.md");
result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, includeExternal));
const rulesDir = join36(dir, ".claude", "rules");
result.push(...await processMdRules({
rulesDir,
type: "Project",
processedPaths,
includeExternal,
conditionalRule: false
}));
}
if (isSettingSourceEnabled("localSettings")) {
const localPath = join36(dir, "CLAUDE.local.md");
result.push(...await processMemoryFile(localPath, "Local", processedPaths, includeExternal));
}
}
if (isEnvTruthy(process.env.CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD)) {
const additionalDirs = getAdditionalDirectoriesForClaudeMd();
for (const dir of additionalDirs) {
const projectPath = join36(dir, "CLAUDE.md");
result.push(...await processMemoryFile(projectPath, "Project", processedPaths, includeExternal));
const dotClaudePath = join36(dir, ".claude", "CLAUDE.md");
result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, includeExternal));
const rulesDir = join36(dir, ".claude", "rules");
result.push(...await processMdRules({
rulesDir,
type: "Project",
processedPaths,
includeExternal,
conditionalRule: false
}));
}
}
if (isAutoMemoryEnabled()) {
const { info: memdirEntry } = await safelyReadMemoryFileAsync(getAutoMemEntrypoint(), "AutoMem");
if (memdirEntry) {
const normalizedPath = normalizePathForComparison(memdirEntry.path);
if (!processedPaths.has(normalizedPath)) {
processedPaths.add(normalizedPath);
result.push(memdirEntry);
}
}
}
if (false) {}
const totalContentLength = result.reduce((sum, f3) => sum + f3.content.length, 0);
logForDiagnosticsNoPII("info", "memory_files_completed", {
duration_ms: Date.now() - startTime,
file_count: result.length,
total_content_length: totalContentLength
});
const typeCounts = {};
for (const f3 of result) {
typeCounts[f3.type] = (typeCounts[f3.type] ?? 0) + 1;
}
if (!hasLoggedInitialLoad) {
hasLoggedInitialLoad = true;
logEvent("tengu_claudemd__initial_load", {
file_count: result.length,
total_content_length: totalContentLength,
user_count: typeCounts["User"] ?? 0,
project_count: typeCounts["Project"] ?? 0,
local_count: typeCounts["Local"] ?? 0,
managed_count: typeCounts["Managed"] ?? 0,
automem_count: typeCounts["AutoMem"] ?? 0,
...{},
duration_ms: Date.now() - startTime
});
}
if (!forceIncludeExternal) {
const eagerLoadReason = consumeNextEagerLoadReason();
if (eagerLoadReason !== undefined && hasInstructionsLoadedHook()) {
for (const file2 of result) {
if (!isInstructionsMemoryType(file2.type))
continue;
const loadReason = file2.parent ? "include" : eagerLoadReason;
executeInstructionsLoadedHooks(file2.path, file2.type, loadReason, {
globs: file2.globs,
parentFilePath: file2.parent
});
}
}
}
return result;
});
});
// src/utils/gitSettings.ts
function shouldIncludeGitInstructions() {
const envVal = process.env.CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS;
if (isEnvTruthy(envVal))
return false;
if (isEnvDefinedFalsy(envVal))
return true;
return getInitialSettings().includeGitInstructions ?? true;
}
var init_gitSettings = __esm(() => {
init_envUtils();
init_settings2();
});
// src/context.ts
function setSystemPromptInjection(value) {
systemPromptInjection = value;
getUserContext.cache.clear?.();
getSystemContext.cache.clear?.();
}
var MAX_STATUS_CHARS = 2000, systemPromptInjection = null, getGitStatus, getSystemContext, getUserContext;
var init_context2 = __esm(() => {
init_memoize();
init_state();
init_common();
init_claudemd();
init_diagLogs();
init_envUtils();
init_execFileNoThrow();
init_git();
init_gitSettings();
init_log3();
getGitStatus = memoize_default(async () => {
if (false) {}
const startTime = Date.now();
logForDiagnosticsNoPII("info", "git_status_started");
const isGitStart = Date.now();
const isGit = await getIsGit();
logForDiagnosticsNoPII("info", "git_is_git_check_completed", {
duration_ms: Date.now() - isGitStart,
is_git: isGit
});
if (!isGit) {
logForDiagnosticsNoPII("info", "git_status_skipped_not_git", {
duration_ms: Date.now() - startTime
});
return null;
}
try {
const gitCmdsStart = Date.now();
const [branch, mainBranch, status, log3, userName] = await Promise.all([
getBranch(),
getDefaultBranch(),
execFileNoThrow(gitExe(), ["--no-optional-locks", "status", "--short"], {
preserveOutputOnError: false
}).then(({ stdout }) => stdout.trim()),
execFileNoThrow(gitExe(), ["--no-optional-locks", "log", "--oneline", "-n", "5"], {
preserveOutputOnError: false
}).then(({ stdout }) => stdout.trim()),
execFileNoThrow(gitExe(), ["config", "user.name"], {
preserveOutputOnError: false
}).then(({ stdout }) => stdout.trim())
]);
logForDiagnosticsNoPII("info", "git_commands_completed", {
duration_ms: Date.now() - gitCmdsStart,
status_length: status.length
});
const truncatedStatus = status.length > MAX_STATUS_CHARS ? status.substring(0, MAX_STATUS_CHARS) + `
... (truncated because it exceeds 2k characters. If you need more information, run "git status" using BashTool)` : status;
logForDiagnosticsNoPII("info", "git_status_completed", {
duration_ms: Date.now() - startTime,
truncated: status.length > MAX_STATUS_CHARS
});
return [
`This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation.`,
`Current branch: ${branch}`,
`Main branch (you will usually use this for PRs): ${mainBranch}`,
...userName ? [`Git user: ${userName}`] : [],
`Status:
${truncatedStatus || "(clean)"}`,
`Recent commits:
${log3}`
].join(`
`);
} catch (error52) {
logForDiagnosticsNoPII("error", "git_status_failed", {
duration_ms: Date.now() - startTime
});
logError2(error52);
return null;
}
});
getSystemContext = memoize_default(async () => {
const startTime = Date.now();
logForDiagnosticsNoPII("info", "system_context_started");
const gitStatus = isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) || !shouldIncludeGitInstructions() ? null : await getGitStatus();
const injection = null;
logForDiagnosticsNoPII("info", "system_context_completed", {
duration_ms: Date.now() - startTime,
has_git_status: gitStatus !== null,
has_injection: injection !== null
});
return {
...gitStatus && { gitStatus },
...{}
};
});
getUserContext = memoize_default(async () => {
const startTime = Date.now();
logForDiagnosticsNoPII("info", "user_context_started");
const shouldDisableClaudeMd = isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS) || isBareMode() && getAdditionalDirectoriesForClaudeMd().length === 0;
const claudeMd = shouldDisableClaudeMd ? null : getClaudeMds(filterInjectedMemoryFiles(await getMemoryFiles()));
setCachedClaudeMdContent(claudeMd || null);
logForDiagnosticsNoPII("info", "user_context_completed", {
duration_ms: Date.now() - startTime,
claudemd_length: claudeMd?.length ?? 0,
claudemd_disabled: Boolean(shouldDisableClaudeMd)
});
return {
...claudeMd && { claudeMd },
currentDate: `Today's date is ${getLocalISODate()}.`
};
});
});
// src/utils/tokens.ts
function getTokenUsage(message) {
if (message?.type === "assistant" && "usage" in message.message && !(message.message.content[0]?.type === "text" && SYNTHETIC_MESSAGES.has(message.message.content[0].text)) && message.message.model !== SYNTHETIC_MODEL) {
return message.message.usage;
}
return;
}
function getAssistantMessageId(message) {
if (message?.type === "assistant" && "id" in message.message && message.message.model !== SYNTHETIC_MODEL) {
return message.message.id;
}
return;
}
function getTokenCountFromUsage(usage) {
return usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + usage.output_tokens;
}
function tokenCountFromLastAPIResponse(messages) {
let i4 = messages.length - 1;
while (i4 >= 0) {
const message = messages[i4];
const usage = message ? getTokenUsage(message) : undefined;
if (usage) {
return getTokenCountFromUsage(usage);
}
i4--;
}
return 0;
}
function finalContextTokensFromLastResponse(messages) {
let i4 = messages.length - 1;
while (i4 >= 0) {
const message = messages[i4];
const usage = message ? getTokenUsage(message) : undefined;
if (usage) {
const iterations = usage.iterations;
if (iterations && iterations.length > 0) {
const last2 = iterations.at(-1);
return last2.input_tokens + last2.output_tokens;
}
return usage.input_tokens + usage.output_tokens;
}
i4--;
}
return 0;
}
function getCurrentUsage(messages) {
for (let i4 = messages.length - 1;i4 >= 0; i4--) {
const message = messages[i4];
const usage = message ? getTokenUsage(message) : undefined;
if (usage) {
return {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
cache_read_input_tokens: usage.cache_read_input_tokens ?? 0
};
}
}
return null;
}
function doesMostRecentAssistantMessageExceed200k(messages) {
const THRESHOLD = 200000;
const lastAsst = messages.findLast((m3) => m3.type === "assistant");
if (!lastAsst)
return false;
const usage = getTokenUsage(lastAsst);
return usage ? getTokenCountFromUsage(usage) > THRESHOLD : false;
}
function getAssistantMessageContentLength(message) {
let contentLength = 0;
for (const block of message.message.content) {
if (block.type === "text") {
contentLength += block.text.length;
} else if (block.type === "thinking") {
contentLength += block.thinking.length;
} else if (block.type === "redacted_thinking") {
contentLength += block.data.length;
} else if (block.type === "tool_use") {
contentLength += jsonStringify(block.input).length;
}
}
return contentLength;
}
function tokenCountWithEstimation(messages) {
let i4 = messages.length - 1;
while (i4 >= 0) {
const message = messages[i4];
const usage = message ? getTokenUsage(message) : undefined;
if (message && usage) {
const responseId = getAssistantMessageId(message);
if (responseId) {
let j2 = i4 - 1;
while (j2 >= 0) {
const prior = messages[j2];
const priorId = prior ? getAssistantMessageId(prior) : undefined;
if (priorId === responseId) {
i4 = j2;
} else if (priorId !== undefined) {
break;
}
j2--;
}
}
return getTokenCountFromUsage(usage) + roughTokenCountEstimationForMessages(messages.slice(i4 + 1));
}
i4--;
}
return roughTokenCountEstimationForMessages(messages);
}
var init_tokens = __esm(() => {
init_tokenEstimation();
init_messages3();
init_slowOperations();
});
// src/services/SessionMemory/sessionMemoryUtils.ts
function getLastSummarizedMessageId() {
return lastSummarizedMessageId;
}
function setLastSummarizedMessageId(messageId) {
lastSummarizedMessageId = messageId;
}
function markExtractionStarted() {
extractionStartedAt = Date.now();
}
function markExtractionCompleted() {
extractionStartedAt = undefined;
}
async function waitForSessionMemoryExtraction() {
const startTime = Date.now();
while (extractionStartedAt) {
const extractionAge = Date.now() - extractionStartedAt;
if (extractionAge > EXTRACTION_STALE_THRESHOLD_MS) {
return;
}
if (Date.now() - startTime > EXTRACTION_WAIT_TIMEOUT_MS) {
return;
}
await sleep3(1000);
}
}
async function getSessionMemoryContent() {
const fs8 = getFsImplementation();
const memoryPath = getSessionMemoryPath();
try {
const content = await fs8.readFile(memoryPath, { encoding: "utf-8" });
logEvent("tengu_session_memory_loaded", {
content_length: content.length
});
return content;
} catch (e2) {
if (isFsInaccessible(e2))
return null;
throw e2;
}
}
function setSessionMemoryConfig(config2) {
sessionMemoryConfig = {
...sessionMemoryConfig,
...config2
};
}
function getSessionMemoryConfig() {
return { ...sessionMemoryConfig };
}
function recordExtractionTokenCount(currentTokenCount) {
tokensAtLastExtraction = currentTokenCount;
}
function isSessionMemoryInitialized() {
return sessionMemoryInitialized;
}
function markSessionMemoryInitialized() {
sessionMemoryInitialized = true;
}
function hasMetInitializationThreshold(currentTokenCount) {
return currentTokenCount >= sessionMemoryConfig.minimumMessageTokensToInit;
}
function hasMetUpdateThreshold(currentTokenCount) {
const tokensSinceLastExtraction = currentTokenCount - tokensAtLastExtraction;
return tokensSinceLastExtraction >= sessionMemoryConfig.minimumTokensBetweenUpdate;
}
function getToolCallsBetweenUpdates() {
return sessionMemoryConfig.toolCallsBetweenUpdates;
}
var EXTRACTION_WAIT_TIMEOUT_MS = 15000, EXTRACTION_STALE_THRESHOLD_MS = 60000, DEFAULT_SESSION_MEMORY_CONFIG, sessionMemoryConfig, lastSummarizedMessageId, extractionStartedAt, tokensAtLastExtraction = 0, sessionMemoryInitialized = false;
var init_sessionMemoryUtils = __esm(() => {
init_errors();
init_fsOperations();
init_filesystem();
init_analytics();
DEFAULT_SESSION_MEMORY_CONFIG = {
minimumMessageTokensToInit: 1e4,
minimumTokensBetweenUpdate: 5000,
toolCallsBetweenUpdates: 3
};
sessionMemoryConfig = {
...DEFAULT_SESSION_MEMORY_CONFIG
};
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseFindIndex.js
function baseFindIndex(array2, predicate, fromIndex, fromRight) {
var length = array2.length, index = fromIndex + (fromRight ? 1 : -1);
while (fromRight ? index-- : ++index < length) {
if (predicate(array2[index], index, array2)) {
return index;
}
}
return -1;
}
var _baseFindIndex_default;
var init__baseFindIndex = __esm(() => {
_baseFindIndex_default = baseFindIndex;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIsNaN.js
function baseIsNaN(value) {
return value !== value;
}
var _baseIsNaN_default;
var init__baseIsNaN = __esm(() => {
_baseIsNaN_default = baseIsNaN;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_strictIndexOf.js
function strictIndexOf(array2, value, fromIndex) {
var index = fromIndex - 1, length = array2.length;
while (++index < length) {
if (array2[index] === value) {
return index;
}
}
return -1;
}
var _strictIndexOf_default;
var init__strictIndexOf = __esm(() => {
_strictIndexOf_default = strictIndexOf;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseIndexOf.js
function baseIndexOf(array2, value, fromIndex) {
return value === value ? _strictIndexOf_default(array2, value, fromIndex) : _baseFindIndex_default(array2, _baseIsNaN_default, fromIndex);
}
var _baseIndexOf_default;
var init__baseIndexOf = __esm(() => {
init__baseFindIndex();
init__baseIsNaN();
init__strictIndexOf();
_baseIndexOf_default = baseIndexOf;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayIncludes.js
function arrayIncludes(array2, value) {
var length = array2 == null ? 0 : array2.length;
return !!length && _baseIndexOf_default(array2, value, 0) > -1;
}
var _arrayIncludes_default;
var init__arrayIncludes = __esm(() => {
init__baseIndexOf();
_arrayIncludes_default = arrayIncludes;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_arrayIncludesWith.js
function arrayIncludesWith(array2, value, comparator) {
var index = -1, length = array2 == null ? 0 : array2.length;
while (++index < length) {
if (comparator(value, array2[index])) {
return true;
}
}
return false;
}
var _arrayIncludesWith_default;
var init__arrayIncludesWith = __esm(() => {
_arrayIncludesWith_default = arrayIncludesWith;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_createSet.js
var INFINITY3, createSet, _createSet_default;
var init__createSet = __esm(() => {
init__Set();
init_noop();
init__setToArray();
INFINITY3 = 1 / 0;
createSet = !(_Set_default && 1 / _setToArray_default(new _Set_default([, -0]))[1] == INFINITY3) ? noop_default : function(values2) {
return new _Set_default(values2);
};
_createSet_default = createSet;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/_baseUniq.js
function baseUniq(array2, iteratee, comparator) {
var index = -1, includes = _arrayIncludes_default, length = array2.length, isCommon = true, result = [], seen = result;
if (comparator) {
isCommon = false;
includes = _arrayIncludesWith_default;
} else if (length >= LARGE_ARRAY_SIZE2) {
var set2 = iteratee ? null : _createSet_default(array2);
if (set2) {
return _setToArray_default(set2);
}
isCommon = false;
includes = _cacheHas_default;
seen = new _SetCache_default;
} else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array2[index], computed = iteratee ? iteratee(value) : value;
value = comparator || value !== 0 ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
} else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
var LARGE_ARRAY_SIZE2 = 200, _baseUniq_default;
var init__baseUniq = __esm(() => {
init__SetCache();
init__arrayIncludes();
init__arrayIncludesWith();
init__cacheHas();
init__createSet();
init__setToArray();
_baseUniq_default = baseUniq;
});
// node_modules/.pnpm/lodash-es@4.17.23/node_modules/lodash-es/uniqBy.js
function uniqBy(array2, iteratee) {
return array2 && array2.length ? _baseUniq_default(array2, _baseIteratee_default(iteratee, 2)) : [];
}
var uniqBy_default;
var init_uniqBy = __esm(() => {
init__baseIteratee();
init__baseUniq();
uniqBy_default = uniqBy;
});
// src/tools/ToolSearchTool/ToolSearchTool.ts
var exports_ToolSearchTool = {};
__export(exports_ToolSearchTool, {
outputSchema: () => outputSchema,
inputSchema: () => inputSchema,
clearToolSearchDescriptionCache: () => clearToolSearchDescriptionCache,
ToolSearchTool: () => ToolSearchTool
});
function getDeferredToolsCacheKey(deferredTools) {
return deferredTools.map((t2) => t2.name).sort().join(",");
}
function maybeInvalidateCache(deferredTools) {
const currentKey = getDeferredToolsCacheKey(deferredTools);
if (cachedDeferredToolNames !== currentKey) {
logForDebugging(`ToolSearchTool: cache invalidated - deferred tools changed`);
getToolDescriptionMemoized.cache.clear?.();
cachedDeferredToolNames = currentKey;
}
}
function clearToolSearchDescriptionCache() {
getToolDescriptionMemoized.cache.clear?.();
cachedDeferredToolNames = null;
}
function buildSearchResult(matches, query, totalDeferredTools, pendingMcpServers) {
return {
data: {
matches,
query,
total_deferred_tools: totalDeferredTools,
...pendingMcpServers && pendingMcpServers.length > 0 ? { pending_mcp_servers: pendingMcpServers } : {}
}
};
}
function parseToolName(name3) {
if (name3.startsWith("mcp__")) {
const withoutPrefix = name3.replace(/^mcp__/, "").toLowerCase();
const parts2 = withoutPrefix.split("__").flatMap((p) => p.split("_"));
return {
parts: parts2.filter(Boolean),
full: withoutPrefix.replace(/__/g, " ").replace(/_/g, " "),
isMcp: true
};
}
const parts = name3.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/_/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
return {
parts,
full: parts.join(" "),
isMcp: false
};
}
function compileTermPatterns(terms) {
const patterns = new Map;
for (const term of terms) {
if (!patterns.has(term)) {
patterns.set(term, new RegExp(`\\b${escapeRegExp(term)}\\b`));
}
}
return patterns;
}
async function searchToolsWithKeywords(query, deferredTools, tools, maxResults) {
const queryLower = query.toLowerCase().trim();
const exactMatch = deferredTools.find((t2) => t2.name.toLowerCase() === queryLower) ?? tools.find((t2) => t2.name.toLowerCase() === queryLower);
if (exactMatch) {
return [exactMatch.name];
}
if (queryLower.startsWith("mcp__") && queryLower.length > 5) {
const prefixMatches = deferredTools.filter((t2) => t2.name.toLowerCase().startsWith(queryLower)).slice(0, maxResults).map((t2) => t2.name);
if (prefixMatches.length > 0) {
return prefixMatches;
}
}
const queryTerms = queryLower.split(/\s+/).filter((term) => term.length > 0);
const requiredTerms = [];
const optionalTerms = [];
for (const term of queryTerms) {
if (term.startsWith("+") && term.length > 1) {
requiredTerms.push(term.slice(1));
} else {
optionalTerms.push(term);
}
}
const allScoringTerms = requiredTerms.length > 0 ? [...requiredTerms, ...optionalTerms] : queryTerms;
const termPatterns = compileTermPatterns(allScoringTerms);
let candidateTools = deferredTools;
if (requiredTerms.length > 0) {
const matches = await Promise.all(deferredTools.map(async (tool) => {
const parsed = parseToolName(tool.name);
const description = await getToolDescriptionMemoized(tool.name, tools);
const descNormalized = description.toLowerCase();
const hintNormalized = tool.searchHint?.toLowerCase() ?? "";
const matchesAll = requiredTerms.every((term) => {
const pattern = termPatterns.get(term);
return parsed.parts.includes(term) || parsed.parts.some((part) => part.includes(term)) || pattern.test(descNormalized) || hintNormalized && pattern.test(hintNormalized);
});
return matchesAll ? tool : null;
}));
candidateTools = matches.filter((t2) => t2 !== null);
}
const scored = await Promise.all(candidateTools.map(async (tool) => {
const parsed = parseToolName(tool.name);
const description = await getToolDescriptionMemoized(tool.name, tools);
const descNormalized = description.toLowerCase();
const hintNormalized = tool.searchHint?.toLowerCase() ?? "";
let score = 0;
for (const term of allScoringTerms) {
const pattern = termPatterns.get(term);
if (parsed.parts.includes(term)) {
score += parsed.isMcp ? 12 : 10;
} else if (parsed.parts.some((part) => part.includes(term))) {
score += parsed.isMcp ? 6 : 5;
}
if (parsed.full.includes(term) && score === 0) {
score += 3;
}
if (hintNormalized && pattern.test(hintNormalized)) {
score += 4;
}
if (pattern.test(descNormalized)) {
score += 2;
}
}
return { name: tool.name, score };
}));
return scored.filter((item) => item.score > 0).sort((a2, b3) => b3.score - a2.score).slice(0, maxResults).map((item) => item.name);
}
var inputSchema, outputSchema, cachedDeferredToolNames = null, getToolDescriptionMemoized, ToolSearchTool;
var init_ToolSearchTool = __esm(() => {
init_memoize();
init_v4();
init_analytics();
init_Tool();
init_debug();
init_stringUtils();
init_toolSearch();
init_prompt7();
inputSchema = lazySchema(() => exports_external.object({
query: exports_external.string().describe('Query to find deferred tools. Use "select:" for direct selection, or keywords to search.'),
max_results: exports_external.number().optional().default(5).describe("Maximum number of results to return (default: 5)")
}));
outputSchema = lazySchema(() => exports_external.object({
matches: exports_external.array(exports_external.string()),
query: exports_external.string(),
total_deferred_tools: exports_external.number(),
pending_mcp_servers: exports_external.array(exports_external.string()).optional()
}));
getToolDescriptionMemoized = memoize_default(async (toolName, tools) => {
const tool = findToolByName(tools, toolName);
if (!tool) {
return "";
}
return tool.prompt({
getToolPermissionContext: async () => ({
mode: "default",
additionalWorkingDirectories: new Map,
alwaysAllowRules: {},
alwaysDenyRules: {},
alwaysAskRules: {},
isBypassPermissionsModeAvailable: false
}),
tools,
agents: []
});
}, (toolName) => toolName);
ToolSearchTool = buildTool({
isEnabled() {
return isToolSearchEnabledOptimistic();
},
isConcurrencySafe() {
return true;
},
isReadOnly() {
return true;
},
name: TOOL_SEARCH_TOOL_NAME,
maxResultSizeChars: 1e5,
async description() {
return getPrompt2();
},
async prompt() {
return getPrompt2();
},
get inputSchema() {
return inputSchema();
},
get outputSchema() {
return outputSchema();
},
async call(input, { options: { tools }, getAppState }) {
const { query, max_results = 5 } = input;
const deferredTools = tools.filter(isDeferredTool);
maybeInvalidateCache(deferredTools);
function getPendingServerNames() {
const appState = getAppState();
const pending = appState.mcp.clients.filter((c6) => c6.type === "pending");
return pending.length > 0 ? pending.map((s2) => s2.name) : undefined;
}
function logSearchOutcome(matches2, queryType) {
logEvent("tengu_tool_search_outcome", {
query,
queryType,
matchCount: matches2.length,
totalDeferredTools: deferredTools.length,
maxResults: max_results,
hasMatches: matches2.length > 0
});
}
const selectMatch = query.match(/^select:(.+)$/i);
if (selectMatch) {
const requested = selectMatch[1].split(",").map((s2) => s2.trim()).filter(Boolean);
const found = [];
const missing = [];
for (const toolName of requested) {
const tool = findToolByName(deferredTools, toolName) ?? findToolByName(tools, toolName);
if (tool) {
if (!found.includes(tool.name))
found.push(tool.name);
} else {
missing.push(toolName);
}
}
if (found.length === 0) {
logForDebugging(`ToolSearchTool: select failed — none found: ${missing.join(", ")}`);
logSearchOutcome([], "select");
const pendingServers = getPendingServerNames();
return buildSearchResult([], query, deferredTools.length, pendingServers);
}
if (missing.length > 0) {
logForDebugging(`ToolSearchTool: partial select — found: ${found.join(", ")}, missing: ${missing.join(", ")}`);
} else {
logForDebugging(`ToolSearchTool: selected ${found.join(", ")}`);
}
logSearchOutcome(found, "select");
return buildSearchResult(found, query, deferredTools.length);
}
const matches = await searchToolsWithKeywords(query, deferredTools, tools, max_results);
logForDebugging(`ToolSearchTool: keyword search for "${query}", found ${matches.length} matches`);
logSearchOutcome(matches, "keyword");
if (matches.length === 0) {
const pendingServers = getPendingServerNames();
return buildSearchResult(matches, query, deferredTools.length, pendingServers);
}
return buildSearchResult(matches, query, deferredTools.length);
},
renderToolUseMessage() {
return null;
},
userFacingName: () => "",
mapToolResultToToolResultBlockParam(content, toolUseID) {
if (content.matches.length === 0) {
let text = "No matching deferred tools found";
if (content.pending_mcp_servers && content.pending_mcp_servers.length > 0) {
text += `. Some MCP servers are still connecting: ${content.pending_mcp_servers.join(", ")}. Their tools will become available shortly — try searching again.`;
}
return {
type: "tool_result",
tool_use_id: toolUseID,
content: text
};
}
return {
type: "tool_result",
tool_use_id: toolUseID,
content: content.matches.map((name3) => ({
type: "tool_reference",
tool_name: name3
}))
};
}
});
});
// src/utils/contextAnalysis.ts
function analyzeContext(messages) {
const stats = {
toolRequests: new Map,
toolResults: new Map,
humanMessages: 0,
assistantMessages: 0,
localCommandOutputs: 0,
other: 0,
attachments: new Map,
duplicateFileReads: new Map,
total: 0
};
const toolIdsToToolNames = new Map;
const readToolIdToFilePath = new Map;
const fileReadStats = new Map;
messages.forEach((msg) => {
if (msg.type === "attachment") {
const type = msg.attachment.type || "unknown";
stats.attachments.set(type, (stats.attachments.get(type) || 0) + 1);
}
});
const normalizedMessages = normalizeMessagesForAPI(messages);
normalizedMessages.forEach((msg) => {
const { content } = msg.message;
if (typeof content === "string") {
const tokens = roughTokenCountEstimation(content);
stats.total += tokens;
if (msg.type === "user" && content.includes("local-command-stdout")) {
stats.localCommandOutputs += tokens;
} else {
stats[msg.type === "user" ? "humanMessages" : "assistantMessages"] += tokens;
}
} else {
content.forEach((block) => processBlock(block, msg, stats, toolIdsToToolNames, readToolIdToFilePath, fileReadStats));
}
});
fileReadStats.forEach((data, path14) => {
if (data.count > 1) {
const averageTokensPerRead = Math.floor(data.totalTokens / data.count);
const duplicateTokens = averageTokensPerRead * (data.count - 1);
stats.duplicateFileReads.set(path14, {
count: data.count,
tokens: duplicateTokens
});
}
});
return stats;
}
function processBlock(block, message, stats, toolIds, readToolPaths, fileReads) {
const tokens = roughTokenCountEstimation(jsonStringify(block));
stats.total += tokens;
switch (block.type) {
case "text":
if (message.type === "user" && "text" in block && block.text.includes("local-command-stdout")) {
stats.localCommandOutputs += tokens;
} else {
stats[message.type === "user" ? "humanMessages" : "assistantMessages"] += tokens;
}
break;
case "tool_use": {
if ("name" in block && "id" in block) {
const toolName = block.name || "unknown";
increment2(stats.toolRequests, toolName, tokens);
toolIds.set(block.id, toolName);
if (toolName === "Read" && "input" in block && block.input && typeof block.input === "object" && "file_path" in block.input) {
const path14 = String(block.input.file_path);
readToolPaths.set(block.id, path14);
}
}
break;
}
case "tool_result": {
if ("tool_use_id" in block) {
const toolName = toolIds.get(block.tool_use_id) || "unknown";
increment2(stats.toolResults, toolName, tokens);
if (toolName === "Read") {
const path14 = readToolPaths.get(block.tool_use_id);
if (path14) {
const current = fileReads.get(path14) || { count: 0, totalTokens: 0 };
fileReads.set(path14, {
count: current.count + 1,
totalTokens: current.totalTokens + tokens
});
}
}
}
break;
}
case "image":
case "server_tool_use":
case "web_search_tool_result":
case "search_result":
case "document":
case "thinking":
case "redacted_thinking":
case "code_execution_tool_result":
case "mcp_tool_use":
case "mcp_tool_result":
case "container_upload":
case "web_fetch_tool_result":
case "bash_code_execution_tool_result":
case "text_editor_code_execution_tool_result":
case "tool_search_tool_result":
case "compaction":
stats["other"] += tokens;
break;
}
}
function increment2(map3, key, value) {
map3.set(key, (map3.get(key) || 0) + value);
}
function tokenStatsToStatsigMetrics(stats) {
const metrics = {
total_tokens: stats.total,
human_message_tokens: stats.humanMessages,
assistant_message_tokens: stats.assistantMessages,
local_command_output_tokens: stats.localCommandOutputs,
other_tokens: stats.other
};
stats.attachments.forEach((count3, type) => {
metrics[`attachment_${type}_count`] = count3;
});
stats.toolRequests.forEach((tokens, tool) => {
metrics[`tool_request_${tool}_tokens`] = tokens;
});
stats.toolResults.forEach((tokens, tool) => {
metrics[`tool_result_${tool}_tokens`] = tokens;
});
const duplicateTotal = [...stats.duplicateFileReads.values()].reduce((sum, d) => sum + d.tokens, 0);
metrics.duplicate_read_tokens = duplicateTotal;
metrics.duplicate_read_file_count = stats.duplicateFileReads.size;
if (stats.total > 0) {
metrics.human_message_percent = Math.round(stats.humanMessages / stats.total * 100);
metrics.assistant_message_percent = Math.round(stats.assistantMessages / stats.total * 100);
metrics.local_command_output_percent = Math.round(stats.localCommandOutputs / stats.total * 100);
metrics.duplicate_read_percent = Math.round(duplicateTotal / stats.total * 100);
const toolRequestTotal = [...stats.toolRequests.values()].reduce((sum, v2) => sum + v2, 0);
const toolResultTotal = [...stats.toolResults.values()].reduce((sum, v2) => sum + v2, 0);
metrics.tool_request_percent = Math.round(toolRequestTotal / stats.total * 100);
metrics.tool_result_percent = Math.round(toolResultTotal / stats.total * 100);
stats.toolRequests.forEach((tokens, tool) => {
metrics[`tool_request_${tool}_percent`] = Math.round(tokens / stats.total * 100);
});
stats.toolResults.forEach((tokens, tool) => {
metrics[`tool_result_${tool}_percent`] = Math.round(tokens / stats.total * 100);
});
}
return metrics;
}
var init_contextAnalysis = __esm(() => {
init_tokenEstimation();
init_messages3();
init_slowOperations();
});
// src/services/rateLimitMocking.ts
function processRateLimitHeaders(headers) {
if (shouldProcessMockLimits()) {
return applyMockHeaders(headers);
}
return headers;
}
function shouldProcessRateLimits(isSubscriber) {
return isSubscriber || shouldProcessMockLimits();
}
function checkMockRateLimitError(currentModel, isFastModeActive) {
if (!shouldProcessMockLimits()) {
return null;
}
const headerlessMessage = getMockHeaderless429Message();
if (headerlessMessage) {
return new APIError(429, { error: { type: "rate_limit_error", message: headerlessMessage } }, headerlessMessage, new globalThis.Headers);
}
const mockHeaders2 = getMockHeaders();
if (!mockHeaders2) {
return null;
}
const status = mockHeaders2["anthropic-ratelimit-unified-status"];
const overageStatus = mockHeaders2["anthropic-ratelimit-unified-overage-status"];
const rateLimitType = mockHeaders2["anthropic-ratelimit-unified-representative-claim"];
const isOpusLimit = rateLimitType === "seven_day_opus";
const isUsingOpus = currentModel.includes("opus");
if (isOpusLimit && !isUsingOpus) {
return null;
}
if (isMockFastModeRateLimitScenario()) {
const fastModeHeaders = checkMockFastModeRateLimit(isFastModeActive);
if (fastModeHeaders === null) {
return null;
}
const error52 = new APIError(429, { error: { type: "rate_limit_error", message: "Rate limit exceeded" } }, "Rate limit exceeded", new globalThis.Headers(Object.entries(fastModeHeaders).filter(([_2, v2]) => v2 !== undefined)));
return error52;
}
const shouldThrow429 = status === "rejected" && (!overageStatus || overageStatus === "rejected");
if (shouldThrow429) {
const error52 = new APIError(429, { error: { type: "rate_limit_error", message: "Rate limit exceeded" } }, "Rate limit exceeded", new globalThis.Headers(Object.entries(mockHeaders2).filter(([_2, v2]) => v2 !== undefined)));
return error52;
}
return null;
}
function isMockRateLimitError(error52) {
return shouldProcessMockLimits() && error52.status === 429;
}
var init_rateLimitMocking = __esm(() => {
init_sdk();
init_mockRateLimits();
});
// src/services/api/errorUtils.ts
function extractConnectionErrorDetails(error52) {
if (!error52 || typeof error52 !== "object") {
return null;
}
let current = error52;
const maxDepth = 5;
let depth = 0;
while (current && depth < maxDepth) {
if (current instanceof Error && "code" in current && typeof current.code === "string") {
const code = current.code;
const isSSLError = SSL_ERROR_CODES.has(code);
return {
code,
message: current.message,
isSSLError
};
}
if (current instanceof Error && "cause" in current && current.cause !== current) {
current = current.cause;
depth++;
} else {
break;
}
}
return null;
}
function getSSLErrorHint(error52) {
const details = extractConnectionErrorDetails(error52);
if (!details?.isSSLError) {
return null;
}
return `SSL certificate error (${details.code}). If you are behind a corporate proxy or TLS-intercepting firewall, set NODE_EXTRA_CA_CERTS to your CA bundle path, or ask IT to allowlist *.anthropic.com. Run /doctor for details.`;
}
function sanitizeMessageHTML(message) {
if (message.includes("([^<]+)<\/title>/);
if (titleMatch && titleMatch[1]) {
return titleMatch[1].trim();
}
return "";
}
return message;
}
function sanitizeAPIError(apiError) {
const message = apiError.message;
if (!message) {
return "";
}
return sanitizeMessageHTML(message);
}
function hasNestedError(value) {
return typeof value === "object" && value !== null && "error" in value && typeof value.error === "object" && value.error !== null;
}
function extractNestedErrorMessage(error52) {
if (!hasNestedError(error52)) {
return null;
}
const narrowed = error52;
const nested = narrowed.error;
const deepMsg = nested?.error?.message;
if (typeof deepMsg === "string" && deepMsg.length > 0) {
const sanitized = sanitizeMessageHTML(deepMsg);
if (sanitized.length > 0) {
return sanitized;
}
}
const msg = nested?.message;
if (typeof msg === "string" && msg.length > 0) {
const sanitized = sanitizeMessageHTML(msg);
if (sanitized.length > 0) {
return sanitized;
}
}
return null;
}
function formatAPIError(error52) {
const connectionDetails = extractConnectionErrorDetails(error52);
if (connectionDetails) {
const { code, isSSLError } = connectionDetails;
if (code === "ETIMEDOUT") {
return "Request timed out. Check your internet connection and proxy settings";
}
if (isSSLError) {
switch (code) {
case "UNABLE_TO_VERIFY_LEAF_SIGNATURE":
case "UNABLE_TO_GET_ISSUER_CERT":
case "UNABLE_TO_GET_ISSUER_CERT_LOCALLY":
return "Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates";
case "CERT_HAS_EXPIRED":
return "Unable to connect to API: SSL certificate has expired";
case "CERT_REVOKED":
return "Unable to connect to API: SSL certificate has been revoked";
case "DEPTH_ZERO_SELF_SIGNED_CERT":
case "SELF_SIGNED_CERT_IN_CHAIN":
return "Unable to connect to API: Self-signed certificate detected. Check your proxy or corporate SSL certificates";
case "ERR_TLS_CERT_ALTNAME_INVALID":
case "HOSTNAME_MISMATCH":
return "Unable to connect to API: SSL certificate hostname mismatch";
case "CERT_NOT_YET_VALID":
return "Unable to connect to API: SSL certificate is not yet valid";
default:
return `Unable to connect to API: SSL error (${code})`;
}
}
}
if (error52.message === "Connection error.") {
if (connectionDetails?.code) {
return `Unable to connect to API (${connectionDetails.code})`;
}
return "Unable to connect to API. Check your internet connection";
}
if (!error52.message) {
return extractNestedErrorMessage(error52) ?? `API error (status ${error52.status ?? "unknown"})`;
}
const sanitizedMessage = sanitizeAPIError(error52);
return sanitizedMessage !== error52.message && sanitizedMessage.length > 0 ? sanitizedMessage : error52.message;
}
var SSL_ERROR_CODES;
var init_errorUtils = __esm(() => {
SSL_ERROR_CODES = new Set([
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
"UNABLE_TO_GET_ISSUER_CERT",
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
"CERT_SIGNATURE_FAILURE",
"CERT_NOT_YET_VALID",
"CERT_HAS_EXPIRED",
"CERT_REVOKED",
"CERT_REJECTED",
"CERT_UNTRUSTED",
"DEPTH_ZERO_SELF_SIGNED_CERT",
"SELF_SIGNED_CERT_IN_CHAIN",
"CERT_CHAIN_TOO_LONG",
"PATH_LENGTH_EXCEEDED",
"ERR_TLS_CERT_ALTNAME_INVALID",
"HOSTNAME_MISMATCH",
"ERR_TLS_HANDSHAKE_TIMEOUT",
"ERR_SSL_WRONG_VERSION_NUMBER",
"ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC"
]);
});
// src/services/api/withRetry.ts
function shouldRetry529(querySource) {
return querySource === undefined || FOREGROUND_529_RETRY_SOURCES.has(querySource);
}
function isPersistentRetryEnabled() {
return false;
}
function isTransientCapacityError(error52) {
return is529Error(error52) || error52 instanceof APIError && error52.status === 429;
}
function isStaleConnectionError(error52) {
if (!(error52 instanceof APIConnectionError)) {
return false;
}
const details = extractConnectionErrorDetails(error52);
return details?.code === "ECONNRESET" || details?.code === "EPIPE";
}
async function* withRetry(getClient2, operation, options) {
const maxRetries = getMaxRetries(options);
const retryContext = {
model: options.model,
thinkingConfig: options.thinkingConfig,
...isFastModeEnabled() && { fastMode: options.fastMode }
};
let client5 = null;
let consecutive529Errors = options.initialConsecutive529Errors ?? 0;
let lastError;
let persistentAttempt = 0;
for (let attempt = 1;attempt <= maxRetries + 1; attempt++) {
if (options.signal?.aborted) {
throw new APIUserAbortError;
}
const wasFastModeActive = isFastModeEnabled() ? retryContext.fastMode && !isFastModeCooldown() : false;
try {
if (process.env.USER_TYPE === "ant") {
const mockError = checkMockRateLimitError(retryContext.model, wasFastModeActive);
if (mockError) {
throw mockError;
}
}
const isStaleConnection = isStaleConnectionError(lastError);
if (isStaleConnection && getFeatureValue_CACHED_MAY_BE_STALE("tengu_disable_keepalive_on_econnreset", false)) {
logForDebugging("Stale connection (ECONNRESET/EPIPE) — disabling keep-alive for retry");
disableKeepAlive();
}
if (client5 === null || lastError instanceof APIError && lastError.status === 401 || isOAuthTokenRevokedError(lastError) || isBedrockAuthError(lastError) || isVertexAuthError(lastError) || isStaleConnection) {
if (lastError instanceof APIError && lastError.status === 401 || isOAuthTokenRevokedError(lastError)) {
const failedAccessToken = getClaudeAIOAuthTokens()?.accessToken;
if (failedAccessToken) {
await handleOAuth401Error(failedAccessToken);
}
}
client5 = await getClient2();
}
return await operation(client5, attempt, retryContext);
} catch (error52) {
lastError = error52;
logForDebugging(`API error (attempt ${attempt}/${maxRetries + 1}): ${error52 instanceof APIError ? `${error52.status} ${error52.message}` : errorMessage(error52)}`, { level: "error" });
if (wasFastModeActive && !isPersistentRetryEnabled() && error52 instanceof APIError && (error52.status === 429 || is529Error(error52))) {
const overageReason = error52.headers?.get("anthropic-ratelimit-unified-overage-disabled-reason");
if (overageReason !== null && overageReason !== undefined) {
handleFastModeOverageRejection(overageReason);
retryContext.fastMode = false;
continue;
}
const retryAfterMs = getRetryAfterMs(error52);
if (retryAfterMs !== null && retryAfterMs < SHORT_RETRY_THRESHOLD_MS) {
await sleep3(retryAfterMs, options.signal, { abortError });
continue;
}
const cooldownMs = Math.max(retryAfterMs ?? DEFAULT_FAST_MODE_FALLBACK_HOLD_MS, MIN_COOLDOWN_MS);
const cooldownReason = is529Error(error52) ? "overloaded" : "rate_limit";
triggerFastModeCooldown(Date.now() + cooldownMs, cooldownReason);
if (isFastModeEnabled()) {
retryContext.fastMode = false;
}
continue;
}
if (wasFastModeActive && isFastModeNotEnabledError(error52)) {
handleFastModeRejectedByAPI();
retryContext.fastMode = false;
continue;
}
if (is529Error(error52) && !shouldRetry529(options.querySource)) {
logEvent("tengu_api_529_background_dropped", {
query_source: options.querySource
});
throw new CannotRetryError(error52, retryContext);
}
if (is529Error(error52) && (process.env.FALLBACK_FOR_ALL_PRIMARY_MODELS || !isClaudeAISubscriber() && isNonCustomOpusModel(options.model))) {
consecutive529Errors++;
if (consecutive529Errors >= MAX_529_RETRIES) {
if (options.fallbackModel) {
logEvent("tengu_api_opus_fallback_triggered", {
original_model: options.model,
fallback_model: options.fallbackModel,
provider: getAPIProviderForStatsig()
});
throw new FallbackTriggeredError(options.model, options.fallbackModel);
}
if (process.env.USER_TYPE === "external" && !process.env.IS_SANDBOX && !isPersistentRetryEnabled()) {
logEvent("tengu_api_custom_529_overloaded_error", {});
throw new CannotRetryError(new Error(REPEATED_529_ERROR_MESSAGE), retryContext);
}
}
}
const persistent = isPersistentRetryEnabled() && isTransientCapacityError(error52);
if (attempt > maxRetries && !persistent) {
throw new CannotRetryError(error52, retryContext);
}
const handledCloudAuthError = handleAwsCredentialError(error52) || handleGcpCredentialError(error52);
if (!handledCloudAuthError && (!(error52 instanceof APIError) || !shouldRetry(error52))) {
throw new CannotRetryError(error52, retryContext);
}
if (error52 instanceof APIError) {
const overflowData = parseMaxTokensContextOverflowError(error52);
if (overflowData) {
const { inputTokens, contextLimit } = overflowData;
const safetyBuffer = 1000;
const availableContext = Math.max(0, contextLimit - inputTokens - safetyBuffer);
if (availableContext < FLOOR_OUTPUT_TOKENS) {
logError2(new Error(`availableContext ${availableContext} is less than FLOOR_OUTPUT_TOKENS ${FLOOR_OUTPUT_TOKENS}`));
throw error52;
}
const minRequired = (retryContext.thinkingConfig.type === "enabled" ? retryContext.thinkingConfig.budgetTokens : 0) + 1;
const adjustedMaxTokens = Math.max(FLOOR_OUTPUT_TOKENS, availableContext, minRequired);
retryContext.maxTokensOverride = adjustedMaxTokens;
logEvent("tengu_max_tokens_context_overflow_adjustment", {
inputTokens,
contextLimit,
adjustedMaxTokens,
attempt
});
continue;
}
}
const retryAfter = getRetryAfter(error52);
let delayMs;
if (persistent && error52 instanceof APIError && error52.status === 429) {
persistentAttempt++;
const resetDelay = getRateLimitResetDelayMs(error52);
delayMs = resetDelay ?? Math.min(getRetryDelay(persistentAttempt, retryAfter, PERSISTENT_MAX_BACKOFF_MS), PERSISTENT_RESET_CAP_MS);
} else if (persistent) {
persistentAttempt++;
delayMs = Math.min(getRetryDelay(persistentAttempt, retryAfter, PERSISTENT_MAX_BACKOFF_MS), PERSISTENT_RESET_CAP_MS);
} else {
delayMs = getRetryDelay(attempt, retryAfter);
}
const reportedAttempt = persistent ? persistentAttempt : attempt;
logEvent("tengu_api_retry", {
attempt: reportedAttempt,
delayMs,
error: error52.message,
status: error52.status,
provider: getAPIProviderForStatsig()
});
if (persistent) {
if (delayMs > 60000) {
logEvent("tengu_api_persistent_retry_wait", {
status: error52.status,
delayMs,
attempt: reportedAttempt,
provider: getAPIProviderForStatsig()
});
}
let remaining = delayMs;
while (remaining > 0) {
if (options.signal?.aborted)
throw new APIUserAbortError;
if (error52 instanceof APIError) {
yield createSystemAPIErrorMessage(error52, remaining, reportedAttempt, maxRetries);
}
const chunk = Math.min(remaining, HEARTBEAT_INTERVAL_MS);
await sleep3(chunk, options.signal, { abortError });
remaining -= chunk;
}
if (attempt >= maxRetries)
attempt = maxRetries;
} else {
if (error52 instanceof APIError) {
yield createSystemAPIErrorMessage(error52, delayMs, attempt, maxRetries);
}
await sleep3(delayMs, options.signal, { abortError });
}
}
}
throw new CannotRetryError(lastError, retryContext);
}
function getRetryAfter(error52) {
return (error52.headers?.["retry-after"] || error52.headers?.get?.("retry-after")) ?? null;
}
function getRetryDelay(attempt, retryAfterHeader, maxDelayMs = 32000) {
if (retryAfterHeader) {
const seconds = parseInt(retryAfterHeader, 10);
if (!isNaN(seconds)) {
return seconds * 1000;
}
}
const baseDelay = Math.min(BASE_DELAY_MS * Math.pow(2, attempt - 1), maxDelayMs);
const jitter = Math.random() * 0.25 * baseDelay;
return baseDelay + jitter;
}
function parseMaxTokensContextOverflowError(error52) {
if (error52.status !== 400 || !error52.message) {
return;
}
if (!error52.message.includes("input length and `max_tokens` exceed context limit")) {
return;
}
const regex2 = /input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/;
const match = error52.message.match(regex2);
if (!match || match.length !== 4) {
return;
}
if (!match[1] || !match[2] || !match[3]) {
logError2(new Error("Unable to parse max_tokens from max_tokens exceed context limit error message"));
return;
}
const inputTokens = parseInt(match[1], 10);
const maxTokens = parseInt(match[2], 10);
const contextLimit = parseInt(match[3], 10);
if (isNaN(inputTokens) || isNaN(maxTokens) || isNaN(contextLimit)) {
return;
}
return { inputTokens, maxTokens, contextLimit };
}
function isFastModeNotEnabledError(error52) {
if (!(error52 instanceof APIError)) {
return false;
}
return error52.status === 400 && (error52.message?.includes("Fast mode is not enabled") ?? false);
}
function is529Error(error52) {
if (!(error52 instanceof APIError)) {
return false;
}
return error52.status === 529 || (error52.message?.includes('"type":"overloaded_error"') ?? false);
}
function isOAuthTokenRevokedError(error52) {
return error52 instanceof APIError && error52.status === 403 && (error52.message?.includes("OAuth token has been revoked") ?? false);
}
function isBedrockAuthError(error52) {
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK)) {
if (isAwsCredentialsProviderError(error52) || error52 instanceof APIError && error52.status === 403) {
return true;
}
}
return false;
}
function handleAwsCredentialError(error52) {
if (isBedrockAuthError(error52)) {
clearAwsCredentialsCache();
return true;
}
return false;
}
function isGoogleAuthLibraryCredentialError(error52) {
if (!(error52 instanceof Error))
return false;
const msg = error52.message;
return msg.includes("Could not load the default credentials") || msg.includes("Could not refresh access token") || msg.includes("invalid_grant");
}
function isVertexAuthError(error52) {
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX)) {
if (isGoogleAuthLibraryCredentialError(error52)) {
return true;
}
if (error52 instanceof APIError && error52.status === 401) {
return true;
}
}
return false;
}
function handleGcpCredentialError(error52) {
if (isVertexAuthError(error52)) {
clearGcpCredentialsCache();
return true;
}
return false;
}
function shouldRetry(error52) {
if (isMockRateLimitError(error52)) {
return false;
}
if (isPersistentRetryEnabled() && isTransientCapacityError(error52)) {
return true;
}
if (isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) && (error52.status === 401 || error52.status === 403)) {
return true;
}
if (error52.message?.includes('"type":"overloaded_error"')) {
return true;
}
if (parseMaxTokensContextOverflowError(error52)) {
return true;
}
const shouldRetryHeader = error52.headers?.get("x-should-retry");
if (shouldRetryHeader === "true" && (!isClaudeAISubscriber() || isEnterpriseSubscriber())) {
return true;
}
if (shouldRetryHeader === "false") {
const is5xxError = error52.status !== undefined && error52.status >= 500;
if (!(process.env.USER_TYPE === "ant" && is5xxError)) {
return false;
}
}
if (error52 instanceof APIConnectionError) {
return true;
}
if (!error52.status)
return false;
if (error52.status === 408)
return true;
if (error52.status === 409)
return true;
if (error52.status === 429) {
return !isClaudeAISubscriber() || isEnterpriseSubscriber();
}
if (error52.status === 401) {
clearApiKeyHelperCache();
return true;
}
if (isOAuthTokenRevokedError(error52)) {
return true;
}
if (error52.status && error52.status >= 500)
return true;
return false;
}
function getDefaultMaxRetries() {
if (process.env.CLAUDE_CODE_MAX_RETRIES) {
return parseInt(process.env.CLAUDE_CODE_MAX_RETRIES, 10);
}
return DEFAULT_MAX_RETRIES;
}
function getMaxRetries(options) {
return options.maxRetries ?? getDefaultMaxRetries();
}
function getRetryAfterMs(error52) {
const retryAfter = getRetryAfter(error52);
if (retryAfter) {
const seconds = parseInt(retryAfter, 10);
if (!isNaN(seconds)) {
return seconds * 1000;
}
}
return null;
}
function getRateLimitResetDelayMs(error52) {
const resetHeader = error52.headers?.get?.("anthropic-ratelimit-unified-reset");
if (!resetHeader)
return null;
const resetUnixSec = Number(resetHeader);
if (!Number.isFinite(resetUnixSec))
return null;
const delayMs = resetUnixSec * 1000 - Date.now();
if (delayMs <= 0)
return null;
return Math.min(delayMs, PERSISTENT_RESET_CAP_MS);
}
var abortError = () => new APIUserAbortError, DEFAULT_MAX_RETRIES = 10, FLOOR_OUTPUT_TOKENS = 3000, MAX_529_RETRIES = 3, BASE_DELAY_MS = 500, FOREGROUND_529_RETRY_SOURCES, PERSISTENT_MAX_BACKOFF_MS, PERSISTENT_RESET_CAP_MS, HEARTBEAT_INTERVAL_MS = 30000, CannotRetryError, FallbackTriggeredError, DEFAULT_FAST_MODE_FALLBACK_HOLD_MS, SHORT_RETRY_THRESHOLD_MS, MIN_COOLDOWN_MS;
var init_withRetry = __esm(() => {
init_sdk();
init_aws();
init_debug();
init_log3();
init_messages3();
init_providers();
init_auth2();
init_envUtils();
init_errors();
init_fastMode();
init_model();
init_proxy();
init_growthbook();
init_analytics();
init_rateLimitMocking();
init_errors6();
init_errorUtils();
FOREGROUND_529_RETRY_SOURCES = new Set([
"repl_main_thread",
"repl_main_thread:outputStyle:custom",
"repl_main_thread:outputStyle:Explanatory",
"repl_main_thread:outputStyle:Learning",
"sdk",
"agent:custom",
"agent:default",
"agent:builtin",
"compact",
"hook_agent",
"hook_prompt",
"verification_agent",
"side_question",
"auto_mode",
...[]
]);
PERSISTENT_MAX_BACKOFF_MS = 5 * 60 * 1000;
PERSISTENT_RESET_CAP_MS = 6 * 60 * 60 * 1000;
CannotRetryError = class CannotRetryError extends Error {
originalError;
retryContext;
constructor(originalError, retryContext) {
const message = errorMessage(originalError);
super(message);
this.originalError = originalError;
this.retryContext = retryContext;
this.name = "RetryError";
if (originalError instanceof Error && originalError.stack) {
this.stack = originalError.stack;
}
}
};
FallbackTriggeredError = class FallbackTriggeredError extends Error {
originalModel;
fallbackModel;
constructor(originalModel, fallbackModel) {
super(`Model fallback triggered: ${originalModel} -> ${fallbackModel}`);
this.originalModel = originalModel;
this.fallbackModel = fallbackModel;
this.name = "FallbackTriggeredError";
}
};
DEFAULT_FAST_MODE_FALLBACK_HOLD_MS = 30 * 60 * 1000;
SHORT_RETRY_THRESHOLD_MS = 20 * 1000;
MIN_COOLDOWN_MS = 10 * 60 * 1000;
});
// src/utils/imageValidation.ts
function isBase64ImageBlock(block) {
if (typeof block !== "object" || block === null)
return false;
const b3 = block;
if (b3.type !== "image")
return false;
if (typeof b3.source !== "object" || b3.source === null)
return false;
const source = b3.source;
return source.type === "base64" && typeof source.data === "string";
}
function validateImagesForAPI(messages) {
const oversizedImages = [];
let imageIndex = 0;
for (const msg of messages) {
if (typeof msg !== "object" || msg === null)
continue;
const m3 = msg;
if (m3.type !== "user")
continue;
const innerMessage = m3.message;
if (!innerMessage)
continue;
const content = innerMessage.content;
if (typeof content === "string" || !Array.isArray(content))
continue;
for (const block of content) {
if (isBase64ImageBlock(block)) {
imageIndex++;
const base64Size = block.source.data.length;
if (base64Size > API_IMAGE_MAX_BASE64_SIZE) {
logEvent("tengu_image_api_validation_failed", {
base64_size_bytes: base64Size,
max_bytes: API_IMAGE_MAX_BASE64_SIZE
});
oversizedImages.push({ index: imageIndex, size: base64Size });
}
}
}
}
if (oversizedImages.length > 0) {
throw new ImageSizeError(oversizedImages, API_IMAGE_MAX_BASE64_SIZE);
}
}
var ImageSizeError;
var init_imageValidation = __esm(() => {
init_apiLimits();
init_analytics();
init_format();
ImageSizeError = class ImageSizeError extends Error {
constructor(oversizedImages, maxSize) {
let message;
const firstImage = oversizedImages[0];
if (oversizedImages.length === 1 && firstImage) {
message = `Image base64 size (${formatFileSize(firstImage.size)}) exceeds API limit (${formatFileSize(maxSize)}). ` + `Please resize the image before sending.`;
} else {
message = `${oversizedImages.length} images exceed the API limit (${formatFileSize(maxSize)}): ` + oversizedImages.map((img) => `Image ${img.index}: ${formatFileSize(img.size)}`).join(", ") + `. Please resize these images before sending.`;
}
super(message);
this.name = "ImageSizeError";
}
};
});
// src/tools/FileReadTool/imageProcessor.ts
async function getImageProcessor() {
if (imageProcessorModule) {
return imageProcessorModule.default;
}
if (isInBundledMode()) {
try {
const imageProcessor = await import("image-processor-napi");
const sharp2 = imageProcessor.sharp || imageProcessor.default;
imageProcessorModule = { default: sharp2 };
return sharp2;
} catch {
console.warn("Native image processor not available, falling back to sharp");
}
}
const imported = await import("sharp");
const sharp = unwrapDefault(imported);
imageProcessorModule = { default: sharp };
return sharp;
}
function unwrapDefault(mod2) {
return typeof mod2 === "function" ? mod2 : mod2.default;
}
var imageProcessorModule = null;
var init_imageProcessor = () => {};
// src/utils/imageResizer.ts
function classifyImageError(error52) {
if (error52 instanceof Error) {
const errorWithCode = error52;
if (errorWithCode.code === "MODULE_NOT_FOUND" || errorWithCode.code === "ERR_MODULE_NOT_FOUND" || errorWithCode.code === "ERR_DLOPEN_FAILED") {
return ERROR_TYPE_MODULE_LOAD;
}
if (errorWithCode.code === "EACCES" || errorWithCode.code === "EPERM") {
return ERROR_TYPE_PERMISSION;
}
if (errorWithCode.code === "ENOMEM") {
return ERROR_TYPE_MEMORY;
}
}
const message = errorMessage(error52);
if (message.includes("Native image processor module not available")) {
return ERROR_TYPE_MODULE_LOAD;
}
if (message.includes("unsupported image format") || message.includes("Input buffer") || message.includes("Input file is missing") || message.includes("Input file has corrupt header") || message.includes("corrupt header") || message.includes("corrupt image") || message.includes("premature end") || message.includes("zlib: data error") || message.includes("zero width") || message.includes("zero height")) {
return ERROR_TYPE_PROCESSING;
}
if (message.includes("pixel limit") || message.includes("too many pixels") || message.includes("exceeds pixel") || message.includes("image dimensions")) {
return ERROR_TYPE_PIXEL_LIMIT;
}
if (message.includes("out of memory") || message.includes("Cannot allocate") || message.includes("memory allocation")) {
return ERROR_TYPE_MEMORY;
}
if (message.includes("timeout") || message.includes("timed out")) {
return ERROR_TYPE_TIMEOUT;
}
if (message.includes("Vips")) {
return ERROR_TYPE_VIPS;
}
return ERROR_TYPE_UNKNOWN;
}
function hashString2(str) {
let hash3 = 5381;
for (let i4 = 0;i4 < str.length; i4++) {
hash3 = (hash3 << 5) + hash3 + str.charCodeAt(i4) | 0;
}
return hash3 >>> 0;
}
async function maybeResizeAndDownsampleImageBuffer(imageBuffer, originalSize, ext) {
if (imageBuffer.length === 0) {
throw new ImageResizeError("Image file is empty (0 bytes)");
}
try {
const sharp = await getImageProcessor();
const image = sharp(imageBuffer);
const metadata = await image.metadata();
const mediaType = metadata.format ?? ext;
const normalizedMediaType = mediaType === "jpg" ? "jpeg" : mediaType;
if (!metadata.width || !metadata.height) {
if (originalSize > IMAGE_TARGET_RAW_SIZE) {
const compressedBuffer = await sharp(imageBuffer).jpeg({ quality: 80 }).toBuffer();
return { buffer: compressedBuffer, mediaType: "jpeg" };
}
return { buffer: imageBuffer, mediaType: normalizedMediaType };
}
const originalWidth = metadata.width;
const originalHeight = metadata.height;
let width = originalWidth;
let height = originalHeight;
if (originalSize <= IMAGE_TARGET_RAW_SIZE && width <= IMAGE_MAX_WIDTH && height <= IMAGE_MAX_HEIGHT) {
return {
buffer: imageBuffer,
mediaType: normalizedMediaType,
dimensions: {
originalWidth,
originalHeight,
displayWidth: width,
displayHeight: height
}
};
}
const needsDimensionResize = width > IMAGE_MAX_WIDTH || height > IMAGE_MAX_HEIGHT;
const isPng = normalizedMediaType === "png";
if (!needsDimensionResize && originalSize > IMAGE_TARGET_RAW_SIZE) {
if (isPng) {
const pngCompressed = await sharp(imageBuffer).png({ compressionLevel: 9, palette: true }).toBuffer();
if (pngCompressed.length <= IMAGE_TARGET_RAW_SIZE) {
return {
buffer: pngCompressed,
mediaType: "png",
dimensions: {
originalWidth,
originalHeight,
displayWidth: width,
displayHeight: height
}
};
}
}
for (const quality of [80, 60, 40, 20]) {
const compressedBuffer = await sharp(imageBuffer).jpeg({ quality }).toBuffer();
if (compressedBuffer.length <= IMAGE_TARGET_RAW_SIZE) {
return {
buffer: compressedBuffer,
mediaType: "jpeg",
dimensions: {
originalWidth,
originalHeight,
displayWidth: width,
displayHeight: height
}
};
}
}
}
if (width > IMAGE_MAX_WIDTH) {
height = Math.round(height * IMAGE_MAX_WIDTH / width);
width = IMAGE_MAX_WIDTH;
}
if (height > IMAGE_MAX_HEIGHT) {
width = Math.round(width * IMAGE_MAX_HEIGHT / height);
height = IMAGE_MAX_HEIGHT;
}
logForDebugging(`Resizing to ${width}x${height}`);
const resizedImageBuffer = await sharp(imageBuffer).resize(width, height, {
fit: "inside",
withoutEnlargement: true
}).toBuffer();
if (resizedImageBuffer.length > IMAGE_TARGET_RAW_SIZE) {
if (isPng) {
const pngCompressed = await sharp(imageBuffer).resize(width, height, {
fit: "inside",
withoutEnlargement: true
}).png({ compressionLevel: 9, palette: true }).toBuffer();
if (pngCompressed.length <= IMAGE_TARGET_RAW_SIZE) {
return {
buffer: pngCompressed,
mediaType: "png",
dimensions: {
originalWidth,
originalHeight,
displayWidth: width,
displayHeight: height
}
};
}
}
for (const quality of [80, 60, 40, 20]) {
const compressedBuffer2 = await sharp(imageBuffer).resize(width, height, {
fit: "inside",
withoutEnlargement: true
}).jpeg({ quality }).toBuffer();
if (compressedBuffer2.length <= IMAGE_TARGET_RAW_SIZE) {
return {
buffer: compressedBuffer2,
mediaType: "jpeg",
dimensions: {
originalWidth,
originalHeight,
displayWidth: width,
displayHeight: height
}
};
}
}
const smallerWidth = Math.min(width, 1000);
const smallerHeight = Math.round(height * smallerWidth / Math.max(width, 1));
logForDebugging("Still too large, compressing with JPEG");
const compressedBuffer = await sharp(imageBuffer).resize(smallerWidth, smallerHeight, {
fit: "inside",
withoutEnlargement: true
}).jpeg({ quality: 20 }).toBuffer();
logForDebugging(`JPEG compressed buffer size: ${compressedBuffer.length}`);
return {
buffer: compressedBuffer,
mediaType: "jpeg",
dimensions: {
originalWidth,
originalHeight,
displayWidth: smallerWidth,
displayHeight: smallerHeight
}
};
}
return {
buffer: resizedImageBuffer,
mediaType: normalizedMediaType,
dimensions: {
originalWidth,
originalHeight,
displayWidth: width,
displayHeight: height
}
};
} catch (error52) {
logError2(error52);
const errorType = classifyImageError(error52);
const errorMsg = errorMessage(error52);
logEvent("tengu_image_resize_failed", {
original_size_bytes: originalSize,
error_type: errorType,
error_message_hash: hashString2(errorMsg)
});
const detected = detectImageFormatFromBuffer(imageBuffer);
const normalizedExt = detected.slice(6);
const base64Size = Math.ceil(originalSize * 4 / 3);
const overDim = imageBuffer.length >= 24 && imageBuffer[0] === 137 && imageBuffer[1] === 80 && imageBuffer[2] === 78 && imageBuffer[3] === 71 && (imageBuffer.readUInt32BE(16) > IMAGE_MAX_WIDTH || imageBuffer.readUInt32BE(20) > IMAGE_MAX_HEIGHT);
if (base64Size <= API_IMAGE_MAX_BASE64_SIZE && !overDim) {
logEvent("tengu_image_resize_fallback", {
original_size_bytes: originalSize,
base64_size_bytes: base64Size,
error_type: errorType
});
return { buffer: imageBuffer, mediaType: normalizedExt };
}
throw new ImageResizeError(overDim ? `Unable to resize image — dimensions exceed the ${IMAGE_MAX_WIDTH}x${IMAGE_MAX_HEIGHT}px limit and image processing failed. ` + `Please resize the image to reduce its pixel dimensions.` : `Unable to resize image (${formatFileSize(originalSize)} raw, ${formatFileSize(base64Size)} base64). ` + `The image exceeds the 5MB API limit and compression failed. ` + `Please resize the image manually or use a smaller image.`);
}
}
async function maybeResizeAndDownsampleImageBlock(imageBlock) {
if (imageBlock.source.type !== "base64") {
return { block: imageBlock };
}
const imageBuffer = Buffer.from(imageBlock.source.data, "base64");
const originalSize = imageBuffer.length;
const mediaType = imageBlock.source.media_type;
const ext = mediaType?.split("/")[1] || "png";
const resized = await maybeResizeAndDownsampleImageBuffer(imageBuffer, originalSize, ext);
return {
block: {
type: "image",
source: {
type: "base64",
media_type: `image/${resized.mediaType}`,
data: resized.buffer.toString("base64")
}
},
dimensions: resized.dimensions
};
}
async function compressImageBuffer(imageBuffer, maxBytes = IMAGE_TARGET_RAW_SIZE, originalMediaType) {
const fallbackFormat = originalMediaType?.split("/")[1] || "jpeg";
const normalizedFallback = fallbackFormat === "jpg" ? "jpeg" : fallbackFormat;
try {
const sharp = await getImageProcessor();
const metadata = await sharp(imageBuffer).metadata();
const format4 = metadata.format || normalizedFallback;
const originalSize = imageBuffer.length;
const context3 = {
imageBuffer,
metadata,
format: format4,
maxBytes,
originalSize
};
if (originalSize <= maxBytes) {
return createCompressedImageResult(imageBuffer, format4, originalSize);
}
const resizedResult = await tryProgressiveResizing(context3, sharp);
if (resizedResult) {
return resizedResult;
}
if (format4 === "png") {
const palettizedResult = await tryPalettePNG(context3, sharp);
if (palettizedResult) {
return palettizedResult;
}
}
const jpegResult = await tryJPEGConversion(context3, 50, sharp);
if (jpegResult) {
return jpegResult;
}
return await createUltraCompressedJPEG(context3, sharp);
} catch (error52) {
logError2(error52);
const errorType = classifyImageError(error52);
const errorMsg = errorMessage(error52);
logEvent("tengu_image_compress_failed", {
original_size_bytes: imageBuffer.length,
max_bytes: maxBytes,
error_type: errorType,
error_message_hash: hashString2(errorMsg)
});
if (imageBuffer.length <= maxBytes) {
const detected = detectImageFormatFromBuffer(imageBuffer);
return {
base64: imageBuffer.toString("base64"),
mediaType: detected,
originalSize: imageBuffer.length
};
}
throw new ImageResizeError(`Unable to compress image (${formatFileSize(imageBuffer.length)}) to fit within ${formatFileSize(maxBytes)}. ` + `Please use a smaller image.`);
}
}
async function compressImageBufferWithTokenLimit(imageBuffer, maxTokens, originalMediaType) {
const maxBase64Chars = Math.floor(maxTokens / 0.125);
const maxBytes = Math.floor(maxBase64Chars * 0.75);
return compressImageBuffer(imageBuffer, maxBytes, originalMediaType);
}
async function compressImageBlock(imageBlock, maxBytes = IMAGE_TARGET_RAW_SIZE) {
if (imageBlock.source.type !== "base64") {
return imageBlock;
}
const imageBuffer = Buffer.from(imageBlock.source.data, "base64");
if (imageBuffer.length <= maxBytes) {
return imageBlock;
}
const compressed = await compressImageBuffer(imageBuffer, maxBytes);
return {
type: "image",
source: {
type: "base64",
media_type: compressed.mediaType,
data: compressed.base64
}
};
}
function createCompressedImageResult(buffer, mediaType, originalSize) {
const normalizedMediaType = mediaType === "jpg" ? "jpeg" : mediaType;
return {
base64: buffer.toString("base64"),
mediaType: `image/${normalizedMediaType}`,
originalSize
};
}
async function tryProgressiveResizing(context3, sharp) {
const scalingFactors = [1, 0.75, 0.5, 0.25];
for (const scalingFactor of scalingFactors) {
const newWidth = Math.round((context3.metadata.width || 2000) * scalingFactor);
const newHeight = Math.round((context3.metadata.height || 2000) * scalingFactor);
let resizedImage = sharp(context3.imageBuffer).resize(newWidth, newHeight, {
fit: "inside",
withoutEnlargement: true
});
resizedImage = applyFormatOptimizations(resizedImage, context3.format);
const resizedBuffer = await resizedImage.toBuffer();
if (resizedBuffer.length <= context3.maxBytes) {
return createCompressedImageResult(resizedBuffer, context3.format, context3.originalSize);
}
}
return null;
}
function applyFormatOptimizations(image, format4) {
switch (format4) {
case "png":
return image.png({
compressionLevel: 9,
palette: true
});
case "jpeg":
case "jpg":
return image.jpeg({ quality: 80 });
case "webp":
return image.webp({ quality: 80 });
default:
return image;
}
}
async function tryPalettePNG(context3, sharp) {
const palettePng = await sharp(context3.imageBuffer).resize(800, 800, {
fit: "inside",
withoutEnlargement: true
}).png({
compressionLevel: 9,
palette: true,
colors: 64
}).toBuffer();
if (palettePng.length <= context3.maxBytes) {
return createCompressedImageResult(palettePng, "png", context3.originalSize);
}
return null;
}
async function tryJPEGConversion(context3, quality, sharp) {
const jpegBuffer = await sharp(context3.imageBuffer).resize(600, 600, {
fit: "inside",
withoutEnlargement: true
}).jpeg({ quality }).toBuffer();
if (jpegBuffer.length <= context3.maxBytes) {
return createCompressedImageResult(jpegBuffer, "jpeg", context3.originalSize);
}
return null;
}
async function createUltraCompressedJPEG(context3, sharp) {
const ultraCompressedBuffer = await sharp(context3.imageBuffer).resize(400, 400, {
fit: "inside",
withoutEnlargement: true
}).jpeg({ quality: 20 }).toBuffer();
return createCompressedImageResult(ultraCompressedBuffer, "jpeg", context3.originalSize);
}
function detectImageFormatFromBuffer(buffer) {
if (buffer.length < 4)
return "image/png";
if (buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71) {
return "image/png";
}
if (buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) {
return "image/jpeg";
}
if (buffer[0] === 71 && buffer[1] === 73 && buffer[2] === 70) {
return "image/gif";
}
if (buffer[0] === 82 && buffer[1] === 73 && buffer[2] === 70 && buffer[3] === 70) {
if (buffer.length >= 12 && buffer[8] === 87 && buffer[9] === 69 && buffer[10] === 66 && buffer[11] === 80) {
return "image/webp";
}
}
return "image/png";
}
function detectImageFormatFromBase64(base64Data) {
try {
const buffer = Buffer.from(base64Data, "base64");
return detectImageFormatFromBuffer(buffer);
} catch {
return "image/png";
}
}
function createImageMetadataText(dims, sourcePath) {
const { originalWidth, originalHeight, displayWidth, displayHeight } = dims;
if (!originalWidth || !originalHeight || !displayWidth || !displayHeight || displayWidth <= 0 || displayHeight <= 0) {
if (sourcePath) {
return `[Image source: ${sourcePath}]`;
}
return null;
}
const wasResized = originalWidth !== displayWidth || originalHeight !== displayHeight;
if (!wasResized && !sourcePath) {
return null;
}
const parts = [];
if (sourcePath) {
parts.push(`source: ${sourcePath}`);
}
if (wasResized) {
const scaleFactor = originalWidth / displayWidth;
parts.push(`original ${originalWidth}x${originalHeight}, displayed at ${displayWidth}x${displayHeight}. Multiply coordinates by ${scaleFactor.toFixed(2)} to map to original image.`);
}
return `[Image: ${parts.join(", ")}]`;
}
var ERROR_TYPE_MODULE_LOAD = 1, ERROR_TYPE_PROCESSING = 2, ERROR_TYPE_UNKNOWN = 3, ERROR_TYPE_PIXEL_LIMIT = 4, ERROR_TYPE_MEMORY = 5, ERROR_TYPE_TIMEOUT = 6, ERROR_TYPE_VIPS = 7, ERROR_TYPE_PERMISSION = 8, ImageResizeError;
var init_imageResizer = __esm(() => {
init_apiLimits();
init_analytics();
init_imageProcessor();
init_debug();
init_errors();
init_format();
init_log3();
ImageResizeError = class ImageResizeError extends Error {
constructor(message) {
super(message);
this.name = "ImageResizeError";
}
};
});
// src/utils/systemPromptType.ts
function asSystemPrompt(value) {
return value;
}
// src/constants/errorIds.ts
var E_TOOL_USE_SUMMARY_GENERATION_FAILED = 344;
// src/services/toolUseSummary/toolUseSummaryGenerator.ts
async function generateToolUseSummary({
tools,
signal,
isNonInteractiveSession,
lastAssistantText
}) {
if (tools.length === 0) {
return null;
}
try {
const toolSummaries = tools.map((tool) => {
const inputStr = truncateJson(tool.input, 300);
const outputStr = truncateJson(tool.output, 300);
return `Tool: ${tool.name}
Input: ${inputStr}
Output: ${outputStr}`;
}).join(`
`);
const contextPrefix = lastAssistantText ? `User's intent (from assistant's last message): ${lastAssistantText.slice(0, 200)}
` : "";
const response = await queryHaiku({
systemPrompt: asSystemPrompt([TOOL_USE_SUMMARY_SYSTEM_PROMPT]),
userPrompt: `${contextPrefix}Tools completed:
${toolSummaries}
Label:`,
signal,
options: {
querySource: "tool_use_summary_generation",
enablePromptCaching: true,
agents: [],
isNonInteractiveSession,
hasAppendSystemPrompt: false,
mcpTools: []
}
});
const summary = response.message.content.filter((block) => block.type === "text").map((block) => block.type === "text" ? block.text : "").join("").trim();
return summary || null;
} catch (error52) {
const err2 = toError(error52);
err2.cause = { errorId: E_TOOL_USE_SUMMARY_GENERATION_FAILED };
logError2(err2);
return null;
}
}
function truncateJson(value, maxLength) {
try {
const str = jsonStringify(value);
if (str.length <= maxLength) {
return str;
}
return str.slice(0, maxLength - 3) + "...";
} catch {
return "[unable to serialize]";
}
}
var TOOL_USE_SUMMARY_SYSTEM_PROMPT = `Write a short summary label describing what these tool calls accomplished. It appears as a single-line row in a mobile app and truncates around 30 characters, so think git-commit-subject, not sentence.
Keep the verb in past tense and the most distinctive noun. Drop articles, connectors, and long location context first.
Examples:
- Searched in auth/
- Fixed NPE in UserService
- Created signup endpoint
- Read config.json
- Ran failing tests`;
var init_toolUseSummaryGenerator = __esm(() => {
init_errors();
init_log3();
init_slowOperations();
init_claude();
});
// src/utils/objectGroupBy.ts
function objectGroupBy(items, keySelector) {
const result = Object.create(null);
let index = 0;
for (const item of items) {
const key = keySelector(item, index++);
if (result[key] === undefined) {
result[key] = [];
}
result[key].push(item);
}
return result;
}
// src/utils/messageQueueManager.ts
function logOperation(operation, content) {
const sessionId = getSessionId();
const queueOp = {
type: "queue-operation",
operation,
timestamp: new Date().toISOString(),
sessionId,
...content !== undefined && { content }
};
recordQueueOperation(queueOp);
}
function notifySubscribers() {
snapshot = Object.freeze([...commandQueue]);
queueChanged.emit();
}
function getCommandQueueSnapshot() {
return snapshot;
}
function getCommandQueue() {
return [...commandQueue];
}
function getCommandQueueLength() {
return commandQueue.length;
}
function hasCommandsInQueue() {
return commandQueue.length > 0;
}
function enqueue(command) {
commandQueue.push({ ...command, priority: command.priority ?? "next" });
notifySubscribers();
logOperation("enqueue", typeof command.value === "string" ? command.value : undefined);
}
function enqueuePendingNotification(command) {
commandQueue.push({ ...command, priority: command.priority ?? "later" });
notifySubscribers();
logOperation("enqueue", typeof command.value === "string" ? command.value : undefined);
}
function dequeue(filter2) {
if (commandQueue.length === 0) {
return;
}
let bestIdx = -1;
let bestPriority = Infinity;
for (let i4 = 0;i4 < commandQueue.length; i4++) {
const cmd = commandQueue[i4];
if (filter2 && !filter2(cmd))
continue;
const priority = PRIORITY_ORDER[cmd.priority ?? "next"];
if (priority < bestPriority) {
bestIdx = i4;
bestPriority = priority;
}
}
if (bestIdx === -1)
return;
const [dequeued] = commandQueue.splice(bestIdx, 1);
notifySubscribers();
logOperation("dequeue");
return dequeued;
}
function peek(filter2) {
if (commandQueue.length === 0) {
return;
}
let bestIdx = -1;
let bestPriority = Infinity;
for (let i4 = 0;i4 < commandQueue.length; i4++) {
const cmd = commandQueue[i4];
if (filter2 && !filter2(cmd))
continue;
const priority = PRIORITY_ORDER[cmd.priority ?? "next"];
if (priority < bestPriority) {
bestIdx = i4;
bestPriority = priority;
}
}
if (bestIdx === -1)
return;
return commandQueue[bestIdx];
}
function dequeueAllMatching(predicate) {
const matched = [];
const remaining = [];
for (const cmd of commandQueue) {
if (predicate(cmd)) {
matched.push(cmd);
} else {
remaining.push(cmd);
}
}
if (matched.length === 0) {
return [];
}
commandQueue.length = 0;
commandQueue.push(...remaining);
notifySubscribers();
for (const _cmd of matched) {
logOperation("dequeue");
}
return matched;
}
function remove(commandsToRemove) {
if (commandsToRemove.length === 0) {
return;
}
const before = commandQueue.length;
for (let i4 = commandQueue.length - 1;i4 >= 0; i4--) {
if (commandsToRemove.includes(commandQueue[i4])) {
commandQueue.splice(i4, 1);
}
}
if (commandQueue.length !== before) {
notifySubscribers();
}
for (const _cmd of commandsToRemove) {
logOperation("remove");
}
}
function removeByFilter(predicate) {
const removed = [];
for (let i4 = commandQueue.length - 1;i4 >= 0; i4--) {
if (predicate(commandQueue[i4])) {
removed.unshift(commandQueue.splice(i4, 1)[0]);
}
}
if (removed.length > 0) {
notifySubscribers();
for (const _cmd of removed) {
logOperation("remove");
}
}
return removed;
}
function clearCommandQueue() {
if (commandQueue.length === 0) {
return;
}
commandQueue.length = 0;
notifySubscribers();
}
function isPromptInputModeEditable(mode) {
return !NON_EDITABLE_MODES.has(mode);
}
function isQueuedCommandEditable(cmd) {
return isPromptInputModeEditable(cmd.mode) && !cmd.isMeta;
}
function isQueuedCommandVisible(cmd) {
if (false)
;
return isQueuedCommandEditable(cmd);
}
function extractTextFromValue(value) {
return typeof value === "string" ? value : extractTextContent(value, `
`);
}
function extractImagesFromValue(value, startId) {
if (typeof value === "string") {
return [];
}
const images = [];
let imageIndex = 0;
for (const block of value) {
if (block.type === "image" && block.source.type === "base64") {
images.push({
id: startId + imageIndex,
type: "image",
content: block.source.data,
mediaType: block.source.media_type,
filename: `image${imageIndex + 1}`
});
imageIndex++;
}
}
return images;
}
function popAllEditable(currentInput, currentCursorOffset) {
if (commandQueue.length === 0) {
return;
}
const { editable = [], nonEditable = [] } = objectGroupBy([...commandQueue], (cmd) => isQueuedCommandEditable(cmd) ? "editable" : "nonEditable");
if (editable.length === 0) {
return;
}
const queuedTexts = editable.map((cmd) => extractTextFromValue(cmd.value));
const newInput = [...queuedTexts, currentInput].filter(Boolean).join(`
`);
const cursorOffset = queuedTexts.join(`
`).length + 1 + currentCursorOffset;
const images = [];
let nextImageId = Date.now();
for (const cmd of editable) {
if (cmd.pastedContents) {
for (const content of Object.values(cmd.pastedContents)) {
if (content.type === "image") {
images.push(content);
}
}
}
const cmdImages = extractImagesFromValue(cmd.value, nextImageId);
images.push(...cmdImages);
nextImageId += cmdImages.length;
}
for (const command of editable) {
logOperation("popAll", typeof command.value === "string" ? command.value : undefined);
}
commandQueue.length = 0;
commandQueue.push(...nonEditable);
notifySubscribers();
return { text: newInput, cursorOffset, images };
}
function getCommandsByMaxPriority(maxPriority) {
const threshold = PRIORITY_ORDER[maxPriority];
return commandQueue.filter((cmd) => PRIORITY_ORDER[cmd.priority ?? "next"] <= threshold);
}
function isSlashCommand(cmd) {
return typeof cmd.value === "string" && cmd.value.trim().startsWith("/") && !cmd.skipSlashCommands;
}
var commandQueue, snapshot, queueChanged, subscribeToCommandQueue, PRIORITY_ORDER, NON_EDITABLE_MODES;
var init_messageQueueManager = __esm(() => {
init_state();
init_messages3();
init_sessionStorage();
commandQueue = [];
snapshot = Object.freeze([]);
queueChanged = createSignal();
subscribeToCommandQueue = queueChanged.subscribe;
PRIORITY_ORDER = {
now: 0,
next: 1,
later: 2
};
NON_EDITABLE_MODES = new Set([
"task-notification"
]);
});
// src/utils/commandLifecycle.ts
function setCommandLifecycleListener(cb) {
listener = cb;
}
function notifyCommandLifecycle(uuid8, state3) {
listener?.(uuid8, state3);
}
var listener = null;
// src/utils/headlessProfiler.ts
function clearHeadlessMarks() {
const perf = getPerformance();
const allMarks = perf.getEntriesByType("mark");
for (const mark of allMarks) {
if (mark.name.startsWith(MARK_PREFIX)) {
perf.clearMarks(mark.name);
}
}
}
function headlessProfilerStartTurn() {
if (!getIsNonInteractiveSession())
return;
if (!SHOULD_PROFILE2)
return;
currentTurnNumber++;
clearHeadlessMarks();
const perf = getPerformance();
perf.mark(`${MARK_PREFIX}turn_start`);
if (DETAILED_PROFILING2) {
logForDebugging(`[headlessProfiler] Started turn ${currentTurnNumber}`);
}
}
function headlessProfilerCheckpoint(name3) {
if (!getIsNonInteractiveSession())
return;
if (!SHOULD_PROFILE2)
return;
const perf = getPerformance();
perf.mark(`${MARK_PREFIX}${name3}`);
if (DETAILED_PROFILING2) {
logForDebugging(`[headlessProfiler] Checkpoint: ${name3} at ${perf.now().toFixed(1)}ms`);
}
}
function logHeadlessProfilerTurn() {
if (!getIsNonInteractiveSession())
return;
if (!SHOULD_PROFILE2)
return;
const perf = getPerformance();
const allMarks = perf.getEntriesByType("mark");
const marks = allMarks.filter((mark) => mark.name.startsWith(MARK_PREFIX));
if (marks.length === 0)
return;
const checkpointTimes = new Map;
for (const mark of marks) {
const name3 = mark.name.slice(MARK_PREFIX.length);
checkpointTimes.set(name3, mark.startTime);
}
const turnStart = checkpointTimes.get("turn_start");
if (turnStart === undefined)
return;
const metadata = {
turn_number: currentTurnNumber
};
const systemMessageTime = checkpointTimes.get("system_message_yielded");
if (systemMessageTime !== undefined && currentTurnNumber === 0) {
metadata.time_to_system_message_ms = Math.round(systemMessageTime);
}
const queryStartTime = checkpointTimes.get("query_started");
if (queryStartTime !== undefined) {
metadata.time_to_query_start_ms = Math.round(queryStartTime - turnStart);
}
const firstChunkTime = checkpointTimes.get("first_chunk");
if (firstChunkTime !== undefined) {
metadata.time_to_first_response_ms = Math.round(firstChunkTime - turnStart);
}
const apiRequestTime = checkpointTimes.get("api_request_sent");
if (queryStartTime !== undefined && apiRequestTime !== undefined) {
metadata.query_overhead_ms = Math.round(apiRequestTime - queryStartTime);
}
metadata.checkpoint_count = marks.length;
if (process.env.CLAUDE_CODE_ENTRYPOINT) {
metadata.entrypoint = process.env.CLAUDE_CODE_ENTRYPOINT;
}
if (STATSIG_LOGGING_SAMPLED2) {
logEvent("tengu_headless_latency", metadata);
}
if (DETAILED_PROFILING2) {
logForDebugging(`[headlessProfiler] Turn ${currentTurnNumber} metrics: ${jsonStringify(metadata)}`);
}
}
var DETAILED_PROFILING2, STATSIG_SAMPLE_RATE2 = 0.05, STATSIG_LOGGING_SAMPLED2, SHOULD_PROFILE2, MARK_PREFIX = "headless_", currentTurnNumber = -1;
var init_headlessProfiler = __esm(() => {
init_state();
init_analytics();
init_debug();
init_envUtils();
init_profilerBase();
init_slowOperations();
DETAILED_PROFILING2 = isEnvTruthy(process.env.CLAUDE_CODE_PROFILE_STARTUP);
STATSIG_LOGGING_SAMPLED2 = process.env.USER_TYPE === "ant" || Math.random() < STATSIG_SAMPLE_RATE2;
SHOULD_PROFILE2 = DETAILED_PROFILING2 || STATSIG_LOGGING_SAMPLED2;
});
// src/tools/SleepTool/prompt.ts
var SLEEP_TOOL_NAME = "Sleep", SLEEP_TOOL_PROMPT;
var init_prompt8 = __esm(() => {
init_xml();
SLEEP_TOOL_PROMPT = `Wait for a specified duration. The user can interrupt the sleep at any time.
Use this when the user tells you to sleep or rest, when you have nothing to do, or when you're waiting for something.
You may receive <${TICK_TAG}> prompts — these are periodic check-ins. Look for useful work to do before sleeping.
You can call this concurrently with other tools — it won't interfere with them.
Prefer this over \`Bash(sleep ...)\` — it doesn't hold a shell process.
Each wake-up costs an API call, but the prompt cache expires after 5 minutes of inactivity — balance accordingly.`;
});
// src/utils/hooks/postSamplingHooks.ts
function registerPostSamplingHook(hook) {
postSamplingHooks.push(hook);
}
async function executePostSamplingHooks(messages, systemPrompt, userContext, systemContext, toolUseContext, querySource) {
const context3 = {
messages,
systemPrompt,
userContext,
systemContext,
toolUseContext,
querySource
};
for (const hook of postSamplingHooks) {
try {
await hook(context3);
} catch (error52) {
logError2(toError(error52));
}
}
}
var postSamplingHooks;
var init_postSamplingHooks = __esm(() => {
init_errors();
init_log3();
postSamplingHooks = [];
});
// src/services/api/dumpPrompts.ts
import { createHash as createHash7 } from "crypto";
import { promises as fs8 } from "fs";
import { dirname as dirname20, join as join37 } from "path";
function hashString3(str) {
return createHash7("sha256").update(str).digest("hex");
}
function clearDumpState(agentIdOrSessionId) {
dumpState.delete(agentIdOrSessionId);
}
function clearAllDumpState() {
dumpState.clear();
}
function addApiRequestToCache(requestData) {
if (process.env.USER_TYPE !== "ant")
return;
cachedApiRequests.push({
timestamp: new Date().toISOString(),
request: requestData
});
if (cachedApiRequests.length > MAX_CACHED_REQUESTS) {
cachedApiRequests.shift();
}
}
function getDumpPromptsPath(agentIdOrSessionId) {
return join37(getClaudeConfigHomeDir(), "dump-prompts", `${agentIdOrSessionId ?? getSessionId()}.jsonl`);
}
function appendToFile(filePath, entries) {
if (entries.length === 0)
return;
fs8.mkdir(dirname20(filePath), { recursive: true }).then(() => fs8.appendFile(filePath, entries.join(`
`) + `
`)).catch(() => {});
}
function initFingerprint(req) {
const tools = req.tools;
const system = req.system;
const sysLen = typeof system === "string" ? system.length : Array.isArray(system) ? system.reduce((n2, b3) => n2 + (b3.text?.length ?? 0), 0) : 0;
const toolNames = tools?.map((t2) => t2.name ?? "").join(",") ?? "";
return `${req.model}|${toolNames}|${sysLen}`;
}
function dumpRequest(body, ts, state3, filePath) {
try {
const req = jsonParse(body);
addApiRequestToCache(req);
if (process.env.USER_TYPE !== "ant")
return;
const entries = [];
const messages = req.messages ?? [];
const fingerprint = initFingerprint(req);
if (!state3.initialized || fingerprint !== state3.lastInitFingerprint) {
const { messages: _2, ...initData } = req;
const initDataStr = jsonStringify(initData);
const initDataHash = hashString3(initDataStr);
state3.lastInitFingerprint = fingerprint;
if (!state3.initialized) {
state3.initialized = true;
state3.lastInitDataHash = initDataHash;
entries.push(`{"type":"init","timestamp":"${ts}","data":${initDataStr}}`);
} else if (initDataHash !== state3.lastInitDataHash) {
state3.lastInitDataHash = initDataHash;
entries.push(`{"type":"system_update","timestamp":"${ts}","data":${initDataStr}}`);
}
}
for (const msg of messages.slice(state3.messageCountSeen)) {
if (msg.role === "user") {
entries.push(jsonStringify({ type: "message", timestamp: ts, data: msg }));
}
}
state3.messageCountSeen = messages.length;
appendToFile(filePath, entries);
} catch {}
}
function createDumpPromptsFetch(agentIdOrSessionId) {
const filePath = getDumpPromptsPath(agentIdOrSessionId);
return async (input, init) => {
const state3 = dumpState.get(agentIdOrSessionId) ?? {
initialized: false,
messageCountSeen: 0,
lastInitDataHash: "",
lastInitFingerprint: ""
};
dumpState.set(agentIdOrSessionId, state3);
let timestamp;
if (init?.method === "POST" && init.body) {
timestamp = new Date().toISOString();
setImmediate(dumpRequest, init.body, timestamp, state3, filePath);
}
const response = await globalThis.fetch(input, init);
if (timestamp && response.ok && process.env.USER_TYPE === "ant") {
const cloned = response.clone();
(async () => {
try {
const isStreaming = cloned.headers.get("content-type")?.includes("text/event-stream");
let data;
if (isStreaming && cloned.body) {
const reader = cloned.body.getReader();
const decoder = new TextDecoder;
let buffer = "";
try {
while (true) {
const { done, value } = await reader.read();
if (done)
break;
buffer += decoder.decode(value, { stream: true });
}
} finally {
reader.releaseLock();
}
const chunks = [];
for (const event of buffer.split(`
`)) {
for (const line of event.split(`
`)) {
if (line.startsWith("data: ") && line !== "data: [DONE]") {
try {
chunks.push(jsonParse(line.slice(6)));
} catch {}
}
}
}
data = { stream: true, chunks };
} else {
data = await cloned.json();
}
await fs8.appendFile(filePath, jsonStringify({ type: "response", timestamp, data }) + `
`);
} catch {}
})();
}
return response;
};
}
var MAX_CACHED_REQUESTS = 5, cachedApiRequests, dumpState;
var init_dumpPrompts = __esm(() => {
init_state();
init_envUtils();
init_slowOperations();
cachedApiRequests = [];
dumpState = new Map;
});
// src/utils/abortController.ts
import { setMaxListeners as setMaxListeners2 } from "events";
function createAbortController(maxListeners = DEFAULT_MAX_LISTENERS) {
const controller = new AbortController;
setMaxListeners2(maxListeners, controller.signal);
return controller;
}
function propagateAbort(weakChild) {
const parent = this.deref();
weakChild.deref()?.abort(parent?.signal.reason);
}
function removeAbortHandler(weakHandler) {
const parent = this.deref();
const handler = weakHandler.deref();
if (parent && handler) {
parent.signal.removeEventListener("abort", handler);
}
}
function createChildAbortController(parent, maxListeners) {
const child = createAbortController(maxListeners);
if (parent.signal.aborted) {
child.abort(parent.signal.reason);
return child;
}
const weakChild = new WeakRef(child);
const weakParent = new WeakRef(parent);
const handler = propagateAbort.bind(weakParent, weakChild);
parent.signal.addEventListener("abort", handler, { once: true });
child.signal.addEventListener("abort", removeAbortHandler.bind(weakParent, new WeakRef(handler)), { once: true });
return child;
}
var DEFAULT_MAX_LISTENERS = 50;
var init_abortController = () => {};
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/core.js
var require_core = __commonJS((exports, module) => {
function deepFreeze(obj) {
if (obj instanceof Map) {
obj.clear = obj.delete = obj.set = function() {
throw new Error("map is read-only");
};
} else if (obj instanceof Set) {
obj.add = obj.clear = obj.delete = function() {
throw new Error("set is read-only");
};
}
Object.freeze(obj);
Object.getOwnPropertyNames(obj).forEach((name3) => {
const prop = obj[name3];
const type = typeof prop;
if ((type === "object" || type === "function") && !Object.isFrozen(prop)) {
deepFreeze(prop);
}
});
return obj;
}
class Response3 {
constructor(mode) {
if (mode.data === undefined)
mode.data = {};
this.data = mode.data;
this.isMatchIgnored = false;
}
ignoreMatch() {
this.isMatchIgnored = true;
}
}
function escapeHTML(value) {
return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function inherit$1(original, ...objects) {
const result = Object.create(null);
for (const key in original) {
result[key] = original[key];
}
objects.forEach(function(obj) {
for (const key in obj) {
result[key] = obj[key];
}
});
return result;
}
var SPAN_CLOSE = "";
var emitsWrappingTags = (node) => {
return !!node.scope;
};
var scopeToCSSClass = (name3, { prefix }) => {
if (name3.startsWith("language:")) {
return name3.replace("language:", "language-");
}
if (name3.includes(".")) {
const pieces = name3.split(".");
return [
`${prefix}${pieces.shift()}`,
...pieces.map((x5, i4) => `${x5}${"_".repeat(i4 + 1)}`)
].join(" ");
}
return `${prefix}${name3}`;
};
class HTMLRenderer {
constructor(parseTree2, options) {
this.buffer = "";
this.classPrefix = options.classPrefix;
parseTree2.walk(this);
}
addText(text) {
this.buffer += escapeHTML(text);
}
openNode(node) {
if (!emitsWrappingTags(node))
return;
const className = scopeToCSSClass(node.scope, { prefix: this.classPrefix });
this.span(className);
}
closeNode(node) {
if (!emitsWrappingTags(node))
return;
this.buffer += SPAN_CLOSE;
}
value() {
return this.buffer;
}
span(className) {
this.buffer += ``;
}
}
var newNode = (opts = {}) => {
const result = { children: [] };
Object.assign(result, opts);
return result;
};
class TokenTree {
constructor() {
this.rootNode = newNode();
this.stack = [this.rootNode];
}
get top() {
return this.stack[this.stack.length - 1];
}
get root() {
return this.rootNode;
}
add(node) {
this.top.children.push(node);
}
openNode(scope) {
const node = newNode({ scope });
this.add(node);
this.stack.push(node);
}
closeNode() {
if (this.stack.length > 1) {
return this.stack.pop();
}
return;
}
closeAllNodes() {
while (this.closeNode())
;
}
toJSON() {
return JSON.stringify(this.rootNode, null, 4);
}
walk(builder) {
return this.constructor._walk(builder, this.rootNode);
}
static _walk(builder, node) {
if (typeof node === "string") {
builder.addText(node);
} else if (node.children) {
builder.openNode(node);
node.children.forEach((child) => this._walk(builder, child));
builder.closeNode(node);
}
return builder;
}
static _collapse(node) {
if (typeof node === "string")
return;
if (!node.children)
return;
if (node.children.every((el) => typeof el === "string")) {
node.children = [node.children.join("")];
} else {
node.children.forEach((child) => {
TokenTree._collapse(child);
});
}
}
}
class TokenTreeEmitter extends TokenTree {
constructor(options) {
super();
this.options = options;
}
addText(text) {
if (text === "") {
return;
}
this.add(text);
}
startScope(scope) {
this.openNode(scope);
}
endScope() {
this.closeNode();
}
__addSublanguage(emitter, name3) {
const node = emitter.root;
if (name3)
node.scope = `language:${name3}`;
this.add(node);
}
toHTML() {
const renderer = new HTMLRenderer(this, this.options);
return renderer.value();
}
finalize() {
this.closeAllNodes();
return true;
}
}
function source(re2) {
if (!re2)
return null;
if (typeof re2 === "string")
return re2;
return re2.source;
}
function lookahead(re2) {
return concat2("(?=", re2, ")");
}
function anyNumberOfTimes(re2) {
return concat2("(?:", re2, ")*");
}
function optional2(re2) {
return concat2("(?:", re2, ")?");
}
function concat2(...args) {
const joined = args.map((x5) => source(x5)).join("");
return joined;
}
function stripOptionsFromArgs(args) {
const opts = args[args.length - 1];
if (typeof opts === "object" && opts.constructor === Object) {
args.splice(args.length - 1, 1);
return opts;
} else {
return {};
}
}
function either(...args) {
const opts = stripOptionsFromArgs(args);
const joined = "(" + (opts.capture ? "" : "?:") + args.map((x5) => source(x5)).join("|") + ")";
return joined;
}
function countMatchGroups(re2) {
return new RegExp(re2.toString() + "|").exec("").length - 1;
}
function startsWith(re2, lexeme) {
const match = re2 && re2.exec(lexeme);
return match && match.index === 0;
}
var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
function _rewriteBackreferences(regexps, { joinWith }) {
let numCaptures = 0;
return regexps.map((regex2) => {
numCaptures += 1;
const offset = numCaptures;
let re2 = source(regex2);
let out = "";
while (re2.length > 0) {
const match = BACKREF_RE.exec(re2);
if (!match) {
out += re2;
break;
}
out += re2.substring(0, match.index);
re2 = re2.substring(match.index + match[0].length);
if (match[0][0] === "\\" && match[1]) {
out += "\\" + String(Number(match[1]) + offset);
} else {
out += match[0];
if (match[0] === "(") {
numCaptures++;
}
}
}
return out;
}).map((re2) => `(${re2})`).join(joinWith);
}
var MATCH_NOTHING_RE = /\b\B/;
var IDENT_RE = "[a-zA-Z]\\w*";
var UNDERSCORE_IDENT_RE = "[a-zA-Z_]\\w*";
var NUMBER_RE = "\\b\\d+(\\.\\d+)?";
var C_NUMBER_RE = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";
var BINARY_NUMBER_RE = "\\b(0b[01]+)";
var RE_STARTERS_RE = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";
var SHEBANG = (opts = {}) => {
const beginShebang = /^#![ ]*\//;
if (opts.binary) {
opts.begin = concat2(beginShebang, /.*\b/, opts.binary, /\b.*/);
}
return inherit$1({
scope: "meta",
begin: beginShebang,
end: /$/,
relevance: 0,
"on:begin": (m3, resp) => {
if (m3.index !== 0)
resp.ignoreMatch();
}
}, opts);
};
var BACKSLASH_ESCAPE = {
begin: "\\\\[\\s\\S]",
relevance: 0
};
var APOS_STRING_MODE = {
scope: "string",
begin: "'",
end: "'",
illegal: "\\n",
contains: [BACKSLASH_ESCAPE]
};
var QUOTE_STRING_MODE = {
scope: "string",
begin: '"',
end: '"',
illegal: "\\n",
contains: [BACKSLASH_ESCAPE]
};
var PHRASAL_WORDS_MODE = {
begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
};
var COMMENT = function(begin, end, modeOptions = {}) {
const mode = inherit$1({
scope: "comment",
begin,
end,
contains: []
}, modeOptions);
mode.contains.push({
scope: "doctag",
begin: "[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",
end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
excludeBegin: true,
relevance: 0
});
const ENGLISH_WORD = either("I", "a", "is", "so", "us", "to", "at", "if", "in", "it", "on", /[A-Za-z]+['](d|ve|re|ll|t|s|n)/, /[A-Za-z]+[-][a-z]+/, /[A-Za-z][a-z]{2,}/);
mode.contains.push({
begin: concat2(/[ ]+/, "(", ENGLISH_WORD, /[.]?[:]?([.][ ]|[ ])/, "){3}")
});
return mode;
};
var C_LINE_COMMENT_MODE = COMMENT("//", "$");
var C_BLOCK_COMMENT_MODE = COMMENT("/\\*", "\\*/");
var HASH_COMMENT_MODE = COMMENT("#", "$");
var NUMBER_MODE = {
scope: "number",
begin: NUMBER_RE,
relevance: 0
};
var C_NUMBER_MODE = {
scope: "number",
begin: C_NUMBER_RE,
relevance: 0
};
var BINARY_NUMBER_MODE = {
scope: "number",
begin: BINARY_NUMBER_RE,
relevance: 0
};
var REGEXP_MODE = {
scope: "regexp",
begin: /\/(?=[^/\n]*\/)/,
end: /\/[gimuy]*/,
contains: [
BACKSLASH_ESCAPE,
{
begin: /\[/,
end: /\]/,
relevance: 0,
contains: [BACKSLASH_ESCAPE]
}
]
};
var TITLE_MODE = {
scope: "title",
begin: IDENT_RE,
relevance: 0
};
var UNDERSCORE_TITLE_MODE = {
scope: "title",
begin: UNDERSCORE_IDENT_RE,
relevance: 0
};
var METHOD_GUARD = {
begin: "\\.\\s*" + UNDERSCORE_IDENT_RE,
relevance: 0
};
var END_SAME_AS_BEGIN = function(mode) {
return Object.assign(mode, {
"on:begin": (m3, resp) => {
resp.data._beginMatch = m3[1];
},
"on:end": (m3, resp) => {
if (resp.data._beginMatch !== m3[1])
resp.ignoreMatch();
}
});
};
var MODES = /* @__PURE__ */ Object.freeze({
__proto__: null,
APOS_STRING_MODE,
BACKSLASH_ESCAPE,
BINARY_NUMBER_MODE,
BINARY_NUMBER_RE,
COMMENT,
C_BLOCK_COMMENT_MODE,
C_LINE_COMMENT_MODE,
C_NUMBER_MODE,
C_NUMBER_RE,
END_SAME_AS_BEGIN,
HASH_COMMENT_MODE,
IDENT_RE,
MATCH_NOTHING_RE,
METHOD_GUARD,
NUMBER_MODE,
NUMBER_RE,
PHRASAL_WORDS_MODE,
QUOTE_STRING_MODE,
REGEXP_MODE,
RE_STARTERS_RE,
SHEBANG,
TITLE_MODE,
UNDERSCORE_IDENT_RE,
UNDERSCORE_TITLE_MODE
});
function skipIfHasPrecedingDot(match, response) {
const before = match.input[match.index - 1];
if (before === ".") {
response.ignoreMatch();
}
}
function scopeClassName(mode, _parent) {
if (mode.className !== undefined) {
mode.scope = mode.className;
delete mode.className;
}
}
function beginKeywords(mode, parent) {
if (!parent)
return;
if (!mode.beginKeywords)
return;
mode.begin = "\\b(" + mode.beginKeywords.split(" ").join("|") + ")(?!\\.)(?=\\b|\\s)";
mode.__beforeBegin = skipIfHasPrecedingDot;
mode.keywords = mode.keywords || mode.beginKeywords;
delete mode.beginKeywords;
if (mode.relevance === undefined)
mode.relevance = 0;
}
function compileIllegal(mode, _parent) {
if (!Array.isArray(mode.illegal))
return;
mode.illegal = either(...mode.illegal);
}
function compileMatch(mode, _parent) {
if (!mode.match)
return;
if (mode.begin || mode.end)
throw new Error("begin & end are not supported with match");
mode.begin = mode.match;
delete mode.match;
}
function compileRelevance(mode, _parent) {
if (mode.relevance === undefined)
mode.relevance = 1;
}
var beforeMatchExt = (mode, parent) => {
if (!mode.beforeMatch)
return;
if (mode.starts)
throw new Error("beforeMatch cannot be used with starts");
const originalMode = Object.assign({}, mode);
Object.keys(mode).forEach((key) => {
delete mode[key];
});
mode.keywords = originalMode.keywords;
mode.begin = concat2(originalMode.beforeMatch, lookahead(originalMode.begin));
mode.starts = {
relevance: 0,
contains: [
Object.assign(originalMode, { endsParent: true })
]
};
mode.relevance = 0;
delete originalMode.beforeMatch;
};
var COMMON_KEYWORDS = [
"of",
"and",
"for",
"in",
"not",
"or",
"if",
"then",
"parent",
"list",
"value"
];
var DEFAULT_KEYWORD_SCOPE = "keyword";
function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
const compiledKeywords = Object.create(null);
if (typeof rawKeywords === "string") {
compileList(scopeName, rawKeywords.split(" "));
} else if (Array.isArray(rawKeywords)) {
compileList(scopeName, rawKeywords);
} else {
Object.keys(rawKeywords).forEach(function(scopeName2) {
Object.assign(compiledKeywords, compileKeywords(rawKeywords[scopeName2], caseInsensitive, scopeName2));
});
}
return compiledKeywords;
function compileList(scopeName2, keywordList) {
if (caseInsensitive) {
keywordList = keywordList.map((x5) => x5.toLowerCase());
}
keywordList.forEach(function(keyword) {
const pair = keyword.split("|");
compiledKeywords[pair[0]] = [scopeName2, scoreForKeyword(pair[0], pair[1])];
});
}
}
function scoreForKeyword(keyword, providedScore) {
if (providedScore) {
return Number(providedScore);
}
return commonKeyword(keyword) ? 0 : 1;
}
function commonKeyword(keyword) {
return COMMON_KEYWORDS.includes(keyword.toLowerCase());
}
var seenDeprecations = {};
var error52 = (message) => {
console.error(message);
};
var warn = (message, ...args) => {
console.log(`WARN: ${message}`, ...args);
};
var deprecated = (version7, message) => {
if (seenDeprecations[`${version7}/${message}`])
return;
console.log(`Deprecated as of ${version7}. ${message}`);
seenDeprecations[`${version7}/${message}`] = true;
};
var MultiClassError = new Error;
function remapScopeNames(mode, regexes, { key }) {
let offset = 0;
const scopeNames = mode[key];
const emit = {};
const positions = {};
for (let i4 = 1;i4 <= regexes.length; i4++) {
positions[i4 + offset] = scopeNames[i4];
emit[i4 + offset] = true;
offset += countMatchGroups(regexes[i4 - 1]);
}
mode[key] = positions;
mode[key]._emit = emit;
mode[key]._multi = true;
}
function beginMultiClass(mode) {
if (!Array.isArray(mode.begin))
return;
if (mode.skip || mode.excludeBegin || mode.returnBegin) {
error52("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
throw MultiClassError;
}
if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
error52("beginScope must be object");
throw MultiClassError;
}
remapScopeNames(mode, mode.begin, { key: "beginScope" });
mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" });
}
function endMultiClass(mode) {
if (!Array.isArray(mode.end))
return;
if (mode.skip || mode.excludeEnd || mode.returnEnd) {
error52("skip, excludeEnd, returnEnd not compatible with endScope: {}");
throw MultiClassError;
}
if (typeof mode.endScope !== "object" || mode.endScope === null) {
error52("endScope must be object");
throw MultiClassError;
}
remapScopeNames(mode, mode.end, { key: "endScope" });
mode.end = _rewriteBackreferences(mode.end, { joinWith: "" });
}
function scopeSugar(mode) {
if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) {
mode.beginScope = mode.scope;
delete mode.scope;
}
}
function MultiClass(mode) {
scopeSugar(mode);
if (typeof mode.beginScope === "string") {
mode.beginScope = { _wrap: mode.beginScope };
}
if (typeof mode.endScope === "string") {
mode.endScope = { _wrap: mode.endScope };
}
beginMultiClass(mode);
endMultiClass(mode);
}
function compileLanguage(language) {
function langRe(value, global3) {
return new RegExp(source(value), "m" + (language.case_insensitive ? "i" : "") + (language.unicodeRegex ? "u" : "") + (global3 ? "g" : ""));
}
class MultiRegex {
constructor() {
this.matchIndexes = {};
this.regexes = [];
this.matchAt = 1;
this.position = 0;
}
addRule(re2, opts) {
opts.position = this.position++;
this.matchIndexes[this.matchAt] = opts;
this.regexes.push([opts, re2]);
this.matchAt += countMatchGroups(re2) + 1;
}
compile() {
if (this.regexes.length === 0) {
this.exec = () => null;
}
const terminators = this.regexes.map((el) => el[1]);
this.matcherRe = langRe(_rewriteBackreferences(terminators, { joinWith: "|" }), true);
this.lastIndex = 0;
}
exec(s2) {
this.matcherRe.lastIndex = this.lastIndex;
const match = this.matcherRe.exec(s2);
if (!match) {
return null;
}
const i4 = match.findIndex((el, i5) => i5 > 0 && el !== undefined);
const matchData = this.matchIndexes[i4];
match.splice(0, i4);
return Object.assign(match, matchData);
}
}
class ResumableMultiRegex {
constructor() {
this.rules = [];
this.multiRegexes = [];
this.count = 0;
this.lastIndex = 0;
this.regexIndex = 0;
}
getMatcher(index) {
if (this.multiRegexes[index])
return this.multiRegexes[index];
const matcher = new MultiRegex;
this.rules.slice(index).forEach(([re2, opts]) => matcher.addRule(re2, opts));
matcher.compile();
this.multiRegexes[index] = matcher;
return matcher;
}
resumingScanAtSamePosition() {
return this.regexIndex !== 0;
}
considerAll() {
this.regexIndex = 0;
}
addRule(re2, opts) {
this.rules.push([re2, opts]);
if (opts.type === "begin")
this.count++;
}
exec(s2) {
const m3 = this.getMatcher(this.regexIndex);
m3.lastIndex = this.lastIndex;
let result = m3.exec(s2);
if (this.resumingScanAtSamePosition()) {
if (result && result.index === this.lastIndex)
;
else {
const m22 = this.getMatcher(0);
m22.lastIndex = this.lastIndex + 1;
result = m22.exec(s2);
}
}
if (result) {
this.regexIndex += result.position + 1;
if (this.regexIndex === this.count) {
this.considerAll();
}
}
return result;
}
}
function buildModeRegex(mode) {
const mm = new ResumableMultiRegex;
mode.contains.forEach((term) => mm.addRule(term.begin, { rule: term, type: "begin" }));
if (mode.terminatorEnd) {
mm.addRule(mode.terminatorEnd, { type: "end" });
}
if (mode.illegal) {
mm.addRule(mode.illegal, { type: "illegal" });
}
return mm;
}
function compileMode(mode, parent) {
const cmode = mode;
if (mode.isCompiled)
return cmode;
[
scopeClassName,
compileMatch,
MultiClass,
beforeMatchExt
].forEach((ext) => ext(mode, parent));
language.compilerExtensions.forEach((ext) => ext(mode, parent));
mode.__beforeBegin = null;
[
beginKeywords,
compileIllegal,
compileRelevance
].forEach((ext) => ext(mode, parent));
mode.isCompiled = true;
let keywordPattern = null;
if (typeof mode.keywords === "object" && mode.keywords.$pattern) {
mode.keywords = Object.assign({}, mode.keywords);
keywordPattern = mode.keywords.$pattern;
delete mode.keywords.$pattern;
}
keywordPattern = keywordPattern || /\w+/;
if (mode.keywords) {
mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
}
cmode.keywordPatternRe = langRe(keywordPattern, true);
if (parent) {
if (!mode.begin)
mode.begin = /\B|\b/;
cmode.beginRe = langRe(cmode.begin);
if (!mode.end && !mode.endsWithParent)
mode.end = /\B|\b/;
if (mode.end)
cmode.endRe = langRe(cmode.end);
cmode.terminatorEnd = source(cmode.end) || "";
if (mode.endsWithParent && parent.terminatorEnd) {
cmode.terminatorEnd += (mode.end ? "|" : "") + parent.terminatorEnd;
}
}
if (mode.illegal)
cmode.illegalRe = langRe(mode.illegal);
if (!mode.contains)
mode.contains = [];
mode.contains = [].concat(...mode.contains.map(function(c6) {
return expandOrCloneMode(c6 === "self" ? mode : c6);
}));
mode.contains.forEach(function(c6) {
compileMode(c6, cmode);
});
if (mode.starts) {
compileMode(mode.starts, parent);
}
cmode.matcher = buildModeRegex(cmode);
return cmode;
}
if (!language.compilerExtensions)
language.compilerExtensions = [];
if (language.contains && language.contains.includes("self")) {
throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");
}
language.classNameAliases = inherit$1(language.classNameAliases || {});
return compileMode(language);
}
function dependencyOnParent(mode) {
if (!mode)
return false;
return mode.endsWithParent || dependencyOnParent(mode.starts);
}
function expandOrCloneMode(mode) {
if (mode.variants && !mode.cachedVariants) {
mode.cachedVariants = mode.variants.map(function(variant) {
return inherit$1(mode, { variants: null }, variant);
});
}
if (mode.cachedVariants) {
return mode.cachedVariants;
}
if (dependencyOnParent(mode)) {
return inherit$1(mode, { starts: mode.starts ? inherit$1(mode.starts) : null });
}
if (Object.isFrozen(mode)) {
return inherit$1(mode);
}
return mode;
}
var version6 = "11.11.1";
class HTMLInjectionError extends Error {
constructor(reason, html) {
super(reason);
this.name = "HTMLInjectionError";
this.html = html;
}
}
var escape2 = escapeHTML;
var inherit = inherit$1;
var NO_MATCH = Symbol("nomatch");
var MAX_KEYWORD_HITS = 7;
var HLJS = function(hljs) {
const languages = Object.create(null);
const aliases = Object.create(null);
const plugins = [];
let SAFE_MODE = true;
const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: "Plain text", contains: [] };
let options = {
ignoreUnescapedHTML: false,
throwUnescapedHTML: false,
noHighlightRe: /^(no-?highlight)$/i,
languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
classPrefix: "hljs-",
cssSelector: "pre code",
languages: null,
__emitter: TokenTreeEmitter
};
function shouldNotHighlight(languageName) {
return options.noHighlightRe.test(languageName);
}
function blockLanguage(block) {
let classes = block.className + " ";
classes += block.parentNode ? block.parentNode.className : "";
const match = options.languageDetectRe.exec(classes);
if (match) {
const language = getLanguage(match[1]);
if (!language) {
warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
warn("Falling back to no-highlight mode for this block.", block);
}
return language ? match[1] : "no-highlight";
}
return classes.split(/\s+/).find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
}
function highlight2(codeOrLanguageName, optionsOrCode, ignoreIllegals) {
let code = "";
let languageName = "";
if (typeof optionsOrCode === "object") {
code = codeOrLanguageName;
ignoreIllegals = optionsOrCode.ignoreIllegals;
languageName = optionsOrCode.language;
} else {
deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
deprecated("10.7.0", `Please use highlight(code, options) instead.
https://github.com/highlightjs/highlight.js/issues/2277`);
languageName = codeOrLanguageName;
code = optionsOrCode;
}
if (ignoreIllegals === undefined) {
ignoreIllegals = true;
}
const context3 = {
code,
language: languageName
};
fire("before:highlight", context3);
const result = context3.result ? context3.result : _highlight(context3.language, context3.code, ignoreIllegals);
result.code = context3.code;
fire("after:highlight", result);
return result;
}
function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
const keywordHits = Object.create(null);
function keywordData(mode, matchText) {
return mode.keywords[matchText];
}
function processKeywords() {
if (!top.keywords) {
emitter.addText(modeBuffer);
return;
}
let lastIndex = 0;
top.keywordPatternRe.lastIndex = 0;
let match = top.keywordPatternRe.exec(modeBuffer);
let buf = "";
while (match) {
buf += modeBuffer.substring(lastIndex, match.index);
const word = language.case_insensitive ? match[0].toLowerCase() : match[0];
const data = keywordData(top, word);
if (data) {
const [kind, keywordRelevance] = data;
emitter.addText(buf);
buf = "";
keywordHits[word] = (keywordHits[word] || 0) + 1;
if (keywordHits[word] <= MAX_KEYWORD_HITS)
relevance += keywordRelevance;
if (kind.startsWith("_")) {
buf += match[0];
} else {
const cssClass = language.classNameAliases[kind] || kind;
emitKeyword(match[0], cssClass);
}
} else {
buf += match[0];
}
lastIndex = top.keywordPatternRe.lastIndex;
match = top.keywordPatternRe.exec(modeBuffer);
}
buf += modeBuffer.substring(lastIndex);
emitter.addText(buf);
}
function processSubLanguage() {
if (modeBuffer === "")
return;
let result2 = null;
if (typeof top.subLanguage === "string") {
if (!languages[top.subLanguage]) {
emitter.addText(modeBuffer);
return;
}
result2 = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
continuations[top.subLanguage] = result2._top;
} else {
result2 = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
}
if (top.relevance > 0) {
relevance += result2.relevance;
}
emitter.__addSublanguage(result2._emitter, result2.language);
}
function processBuffer() {
if (top.subLanguage != null) {
processSubLanguage();
} else {
processKeywords();
}
modeBuffer = "";
}
function emitKeyword(keyword, scope) {
if (keyword === "")
return;
emitter.startScope(scope);
emitter.addText(keyword);
emitter.endScope();
}
function emitMultiClass(scope, match) {
let i4 = 1;
const max2 = match.length - 1;
while (i4 <= max2) {
if (!scope._emit[i4]) {
i4++;
continue;
}
const klass = language.classNameAliases[scope[i4]] || scope[i4];
const text = match[i4];
if (klass) {
emitKeyword(text, klass);
} else {
modeBuffer = text;
processKeywords();
modeBuffer = "";
}
i4++;
}
}
function startNewMode(mode, match) {
if (mode.scope && typeof mode.scope === "string") {
emitter.openNode(language.classNameAliases[mode.scope] || mode.scope);
}
if (mode.beginScope) {
if (mode.beginScope._wrap) {
emitKeyword(modeBuffer, language.classNameAliases[mode.beginScope._wrap] || mode.beginScope._wrap);
modeBuffer = "";
} else if (mode.beginScope._multi) {
emitMultiClass(mode.beginScope, match);
modeBuffer = "";
}
}
top = Object.create(mode, { parent: { value: top } });
return top;
}
function endOfMode(mode, match, matchPlusRemainder) {
let matched = startsWith(mode.endRe, matchPlusRemainder);
if (matched) {
if (mode["on:end"]) {
const resp = new Response3(mode);
mode["on:end"](match, resp);
if (resp.isMatchIgnored)
matched = false;
}
if (matched) {
while (mode.endsParent && mode.parent) {
mode = mode.parent;
}
return mode;
}
}
if (mode.endsWithParent) {
return endOfMode(mode.parent, match, matchPlusRemainder);
}
}
function doIgnore(lexeme) {
if (top.matcher.regexIndex === 0) {
modeBuffer += lexeme[0];
return 1;
} else {
resumeScanAtSamePosition = true;
return 0;
}
}
function doBeginMatch(match) {
const lexeme = match[0];
const newMode = match.rule;
const resp = new Response3(newMode);
const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
for (const cb of beforeCallbacks) {
if (!cb)
continue;
cb(match, resp);
if (resp.isMatchIgnored)
return doIgnore(lexeme);
}
if (newMode.skip) {
modeBuffer += lexeme;
} else {
if (newMode.excludeBegin) {
modeBuffer += lexeme;
}
processBuffer();
if (!newMode.returnBegin && !newMode.excludeBegin) {
modeBuffer = lexeme;
}
}
startNewMode(newMode, match);
return newMode.returnBegin ? 0 : lexeme.length;
}
function doEndMatch(match) {
const lexeme = match[0];
const matchPlusRemainder = codeToHighlight.substring(match.index);
const endMode = endOfMode(top, match, matchPlusRemainder);
if (!endMode) {
return NO_MATCH;
}
const origin2 = top;
if (top.endScope && top.endScope._wrap) {
processBuffer();
emitKeyword(lexeme, top.endScope._wrap);
} else if (top.endScope && top.endScope._multi) {
processBuffer();
emitMultiClass(top.endScope, match);
} else if (origin2.skip) {
modeBuffer += lexeme;
} else {
if (!(origin2.returnEnd || origin2.excludeEnd)) {
modeBuffer += lexeme;
}
processBuffer();
if (origin2.excludeEnd) {
modeBuffer = lexeme;
}
}
do {
if (top.scope) {
emitter.closeNode();
}
if (!top.skip && !top.subLanguage) {
relevance += top.relevance;
}
top = top.parent;
} while (top !== endMode.parent);
if (endMode.starts) {
startNewMode(endMode.starts, match);
}
return origin2.returnEnd ? 0 : lexeme.length;
}
function processContinuations() {
const list = [];
for (let current = top;current !== language; current = current.parent) {
if (current.scope) {
list.unshift(current.scope);
}
}
list.forEach((item) => emitter.openNode(item));
}
let lastMatch = {};
function processLexeme(textBeforeMatch, match) {
const lexeme = match && match[0];
modeBuffer += textBeforeMatch;
if (lexeme == null) {
processBuffer();
return 0;
}
if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
modeBuffer += codeToHighlight.slice(match.index, match.index + 1);
if (!SAFE_MODE) {
const err2 = new Error(`0 width match regex (${languageName})`);
err2.languageName = languageName;
err2.badRule = lastMatch.rule;
throw err2;
}
return 1;
}
lastMatch = match;
if (match.type === "begin") {
return doBeginMatch(match);
} else if (match.type === "illegal" && !ignoreIllegals) {
const err2 = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.scope || "") + '"');
err2.mode = top;
throw err2;
} else if (match.type === "end") {
const processed = doEndMatch(match);
if (processed !== NO_MATCH) {
return processed;
}
}
if (match.type === "illegal" && lexeme === "") {
modeBuffer += `
`;
return 1;
}
if (iterations > 1e5 && iterations > match.index * 3) {
const err2 = new Error("potential infinite loop, way more iterations than matches");
throw err2;
}
modeBuffer += lexeme;
return lexeme.length;
}
const language = getLanguage(languageName);
if (!language) {
error52(LANGUAGE_NOT_FOUND.replace("{}", languageName));
throw new Error('Unknown language: "' + languageName + '"');
}
const md = compileLanguage(language);
let result = "";
let top = continuation || md;
const continuations = {};
const emitter = new options.__emitter(options);
processContinuations();
let modeBuffer = "";
let relevance = 0;
let index = 0;
let iterations = 0;
let resumeScanAtSamePosition = false;
try {
if (!language.__emitTokens) {
top.matcher.considerAll();
for (;; ) {
iterations++;
if (resumeScanAtSamePosition) {
resumeScanAtSamePosition = false;
} else {
top.matcher.considerAll();
}
top.matcher.lastIndex = index;
const match = top.matcher.exec(codeToHighlight);
if (!match)
break;
const beforeMatch = codeToHighlight.substring(index, match.index);
const processedCount = processLexeme(beforeMatch, match);
index = match.index + processedCount;
}
processLexeme(codeToHighlight.substring(index));
} else {
language.__emitTokens(codeToHighlight, emitter);
}
emitter.finalize();
result = emitter.toHTML();
return {
language: languageName,
value: result,
relevance,
illegal: false,
_emitter: emitter,
_top: top
};
} catch (err2) {
if (err2.message && err2.message.includes("Illegal")) {
return {
language: languageName,
value: escape2(codeToHighlight),
illegal: true,
relevance: 0,
_illegalBy: {
message: err2.message,
index,
context: codeToHighlight.slice(index - 100, index + 100),
mode: err2.mode,
resultSoFar: result
},
_emitter: emitter
};
} else if (SAFE_MODE) {
return {
language: languageName,
value: escape2(codeToHighlight),
illegal: false,
relevance: 0,
errorRaised: err2,
_emitter: emitter,
_top: top
};
} else {
throw err2;
}
}
}
function justTextHighlightResult(code) {
const result = {
value: escape2(code),
illegal: false,
relevance: 0,
_top: PLAINTEXT_LANGUAGE,
_emitter: new options.__emitter(options)
};
result._emitter.addText(code);
return result;
}
function highlightAuto(code, languageSubset) {
languageSubset = languageSubset || options.languages || Object.keys(languages);
const plaintext = justTextHighlightResult(code);
const results = languageSubset.filter(getLanguage).filter(autoDetection).map((name3) => _highlight(name3, code, false));
results.unshift(plaintext);
const sorted = results.sort((a2, b3) => {
if (a2.relevance !== b3.relevance)
return b3.relevance - a2.relevance;
if (a2.language && b3.language) {
if (getLanguage(a2.language).supersetOf === b3.language) {
return 1;
} else if (getLanguage(b3.language).supersetOf === a2.language) {
return -1;
}
}
return 0;
});
const [best, secondBest] = sorted;
const result = best;
result.secondBest = secondBest;
return result;
}
function updateClassName(element, currentLang, resultLang) {
const language = currentLang && aliases[currentLang] || resultLang;
element.classList.add("hljs");
element.classList.add(`language-${language}`);
}
function highlightElement(element) {
let node = null;
const language = blockLanguage(element);
if (shouldNotHighlight(language))
return;
fire("before:highlightElement", { el: element, language });
if (element.dataset.highlighted) {
console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.", element);
return;
}
if (element.children.length > 0) {
if (!options.ignoreUnescapedHTML) {
console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk.");
console.warn("https://github.com/highlightjs/highlight.js/wiki/security");
console.warn("The element with unescaped HTML:");
console.warn(element);
}
if (options.throwUnescapedHTML) {
const err2 = new HTMLInjectionError("One of your code blocks includes unescaped HTML.", element.innerHTML);
throw err2;
}
}
node = element;
const text = node.textContent;
const result = language ? highlight2(text, { language, ignoreIllegals: true }) : highlightAuto(text);
element.innerHTML = result.value;
element.dataset.highlighted = "yes";
updateClassName(element, language, result.language);
element.result = {
language: result.language,
re: result.relevance,
relevance: result.relevance
};
if (result.secondBest) {
element.secondBest = {
language: result.secondBest.language,
relevance: result.secondBest.relevance
};
}
fire("after:highlightElement", { el: element, result, text });
}
function configure(userOptions) {
options = inherit(options, userOptions);
}
const initHighlighting = () => {
highlightAll();
deprecated("10.6.0", "initHighlighting() deprecated. Use highlightAll() now.");
};
function initHighlightingOnLoad() {
highlightAll();
deprecated("10.6.0", "initHighlightingOnLoad() deprecated. Use highlightAll() now.");
}
let wantsHighlight = false;
function highlightAll() {
function boot() {
highlightAll();
}
if (document.readyState === "loading") {
if (!wantsHighlight) {
window.addEventListener("DOMContentLoaded", boot, false);
}
wantsHighlight = true;
return;
}
const blocks = document.querySelectorAll(options.cssSelector);
blocks.forEach(highlightElement);
}
function registerLanguage(languageName, languageDefinition) {
let lang = null;
try {
lang = languageDefinition(hljs);
} catch (error$1) {
error52("Language definition for '{}' could not be registered.".replace("{}", languageName));
if (!SAFE_MODE) {
throw error$1;
} else {
error52(error$1);
}
lang = PLAINTEXT_LANGUAGE;
}
if (!lang.name)
lang.name = languageName;
languages[languageName] = lang;
lang.rawDefinition = languageDefinition.bind(null, hljs);
if (lang.aliases) {
registerAliases(lang.aliases, { languageName });
}
}
function unregisterLanguage(languageName) {
delete languages[languageName];
for (const alias of Object.keys(aliases)) {
if (aliases[alias] === languageName) {
delete aliases[alias];
}
}
}
function listLanguages() {
return Object.keys(languages);
}
function getLanguage(name3) {
name3 = (name3 || "").toLowerCase();
return languages[name3] || languages[aliases[name3]];
}
function registerAliases(aliasList, { languageName }) {
if (typeof aliasList === "string") {
aliasList = [aliasList];
}
aliasList.forEach((alias) => {
aliases[alias.toLowerCase()] = languageName;
});
}
function autoDetection(name3) {
const lang = getLanguage(name3);
return lang && !lang.disableAutodetect;
}
function upgradePluginAPI(plugin) {
if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
plugin["before:highlightElement"] = (data) => {
plugin["before:highlightBlock"](Object.assign({ block: data.el }, data));
};
}
if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
plugin["after:highlightElement"] = (data) => {
plugin["after:highlightBlock"](Object.assign({ block: data.el }, data));
};
}
}
function addPlugin(plugin) {
upgradePluginAPI(plugin);
plugins.push(plugin);
}
function removePlugin(plugin) {
const index = plugins.indexOf(plugin);
if (index !== -1) {
plugins.splice(index, 1);
}
}
function fire(event, args) {
const cb = event;
plugins.forEach(function(plugin) {
if (plugin[cb]) {
plugin[cb](args);
}
});
}
function deprecateHighlightBlock(el) {
deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
deprecated("10.7.0", "Please use highlightElement now.");
return highlightElement(el);
}
Object.assign(hljs, {
highlight: highlight2,
highlightAuto,
highlightAll,
highlightElement,
highlightBlock: deprecateHighlightBlock,
configure,
initHighlighting,
initHighlightingOnLoad,
registerLanguage,
unregisterLanguage,
listLanguages,
getLanguage,
registerAliases,
autoDetection,
inherit,
addPlugin,
removePlugin
});
hljs.debugMode = function() {
SAFE_MODE = false;
};
hljs.safeMode = function() {
SAFE_MODE = true;
};
hljs.versionString = version6;
hljs.regex = {
concat: concat2,
lookahead,
either,
optional: optional2,
anyNumberOfTimes
};
for (const key in MODES) {
if (typeof MODES[key] === "object") {
deepFreeze(MODES[key]);
}
}
Object.assign(hljs, MODES);
return hljs;
};
var highlight = HLJS({});
highlight.newInstance = () => HLJS({});
module.exports = highlight;
highlight.HighlightJS = highlight;
highlight.default = highlight;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/1c.js
var require_1c = __commonJS((exports, module) => {
function _1c(hljs) {
const UNDERSCORE_IDENT_RE = "[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+";
const v7_keywords = "далее ";
const v8_keywords = "возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли " + "конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт ";
const KEYWORD = v7_keywords + v8_keywords;
const v7_meta_keywords = "загрузитьизфайла ";
const v8_meta_keywords = "вебклиент вместо внешнеесоединение клиент конецобласти мобильноеприложениеклиент мобильноеприложениесервер " + "наклиенте наклиентенасервере наклиентенасерверебезконтекста насервере насерверебезконтекста область перед " + "после сервер толстыйклиентобычноеприложение толстыйклиентуправляемоеприложение тонкийклиент ";
const METAKEYWORD = v7_meta_keywords + v8_meta_keywords;
const v7_system_constants = "разделительстраниц разделительстрок символтабуляции ";
const v7_global_context_methods = "ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов " + "датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя " + "кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца " + "коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид " + "назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца " + "начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов " + "основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута " + "получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта " + "префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына " + "рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента " + "счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон ";
const v8_global_context_methods = "acos asin atan base64значение base64строка cos exp log log10 pow sin sqrt tan xmlзначение xmlстрока " + "xmlтип xmlтипзнч активноеокно безопасныйрежим безопасныйрежимразделенияданных булево ввестидату ввестизначение " + "ввестистроку ввестичисло возможностьчтенияxml вопрос восстановитьзначение врег выгрузитьжурналрегистрации " + "выполнитьобработкуоповещения выполнитьпроверкуправдоступа вычислить год данныеформывзначение дата день деньгода " + "деньнедели добавитьмесяц заблокироватьданныедляредактирования заблокироватьработупользователя завершитьработусистемы " + "загрузитьвнешнююкомпоненту закрытьсправку записатьjson записатьxml записатьдатуjson записьжурналарегистрации " + "заполнитьзначениясвойств запроситьразрешениепользователя запуститьприложение запуститьсистему зафиксироватьтранзакцию " + "значениевданныеформы значениевстрокувнутр значениевфайл значениезаполнено значениеизстрокивнутр значениеизфайла " + "изxmlтипа импортмоделиxdto имякомпьютера имяпользователя инициализироватьпредопределенныеданные информацияобошибке " + "каталогбиблиотекимобильногоустройства каталогвременныхфайлов каталогдокументов каталогпрограммы кодироватьстроку " + "кодлокализацииинформационнойбазы кодсимвола командасистемы конецгода конецдня конецквартала конецмесяца конецминуты " + "конецнедели конецчаса конфигурациябазыданныхизмененадинамически конфигурацияизменена копироватьданныеформы " + "копироватьфайл краткоепредставлениеошибки лев макс местноевремя месяц мин минута монопольныйрежим найти " + "найтинедопустимыесимволыxml найтиокнопонавигационнойссылке найтипомеченныенаудаление найтипоссылкам найтифайлы " + "началогода началодня началоквартала началомесяца началоминуты началонедели началочаса начатьзапросразрешенияпользователя " + "начатьзапускприложения начатькопированиефайла начатьперемещениефайла начатьподключениевнешнейкомпоненты " + "начатьподключениерасширенияработыскриптографией начатьподключениерасширенияработысфайлами начатьпоискфайлов " + "начатьполучениекаталогавременныхфайлов начатьполучениекаталогадокументов начатьполучениерабочегокаталогаданныхпользователя " + "начатьполучениефайлов начатьпомещениефайла начатьпомещениефайлов начатьсозданиедвоичныхданныхизфайла начатьсозданиекаталога " + "начатьтранзакцию начатьудалениефайлов начатьустановкувнешнейкомпоненты начатьустановкурасширенияработыскриптографией " + "начатьустановкурасширенияработысфайлами неделягода необходимостьзавершениясоединения номерсеансаинформационнойбазы " + "номерсоединенияинформационнойбазы нрег нстр обновитьинтерфейс обновитьнумерациюобъектов обновитьповторноиспользуемыезначения " + "обработкапрерыванияпользователя объединитьфайлы окр описаниеошибки оповестить оповеститьобизменении " + "отключитьобработчикзапросанастроекклиенталицензирования отключитьобработчикожидания отключитьобработчикоповещения " + "открытьзначение открытьиндекссправки открытьсодержаниесправки открытьсправку открытьформу открытьформумодально " + "отменитьтранзакцию очиститьжурналрегистрации очиститьнастройкипользователя очиститьсообщения параметрыдоступа " + "перейтипонавигационнойссылке переместитьфайл подключитьвнешнююкомпоненту " + "подключитьобработчикзапросанастроекклиенталицензирования подключитьобработчикожидания подключитьобработчикоповещения " + "подключитьрасширениеработыскриптографией подключитьрасширениеработысфайлами подробноепредставлениеошибки " + "показатьвводдаты показатьвводзначения показатьвводстроки показатьвводчисла показатьвопрос показатьзначение " + "показатьинформациюобошибке показатьнакарте показатьоповещениепользователя показатьпредупреждение полноеимяпользователя " + "получитьcomобъект получитьxmlтип получитьадреспоместоположению получитьблокировкусеансов получитьвремязавершенияспящегосеанса " + "получитьвремязасыпанияпассивногосеанса получитьвремяожиданияблокировкиданных получитьданныевыбора " + "получитьдополнительныйпараметрклиенталицензирования получитьдопустимыекодылокализации получитьдопустимыечасовыепояса " + "получитьзаголовокклиентскогоприложения получитьзаголовоксистемы получитьзначенияотборажурналарегистрации " + "получитьидентификаторконфигурации получитьизвременногохранилища получитьимявременногофайла " + "получитьимяклиенталицензирования получитьинформациюэкрановклиента получитьиспользованиежурналарегистрации " + "получитьиспользованиесобытияжурналарегистрации получитькраткийзаголовокприложения получитьмакетоформления " + "получитьмаскувсефайлы получитьмаскувсефайлыклиента получитьмаскувсефайлысервера получитьместоположениепоадресу " + "получитьминимальнуюдлинупаролейпользователей получитьнавигационнуюссылку получитьнавигационнуюссылкуинформационнойбазы " + "получитьобновлениеконфигурациибазыданных получитьобновлениепредопределенныхданныхинформационнойбазы получитьобщиймакет " + "получитьобщуюформу получитьокна получитьоперативнуюотметкувремени получитьотключениебезопасногорежима " + "получитьпараметрыфункциональныхопцийинтерфейса получитьполноеимяпредопределенногозначения " + "получитьпредставлениянавигационныхссылок получитьпроверкусложностипаролейпользователей получитьразделительпути " + "получитьразделительпутиклиента получитьразделительпутисервера получитьсеансыинформационнойбазы " + "получитьскоростьклиентскогосоединения получитьсоединенияинформационнойбазы получитьсообщенияпользователю " + "получитьсоответствиеобъектаиформы получитьсоставстандартногоинтерфейсаodata получитьструктурухранениябазыданных " + "получитьтекущийсеансинформационнойбазы получитьфайл получитьфайлы получитьформу получитьфункциональнуюопцию " + "получитьфункциональнуюопциюинтерфейса получитьчасовойпоясинформационнойбазы пользователиос поместитьвовременноехранилище " + "поместитьфайл поместитьфайлы прав праводоступа предопределенноезначение представлениекодалокализации представлениепериода " + "представлениеправа представлениеприложения представлениесобытияжурналарегистрации представлениечасовогопояса предупреждение " + "прекратитьработусистемы привилегированныйрежим продолжитьвызов прочитатьjson прочитатьxml прочитатьдатуjson пустаястрока " + "рабочийкаталогданныхпользователя разблокироватьданныедляредактирования разделитьфайл разорватьсоединениесвнешнимисточникомданных " + "раскодироватьстроку рольдоступна секунда сигнал символ скопироватьжурналрегистрации смещениелетнеговремени " + "смещениестандартноговремени соединитьбуферыдвоичныхданных создатькаталог создатьфабрикуxdto сокрл сокрлп сокрп сообщить " + "состояние сохранитьзначение сохранитьнастройкипользователя сред стрдлина стрзаканчиваетсяна стрзаменить стрнайти стрначинаетсяс " + "строка строкасоединенияинформационнойбазы стрполучитьстроку стрразделить стрсоединить стрсравнить стрчисловхождений " + "стрчислострок стршаблон текущаядата текущаядатасеанса текущаяуниверсальнаядата текущаяуниверсальнаядатавмиллисекундах " + "текущийвариантинтерфейсаклиентскогоприложения текущийвариантосновногошрифтаклиентскогоприложения текущийкодлокализации " + "текущийрежимзапуска текущийязык текущийязыксистемы тип типзнч транзакцияактивна трег удалитьданныеинформационнойбазы " + "удалитьизвременногохранилища удалитьобъекты удалитьфайлы универсальноевремя установитьбезопасныйрежим " + "установитьбезопасныйрежимразделенияданных установитьблокировкусеансов установитьвнешнююкомпоненту " + "установитьвремязавершенияспящегосеанса установитьвремязасыпанияпассивногосеанса установитьвремяожиданияблокировкиданных " + "установитьзаголовокклиентскогоприложения установитьзаголовоксистемы установитьиспользованиежурналарегистрации " + "установитьиспользованиесобытияжурналарегистрации установитькраткийзаголовокприложения " + "установитьминимальнуюдлинупаролейпользователей установитьмонопольныйрежим установитьнастройкиклиенталицензирования " + "установитьобновлениепредопределенныхданныхинформационнойбазы установитьотключениебезопасногорежима " + "установитьпараметрыфункциональныхопцийинтерфейса установитьпривилегированныйрежим " + "установитьпроверкусложностипаролейпользователей установитьрасширениеработыскриптографией " + "установитьрасширениеработысфайлами установитьсоединениесвнешнимисточникомданных установитьсоответствиеобъектаиформы " + "установитьсоставстандартногоинтерфейсаodata установитьчасовойпоясинформационнойбазы установитьчасовойпояссеанса " + "формат цел час часовойпояс часовойпояссеанса число числопрописью этоадресвременногохранилища ";
const v8_global_context_property = "wsссылки библиотекакартинок библиотекамакетовоформлениякомпоновкиданных библиотекастилей бизнеспроцессы " + "внешниеисточникиданных внешниеобработки внешниеотчеты встроенныепокупки главныйинтерфейс главныйстиль " + "документы доставляемыеуведомления журналыдокументов задачи информацияобинтернетсоединении использованиерабочейдаты " + "историяработыпользователя константы критерииотбора метаданные обработки отображениерекламы отправкадоставляемыхуведомлений " + "отчеты панельзадачос параметрзапуска параметрысеанса перечисления планывидоврасчета планывидовхарактеристик " + "планыобмена планысчетов полнотекстовыйпоиск пользователиинформационнойбазы последовательности проверкавстроенныхпокупок " + "рабочаядата расширенияконфигурации регистрыбухгалтерии регистрынакопления регистрырасчета регистрысведений " + "регламентныезадания сериализаторxdto справочники средствагеопозиционирования средствакриптографии средствамультимедиа " + "средстваотображениярекламы средствапочты средствателефонии фабрикаxdto файловыепотоки фоновыезадания хранилищанастроек " + "хранилищевариантовотчетов хранилищенастроекданныхформ хранилищеобщихнастроек хранилищепользовательскихнастроекдинамическихсписков " + "хранилищепользовательскихнастроекотчетов хранилищесистемныхнастроек ";
const BUILTIN = v7_system_constants + v7_global_context_methods + v8_global_context_methods + v8_global_context_property;
const v8_system_sets_of_values = "webцвета windowsцвета windowsшрифты библиотекакартинок рамкистиля символы цветастиля шрифтыстиля ";
const v8_system_enums_interface = "автоматическоесохранениеданныхформывнастройках автонумерациявформе автораздвижениесерий " + "анимациядиаграммы вариантвыравниванияэлементовизаголовков вариантуправлениявысотойтаблицы " + "вертикальнаяпрокруткаформы вертикальноеположение вертикальноеположениеэлемента видгруппыформы " + "виддекорацииформы виддополненияэлементаформы видизмененияданных видкнопкиформы видпереключателя " + "видподписейкдиаграмме видполяформы видфлажка влияниеразмеранапузырекдиаграммы горизонтальноеположение " + "горизонтальноеположениеэлемента группировкаколонок группировкаподчиненныхэлементовформы " + "группыиэлементы действиеперетаскивания дополнительныйрежимотображения допустимыедействияперетаскивания " + "интервалмеждуэлементамиформы использованиевывода использованиеполосыпрокрутки " + "используемоезначениеточкибиржевойдиаграммы историявыборапривводе источникзначенийоситочекдиаграммы " + "источникзначенияразмерапузырькадиаграммы категориягруппыкоманд максимумсерий начальноеотображениедерева " + "начальноеотображениесписка обновлениетекстаредактирования ориентациядендрограммы ориентациядиаграммы " + "ориентацияметокдиаграммы ориентацияметоксводнойдиаграммы ориентацияэлементаформы отображениевдиаграмме " + "отображениевлегендедиаграммы отображениегруппыкнопок отображениезаголовкашкалыдиаграммы " + "отображениезначенийсводнойдиаграммы отображениезначенияизмерительнойдиаграммы " + "отображениеинтерваладиаграммыганта отображениекнопки отображениекнопкивыбора отображениеобсужденийформы " + "отображениеобычнойгруппы отображениеотрицательныхзначенийпузырьковойдиаграммы отображениепанелипоиска " + "отображениеподсказки отображениепредупрежденияприредактировании отображениеразметкиполосырегулирования " + "отображениестраницформы отображениетаблицы отображениетекстазначениядиаграммыганта " + "отображениеуправленияобычнойгруппы отображениефигурыкнопки палитрацветовдиаграммы поведениеобычнойгруппы " + "поддержкамасштабадендрограммы поддержкамасштабадиаграммыганта поддержкамасштабасводнойдиаграммы " + "поисквтаблицепривводе положениезаголовкаэлементаформы положениекартинкикнопкиформы " + "положениекартинкиэлементаграфическойсхемы положениекоманднойпанелиформы положениекоманднойпанелиэлементаформы " + "положениеопорнойточкиотрисовки положениеподписейкдиаграмме положениеподписейшкалызначенийизмерительнойдиаграммы " + "положениесостоянияпросмотра положениестрокипоиска положениетекстасоединительнойлинии положениеуправленияпоиском " + "положениешкалывремени порядокотображенияточекгоризонтальнойгистограммы порядоксерийвлегендедиаграммы " + "размеркартинки расположениезаголовкашкалыдиаграммы растягиваниеповертикалидиаграммыганта " + "режимавтоотображениясостояния режимвводастроктаблицы режимвыборанезаполненного режимвыделениядаты " + "режимвыделениястрокитаблицы режимвыделениятаблицы режимизмененияразмера режимизменениясвязанногозначения " + "режимиспользованиядиалогапечати режимиспользованияпараметракоманды режиммасштабированияпросмотра " + "режимосновногоокнаклиентскогоприложения режимоткрытияокнаформы режимотображениявыделения " + "режимотображениягеографическойсхемы режимотображениязначенийсерии режимотрисовкисеткиграфическойсхемы " + "режимполупрозрачностидиаграммы режимпробеловдиаграммы режимразмещениянастранице режимредактированияколонки " + "режимсглаживаниядиаграммы режимсглаживанияиндикатора режимсписказадач сквозноевыравнивание " + "сохранениеданныхформывнастройках способзаполнениятекстазаголовкашкалыдиаграммы " + "способопределенияограничивающегозначениядиаграммы стандартнаягруппакоманд стандартноеоформление " + "статусоповещенияпользователя стильстрелки типаппроксимациилиниитрендадиаграммы типдиаграммы " + "типединицышкалывремени типимпортасерийслоягеографическойсхемы типлиниигеографическойсхемы типлиниидиаграммы " + "типмаркерагеографическойсхемы типмаркерадиаграммы типобластиоформления " + "типорганизацииисточникаданныхгеографическойсхемы типотображениясериислоягеографическойсхемы " + "типотображенияточечногообъектагеографическойсхемы типотображенияшкалыэлементалегендыгеографическойсхемы " + "типпоискаобъектовгеографическойсхемы типпроекциигеографическойсхемы типразмещенияизмерений " + "типразмещенияреквизитовизмерений типрамкиэлементауправления типсводнойдиаграммы " + "типсвязидиаграммыганта типсоединениязначенийпосериямдиаграммы типсоединенияточекдиаграммы " + "типсоединительнойлинии типстороныэлементаграфическойсхемы типформыотчета типшкалырадарнойдиаграммы " + "факторлиниитрендадиаграммы фигуракнопки фигурыграфическойсхемы фиксациявтаблице форматдняшкалывремени " + "форматкартинки ширинаподчиненныхэлементовформы ";
const v8_system_enums_objects_properties = "виддвижениябухгалтерии виддвижениянакопления видпериодарегистрарасчета видсчета видточкимаршрутабизнеспроцесса " + "использованиеагрегатарегистранакопления использованиегруппиэлементов использованиережимапроведения " + "использованиесреза периодичностьагрегатарегистранакопления режимавтовремя режимзаписидокумента режимпроведениядокумента ";
const v8_system_enums_exchange_plans = "авторегистрацияизменений допустимыйномерсообщения отправкаэлементаданных получениеэлементаданных ";
const v8_system_enums_tabular_document = "использованиерасшифровкитабличногодокумента ориентациястраницы положениеитоговколоноксводнойтаблицы " + "положениеитоговстроксводнойтаблицы положениетекстаотносительнокартинки расположениезаголовкагруппировкитабличногодокумента " + "способчтениязначенийтабличногодокумента типдвустороннейпечати типзаполненияобластитабличногодокумента " + "типкурсоровтабличногодокумента типлиниирисункатабличногодокумента типлинииячейкитабличногодокумента " + "типнаправленияпереходатабличногодокумента типотображениявыделениятабличногодокумента типотображениялинийсводнойтаблицы " + "типразмещениятекстатабличногодокумента типрисункатабличногодокумента типсмещениятабличногодокумента " + "типузоратабличногодокумента типфайлатабличногодокумента точностьпечати чередованиерасположениястраниц ";
const v8_system_enums_sheduler = "отображениевремениэлементовпланировщика ";
const v8_system_enums_formatted_document = "типфайлаформатированногодокумента ";
const v8_system_enums_query = "обходрезультатазапроса типзаписизапроса ";
const v8_system_enums_report_builder = "видзаполнениярасшифровкипостроителяотчета типдобавленияпредставлений типизмеренияпостроителяотчета типразмещенияитогов ";
const v8_system_enums_files = "доступкфайлу режимдиалогавыборафайла режимоткрытияфайла ";
const v8_system_enums_query_builder = "типизмеренияпостроителязапроса ";
const v8_system_enums_data_analysis = "видданныханализа методкластеризации типединицыинтервалавременианализаданных типзаполнениятаблицырезультатаанализаданных " + "типиспользованиячисловыхзначенийанализаданных типисточникаданныхпоискаассоциаций типколонкианализаданныхдереворешений " + "типколонкианализаданныхкластеризация типколонкианализаданныхобщаястатистика типколонкианализаданныхпоискассоциаций " + "типколонкианализаданныхпоискпоследовательностей типколонкимоделипрогноза типмерырасстоянияанализаданных " + "типотсеченияправилассоциации типполяанализаданных типстандартизациианализаданных типупорядочиванияправилассоциациианализаданных " + "типупорядочиванияшаблоновпоследовательностейанализаданных типупрощениядереварешений ";
const v8_system_enums_xml_json_xs_dom_xdto_ws = "wsнаправлениепараметра вариантxpathxs вариантзаписидатыjson вариантпростоготипаxs видгруппымоделиxs видфасетаxdto " + "действиепостроителяdom завершенностьпростоготипаxs завершенностьсоставноготипаxs завершенностьсхемыxs запрещенныеподстановкиxs " + "исключениягруппподстановкиxs категорияиспользованияатрибутаxs категорияограниченияидентичностиxs категорияограниченияпространствименxs " + "методнаследованияxs модельсодержимогоxs назначениетипаxml недопустимыеподстановкиxs обработкапробельныхсимволовxs обработкасодержимогоxs " + "ограничениезначенияxs параметрыотбораузловdom переносстрокjson позициявдокументеdom пробельныесимволыxml типатрибутаxml типзначенияjson " + "типканоническогоxml типкомпонентыxs типпроверкиxml типрезультатаdomxpath типузлаdom типузлаxml формаxml формапредставленияxs " + "форматдатыjson экранированиесимволовjson ";
const v8_system_enums_data_composition_system = "видсравнениякомпоновкиданных действиеобработкирасшифровкикомпоновкиданных направлениесортировкикомпоновкиданных " + "расположениевложенныхэлементоврезультатакомпоновкиданных расположениеитоговкомпоновкиданных расположениегруппировкикомпоновкиданных " + "расположениеполейгруппировкикомпоновкиданных расположениеполякомпоновкиданных расположениереквизитовкомпоновкиданных " + "расположениересурсовкомпоновкиданных типбухгалтерскогоостаткакомпоновкиданных типвыводатекстакомпоновкиданных " + "типгруппировкикомпоновкиданных типгруппыэлементовотборакомпоновкиданных типдополненияпериодакомпоновкиданных " + "типзаголовкаполейкомпоновкиданных типмакетагруппировкикомпоновкиданных типмакетаобластикомпоновкиданных типостаткакомпоновкиданных " + "типпериодакомпоновкиданных типразмещениятекстакомпоновкиданных типсвязинаборовданныхкомпоновкиданных типэлементарезультатакомпоновкиданных " + "расположениелегендыдиаграммыкомпоновкиданных типпримененияотборакомпоновкиданных режимотображенияэлементанастройкикомпоновкиданных " + "режимотображениянастроеккомпоновкиданных состояниеэлементанастройкикомпоновкиданных способвосстановлениянастроеккомпоновкиданных " + "режимкомпоновкирезультата использованиепараметракомпоновкиданных автопозицияресурсовкомпоновкиданных " + "вариантиспользованиягруппировкикомпоновкиданных расположениересурсоввдиаграммекомпоновкиданных фиксациякомпоновкиданных " + "использованиеусловногооформлениякомпоновкиданных ";
const v8_system_enums_email = "важностьинтернетпочтовогосообщения обработкатекстаинтернетпочтовогосообщения способкодированияинтернетпочтовоговложения " + "способкодированиянеasciiсимволовинтернетпочтовогосообщения типтекстапочтовогосообщения протоколинтернетпочты " + "статусразборапочтовогосообщения ";
const v8_system_enums_logbook = "режимтранзакциизаписижурналарегистрации статустранзакциизаписижурналарегистрации уровеньжурналарегистрации ";
const v8_system_enums_cryptography = "расположениехранилищасертификатовкриптографии режимвключениясертификатовкриптографии режимпроверкисертификатакриптографии " + "типхранилищасертификатовкриптографии ";
const v8_system_enums_zip = "кодировкаименфайловвzipфайле методсжатияzip методшифрованияzip режимвосстановленияпутейфайловzip режимобработкиподкаталоговzip " + "режимсохраненияпутейzip уровеньсжатияzip ";
const v8_system_enums_other = "звуковоеоповещение направлениепереходакстроке позициявпотоке порядокбайтов режимблокировкиданных режимуправленияблокировкойданных " + "сервисвстроенныхпокупок состояниефоновогозадания типподписчикадоставляемыхуведомлений уровеньиспользованиязащищенногосоединенияftp ";
const v8_system_enums_request_schema = "направлениепорядкасхемызапроса типдополненияпериодамисхемызапроса типконтрольнойточкисхемызапроса типобъединениясхемызапроса " + "типпараметрадоступнойтаблицысхемызапроса типсоединениясхемызапроса ";
const v8_system_enums_properties_of_metadata_objects = "httpметод автоиспользованиеобщегореквизита автопрефиксномеразадачи вариантвстроенногоязыка видиерархии видрегистранакопления " + "видтаблицывнешнегоисточникаданных записьдвиженийприпроведении заполнениепоследовательностей индексирование " + "использованиебазыпланавидоврасчета использованиебыстроговыбора использованиеобщегореквизита использованиеподчинения " + "использованиеполнотекстовогопоиска использованиеразделяемыхданныхобщегореквизита использованиереквизита " + "назначениеиспользованияприложения назначениерасширенияконфигурации направлениепередачи обновлениепредопределенныхданных " + "оперативноепроведение основноепредставлениевидарасчета основноепредставлениевидахарактеристики основноепредставлениезадачи " + "основноепредставлениепланаобмена основноепредставлениесправочника основноепредставлениесчета перемещениеграницыприпроведении " + "периодичностьномерабизнеспроцесса периодичностьномерадокумента периодичностьрегистрарасчета периодичностьрегистрасведений " + "повторноеиспользованиевозвращаемыхзначений полнотекстовыйпоискпривводепостроке принадлежностьобъекта проведение " + "разделениеаутентификацииобщегореквизита разделениеданныхобщегореквизита разделениерасширенийконфигурацииобщегореквизита " + "режимавтонумерацииобъектов режимзаписирегистра режимиспользованиямодальности " + "режимиспользованиясинхронныхвызововрасширенийплатформыивнешнихкомпонент режимповторногоиспользованиясеансов " + "режимполученияданныхвыборапривводепостроке режимсовместимости режимсовместимостиинтерфейса " + "режимуправленияблокировкойданныхпоумолчанию сериикодовпланавидовхарактеристик сериикодовпланасчетов " + "сериикодовсправочника созданиепривводе способвыбора способпоискастрокипривводепостроке способредактирования " + "типданныхтаблицывнешнегоисточникаданных типкодапланавидоврасчета типкодасправочника типмакета типномерабизнеспроцесса " + "типномерадокумента типномеразадачи типформы удалениедвижений ";
const v8_system_enums_differents = "важностьпроблемыприменениярасширенияконфигурации вариантинтерфейсаклиентскогоприложения вариантмасштабаформклиентскогоприложения " + "вариантосновногошрифтаклиентскогоприложения вариантстандартногопериода вариантстандартнойдатыначала видграницы видкартинки " + "видотображенияполнотекстовогопоиска видрамки видсравнения видцвета видчисловогозначения видшрифта допустимаядлина допустимыйзнак " + "использованиеbyteordermark использованиеметаданныхполнотекстовогопоиска источникрасширенийконфигурации клавиша кодвозвратадиалога " + "кодировкаxbase кодировкатекста направлениепоиска направлениесортировки обновлениепредопределенныхданных обновлениеприизмененииданных " + "отображениепанелиразделов проверказаполнения режимдиалогавопрос режимзапускаклиентскогоприложения режимокругления режимоткрытияформприложения " + "режимполнотекстовогопоиска скоростьклиентскогосоединения состояниевнешнегоисточникаданных состояниеобновленияконфигурациибазыданных " + "способвыборасертификатаwindows способкодированиястроки статуссообщения типвнешнейкомпоненты типплатформы типповеденияклавишиenter " + "типэлементаинформацииовыполненииобновленияконфигурациибазыданных уровеньизоляциитранзакций хешфункция частидаты";
const CLASS = v8_system_sets_of_values + v8_system_enums_interface + v8_system_enums_objects_properties + v8_system_enums_exchange_plans + v8_system_enums_tabular_document + v8_system_enums_sheduler + v8_system_enums_formatted_document + v8_system_enums_query + v8_system_enums_report_builder + v8_system_enums_files + v8_system_enums_query_builder + v8_system_enums_data_analysis + v8_system_enums_xml_json_xs_dom_xdto_ws + v8_system_enums_data_composition_system + v8_system_enums_email + v8_system_enums_logbook + v8_system_enums_cryptography + v8_system_enums_zip + v8_system_enums_other + v8_system_enums_request_schema + v8_system_enums_properties_of_metadata_objects + v8_system_enums_differents;
const v8_shared_object = "comобъект ftpсоединение httpзапрос httpсервисответ httpсоединение wsопределения wsпрокси xbase анализданных аннотацияxs " + "блокировкаданных буфердвоичныхданных включениеxs выражениекомпоновкиданных генераторслучайныхчисел географическаясхема " + "географическиекоординаты графическаясхема группамоделиxs данныерасшифровкикомпоновкиданных двоичныеданные дендрограмма " + "диаграмма диаграммаганта диалогвыборафайла диалогвыборацвета диалогвыборашрифта диалограсписаниярегламентногозадания " + "диалогредактированиястандартногопериода диапазон документdom документhtml документацияxs доставляемоеуведомление " + "записьdom записьfastinfoset записьhtml записьjson записьxml записьzipфайла записьданных записьтекста записьузловdom " + "запрос защищенноесоединениеopenssl значенияполейрасшифровкикомпоновкиданных извлечениетекста импортxs интернетпочта " + "интернетпочтовоесообщение интернетпочтовыйпрофиль интернетпрокси интернетсоединение информациядляприложенияxs " + "использованиеатрибутаxs использованиесобытияжурналарегистрации источникдоступныхнастроеккомпоновкиданных " + "итераторузловdom картинка квалификаторыдаты квалификаторыдвоичныхданных квалификаторыстроки квалификаторычисла " + "компоновщикмакетакомпоновкиданных компоновщикнастроеккомпоновкиданных конструктормакетаоформлениякомпоновкиданных " + "конструкторнастроеккомпоновкиданных конструкторформатнойстроки линия макеткомпоновкиданных макетобластикомпоновкиданных " + "макетоформлениякомпоновкиданных маскаxs менеджеркриптографии наборсхемxml настройкикомпоновкиданных настройкисериализацииjson " + "обработкакартинок обработкарасшифровкикомпоновкиданных обходдереваdom объявлениеатрибутаxs объявлениенотацииxs " + "объявлениеэлементаxs описаниеиспользованиясобытиядоступжурналарегистрации " + "описаниеиспользованиясобытияотказвдоступежурналарегистрации описаниеобработкирасшифровкикомпоновкиданных " + "описаниепередаваемогофайла описаниетипов определениегруппыатрибутовxs определениегруппымоделиxs " + "определениеограниченияидентичностиxs определениепростоготипаxs определениесоставноготипаxs определениетипадокументаdom " + "определенияxpathxs отборкомпоновкиданных пакетотображаемыхдокументов параметрвыбора параметркомпоновкиданных " + "параметрызаписиjson параметрызаписиxml параметрычтенияxml переопределениеxs планировщик полеанализаданных " + "полекомпоновкиданных построительdom построительзапроса построительотчета построительотчетаанализаданных " + "построительсхемxml поток потоквпамяти почта почтовоесообщение преобразованиеxsl преобразованиекканоническомуxml " + "процессорвыводарезультатакомпоновкиданныхвколлекциюзначений процессорвыводарезультатакомпоновкиданныхвтабличныйдокумент " + "процессоркомпоновкиданных разыменовательпространствименdom рамка расписаниерегламентногозадания расширенноеимяxml " + "результатчтенияданных своднаядиаграмма связьпараметравыбора связьпотипу связьпотипукомпоновкиданных сериализаторxdto " + "сертификатклиентаwindows сертификатклиентафайл сертификаткриптографии сертификатыудостоверяющихцентровwindows " + "сертификатыудостоверяющихцентровфайл сжатиеданных системнаяинформация сообщениепользователю сочетаниеклавиш " + "сравнениезначений стандартнаядатаначала стандартныйпериод схемаxml схемакомпоновкиданных табличныйдокумент " + "текстовыйдокумент тестируемоеприложение типданныхxml уникальныйидентификатор фабрикаxdto файл файловыйпоток " + "фасетдлиныxs фасетколичестваразрядовдробнойчастиxs фасетмаксимальноговключающегозначенияxs " + "фасетмаксимальногоисключающегозначенияxs фасетмаксимальнойдлиныxs фасетминимальноговключающегозначенияxs " + "фасетминимальногоисключающегозначенияxs фасетминимальнойдлиныxs фасетобразцаxs фасетобщегоколичестваразрядовxs " + "фасетперечисленияxs фасетпробельныхсимволовxs фильтрузловdom форматированнаястрока форматированныйдокумент " + "фрагментxs хешированиеданных хранилищезначения цвет чтениеfastinfoset чтениеhtml чтениеjson чтениеxml чтениеzipфайла " + "чтениеданных чтениетекста чтениеузловdom шрифт элементрезультатакомпоновкиданных ";
const v8_universal_collection = "comsafearray деревозначений массив соответствие списокзначений структура таблицазначений фиксированнаяструктура " + "фиксированноесоответствие фиксированныймассив ";
const TYPE = v8_shared_object + v8_universal_collection;
const LITERAL = "null истина ложь неопределено";
const NUMBERS = hljs.inherit(hljs.NUMBER_MODE);
const STRINGS = {
className: "string",
begin: '"|\\|',
end: '"|$',
contains: [{ begin: '""' }]
};
const DATE = {
begin: "'",
end: "'",
excludeBegin: true,
excludeEnd: true,
contains: [
{
className: "number",
begin: "\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}"
}
]
};
const PUNCTUATION = {
match: /[;()+\-:=,]/,
className: "punctuation",
relevance: 0
};
const COMMENTS = hljs.inherit(hljs.C_LINE_COMMENT_MODE);
const META = {
className: "meta",
begin: "#|&",
end: "$",
keywords: {
$pattern: UNDERSCORE_IDENT_RE,
keyword: KEYWORD + METAKEYWORD
},
contains: [COMMENTS]
};
const SYMBOL = {
className: "symbol",
begin: "~",
end: ";|:",
excludeEnd: true
};
const FUNCTION = {
className: "function",
variants: [
{
begin: "процедура|функция",
end: "\\)",
keywords: "процедура функция"
},
{
begin: "конецпроцедуры|конецфункции",
keywords: "конецпроцедуры конецфункции"
}
],
contains: [
{
begin: "\\(",
end: "\\)",
endsParent: true,
contains: [
{
className: "params",
begin: UNDERSCORE_IDENT_RE,
end: ",",
excludeEnd: true,
endsWithParent: true,
keywords: {
$pattern: UNDERSCORE_IDENT_RE,
keyword: "знач",
literal: LITERAL
},
contains: [
NUMBERS,
STRINGS,
DATE
]
},
COMMENTS
]
},
hljs.inherit(hljs.TITLE_MODE, { begin: UNDERSCORE_IDENT_RE })
]
};
return {
name: "1C:Enterprise",
case_insensitive: true,
keywords: {
$pattern: UNDERSCORE_IDENT_RE,
keyword: KEYWORD,
built_in: BUILTIN,
class: CLASS,
type: TYPE,
literal: LITERAL
},
contains: [
META,
FUNCTION,
COMMENTS,
SYMBOL,
NUMBERS,
STRINGS,
DATE,
PUNCTUATION
]
};
}
module.exports = _1c;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/abnf.js
var require_abnf = __commonJS((exports, module) => {
function abnf(hljs) {
const regex2 = hljs.regex;
const IDENT = /^[a-zA-Z][a-zA-Z0-9-]*/;
const KEYWORDS = [
"ALPHA",
"BIT",
"CHAR",
"CR",
"CRLF",
"CTL",
"DIGIT",
"DQUOTE",
"HEXDIG",
"HTAB",
"LF",
"LWSP",
"OCTET",
"SP",
"VCHAR",
"WSP"
];
const COMMENT = hljs.COMMENT(/;/, /$/);
const TERMINAL_BINARY = {
scope: "symbol",
match: /%b[0-1]+(-[0-1]+|(\.[0-1]+)+)?/
};
const TERMINAL_DECIMAL = {
scope: "symbol",
match: /%d[0-9]+(-[0-9]+|(\.[0-9]+)+)?/
};
const TERMINAL_HEXADECIMAL = {
scope: "symbol",
match: /%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+)?/
};
const CASE_SENSITIVITY = {
scope: "symbol",
match: /%[si](?=".*")/
};
const RULE_DECLARATION = {
scope: "attribute",
match: regex2.concat(IDENT, /(?=\s*=)/)
};
const ASSIGNMENT = {
scope: "operator",
match: /=\/?/
};
return {
name: "Augmented Backus-Naur Form",
illegal: /[!@#$^&',?+~`|:]/,
keywords: KEYWORDS,
contains: [
ASSIGNMENT,
RULE_DECLARATION,
COMMENT,
TERMINAL_BINARY,
TERMINAL_DECIMAL,
TERMINAL_HEXADECIMAL,
CASE_SENSITIVITY,
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE
]
};
}
module.exports = abnf;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/accesslog.js
var require_accesslog = __commonJS((exports, module) => {
function accesslog(hljs) {
const regex2 = hljs.regex;
const HTTP_VERBS = [
"GET",
"POST",
"HEAD",
"PUT",
"DELETE",
"CONNECT",
"OPTIONS",
"PATCH",
"TRACE"
];
return {
name: "Apache Access Log",
contains: [
{
className: "number",
begin: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?\b/,
relevance: 5
},
{
className: "number",
begin: /\b\d+\b/,
relevance: 0
},
{
className: "string",
begin: regex2.concat(/"/, regex2.either(...HTTP_VERBS)),
end: /"/,
keywords: HTTP_VERBS,
illegal: /\n/,
relevance: 5,
contains: [
{
begin: /HTTP\/[12]\.\d'/,
relevance: 5
}
]
},
{
className: "string",
begin: /\[\d[^\]\n]{8,}\]/,
illegal: /\n/,
relevance: 1
},
{
className: "string",
begin: /\[/,
end: /\]/,
illegal: /\n/,
relevance: 0
},
{
className: "string",
begin: /"Mozilla\/\d\.\d \(/,
end: /"/,
illegal: /\n/,
relevance: 3
},
{
className: "string",
begin: /"/,
end: /"/,
illegal: /\n/,
relevance: 0
}
]
};
}
module.exports = accesslog;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/actionscript.js
var require_actionscript = __commonJS((exports, module) => {
function actionscript(hljs) {
const regex2 = hljs.regex;
const IDENT_RE = /[a-zA-Z_$][a-zA-Z0-9_$]*/;
const PKG_NAME_RE = regex2.concat(IDENT_RE, regex2.concat("(\\.", IDENT_RE, ")*"));
const IDENT_FUNC_RETURN_TYPE_RE = /([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)/;
const AS3_REST_ARG_MODE = {
className: "rest_arg",
begin: /[.]{3}/,
end: IDENT_RE,
relevance: 10
};
const KEYWORDS = [
"as",
"break",
"case",
"catch",
"class",
"const",
"continue",
"default",
"delete",
"do",
"dynamic",
"each",
"else",
"extends",
"final",
"finally",
"for",
"function",
"get",
"if",
"implements",
"import",
"in",
"include",
"instanceof",
"interface",
"internal",
"is",
"namespace",
"native",
"new",
"override",
"package",
"private",
"protected",
"public",
"return",
"set",
"static",
"super",
"switch",
"this",
"throw",
"try",
"typeof",
"use",
"var",
"void",
"while",
"with"
];
const LITERALS = [
"true",
"false",
"null",
"undefined"
];
return {
name: "ActionScript",
aliases: ["as"],
keywords: {
keyword: KEYWORDS,
literal: LITERALS
},
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_NUMBER_MODE,
{
match: [
/\bpackage/,
/\s+/,
PKG_NAME_RE
],
className: {
1: "keyword",
3: "title.class"
}
},
{
match: [
/\b(?:class|interface|extends|implements)/,
/\s+/,
IDENT_RE
],
className: {
1: "keyword",
3: "title.class"
}
},
{
className: "meta",
beginKeywords: "import include",
end: /;/,
keywords: { keyword: "import include" }
},
{
beginKeywords: "function",
end: /[{;]/,
excludeEnd: true,
illegal: /\S/,
contains: [
hljs.inherit(hljs.TITLE_MODE, { className: "title.function" }),
{
className: "params",
begin: /\(/,
end: /\)/,
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
AS3_REST_ARG_MODE
]
},
{ begin: regex2.concat(/:\s*/, IDENT_FUNC_RETURN_TYPE_RE) }
]
},
hljs.METHOD_GUARD
],
illegal: /#/
};
}
module.exports = actionscript;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/ada.js
var require_ada = __commonJS((exports, module) => {
function ada(hljs) {
const INTEGER_RE = "\\d(_|\\d)*";
const EXPONENT_RE = "[eE][-+]?" + INTEGER_RE;
const DECIMAL_LITERAL_RE = INTEGER_RE + "(\\." + INTEGER_RE + ")?" + "(" + EXPONENT_RE + ")?";
const BASED_INTEGER_RE = "\\w+";
const BASED_LITERAL_RE = INTEGER_RE + "#" + BASED_INTEGER_RE + "(\\." + BASED_INTEGER_RE + ")?" + "#" + "(" + EXPONENT_RE + ")?";
const NUMBER_RE = "\\b(" + BASED_LITERAL_RE + "|" + DECIMAL_LITERAL_RE + ")";
const ID_REGEX = "[A-Za-z](_?[A-Za-z0-9.])*";
const BAD_CHARS = `[]\\{\\}%#'"`;
const COMMENTS = hljs.COMMENT("--", "$");
const VAR_DECLS = {
begin: "\\s+:\\s+",
end: "\\s*(:=|;|\\)|=>|$)",
illegal: BAD_CHARS,
contains: [
{
beginKeywords: "loop for declare others",
endsParent: true
},
{
className: "keyword",
beginKeywords: "not null constant access function procedure in out aliased exception"
},
{
className: "type",
begin: ID_REGEX,
endsParent: true,
relevance: 0
}
]
};
const KEYWORDS = [
"abort",
"else",
"new",
"return",
"abs",
"elsif",
"not",
"reverse",
"abstract",
"end",
"accept",
"entry",
"select",
"access",
"exception",
"of",
"separate",
"aliased",
"exit",
"or",
"some",
"all",
"others",
"subtype",
"and",
"for",
"out",
"synchronized",
"array",
"function",
"overriding",
"at",
"tagged",
"generic",
"package",
"task",
"begin",
"goto",
"pragma",
"terminate",
"body",
"private",
"then",
"if",
"procedure",
"type",
"case",
"in",
"protected",
"constant",
"interface",
"is",
"raise",
"use",
"declare",
"range",
"delay",
"limited",
"record",
"when",
"delta",
"loop",
"rem",
"while",
"digits",
"renames",
"with",
"do",
"mod",
"requeue",
"xor"
];
return {
name: "Ada",
case_insensitive: true,
keywords: {
keyword: KEYWORDS,
literal: [
"True",
"False"
]
},
contains: [
COMMENTS,
{
className: "string",
begin: /"/,
end: /"/,
contains: [
{
begin: /""/,
relevance: 0
}
]
},
{
className: "string",
begin: /'.'/
},
{
className: "number",
begin: NUMBER_RE,
relevance: 0
},
{
className: "symbol",
begin: "'" + ID_REGEX
},
{
className: "title",
begin: "(\\bwith\\s+)?(\\bprivate\\s+)?\\bpackage\\s+(\\bbody\\s+)?",
end: "(is|$)",
keywords: "package body",
excludeBegin: true,
excludeEnd: true,
illegal: BAD_CHARS
},
{
begin: "(\\b(with|overriding)\\s+)?\\b(function|procedure)\\s+",
end: "(\\bis|\\bwith|\\brenames|\\)\\s*;)",
keywords: "overriding function procedure with is renames return",
returnBegin: true,
contains: [
COMMENTS,
{
className: "title",
begin: "(\\bwith\\s+)?\\b(function|procedure)\\s+",
end: "(\\(|\\s+|$)",
excludeBegin: true,
excludeEnd: true,
illegal: BAD_CHARS
},
VAR_DECLS,
{
className: "type",
begin: "\\breturn\\s+",
end: "(\\s+|;|$)",
keywords: "return",
excludeBegin: true,
excludeEnd: true,
endsParent: true,
illegal: BAD_CHARS
}
]
},
{
className: "type",
begin: "\\b(sub)?type\\s+",
end: "\\s+",
keywords: "type",
excludeBegin: true,
illegal: BAD_CHARS
},
VAR_DECLS
]
};
}
module.exports = ada;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/angelscript.js
var require_angelscript = __commonJS((exports, module) => {
function angelscript(hljs) {
const builtInTypeMode = {
className: "built_in",
begin: "\\b(void|bool|int8|int16|int32|int64|int|uint8|uint16|uint32|uint64|uint|string|ref|array|double|float|auto|dictionary)"
};
const objectHandleMode = {
className: "symbol",
begin: "[a-zA-Z0-9_]+@"
};
const genericMode = {
className: "keyword",
begin: "<",
end: ">",
contains: [
builtInTypeMode,
objectHandleMode
]
};
builtInTypeMode.contains = [genericMode];
objectHandleMode.contains = [genericMode];
const KEYWORDS = [
"for",
"in|0",
"break",
"continue",
"while",
"do|0",
"return",
"if",
"else",
"case",
"switch",
"namespace",
"is",
"cast",
"or",
"and",
"xor",
"not",
"get|0",
"in",
"inout|10",
"out",
"override",
"set|0",
"private",
"public",
"const",
"default|0",
"final",
"shared",
"external",
"mixin|10",
"enum",
"typedef",
"funcdef",
"this",
"super",
"import",
"from",
"interface",
"abstract|0",
"try",
"catch",
"protected",
"explicit",
"property"
];
return {
name: "AngelScript",
aliases: ["asc"],
keywords: KEYWORDS,
illegal: "(^using\\s+[A-Za-z0-9_\\.]+;$|\\bfunction\\s*[^\\(])",
contains: [
{
className: "string",
begin: "'",
end: "'",
illegal: "\\n",
contains: [hljs.BACKSLASH_ESCAPE],
relevance: 0
},
{
className: "string",
begin: '"""',
end: '"""'
},
{
className: "string",
begin: '"',
end: '"',
illegal: "\\n",
contains: [hljs.BACKSLASH_ESCAPE],
relevance: 0
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
{
className: "string",
begin: "^\\s*\\[",
end: "\\]"
},
{
beginKeywords: "interface namespace",
end: /\{/,
illegal: "[;.\\-]",
contains: [
{
className: "symbol",
begin: "[a-zA-Z0-9_]+"
}
]
},
{
beginKeywords: "class",
end: /\{/,
illegal: "[;.\\-]",
contains: [
{
className: "symbol",
begin: "[a-zA-Z0-9_]+",
contains: [
{
begin: "[:,]\\s*",
contains: [
{
className: "symbol",
begin: "[a-zA-Z0-9_]+"
}
]
}
]
}
]
},
builtInTypeMode,
objectHandleMode,
{
className: "literal",
begin: "\\b(null|true|false)"
},
{
className: "number",
relevance: 0,
begin: "(-?)(\\b0[xXbBoOdD][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?f?|\\.\\d+f?)([eE][-+]?\\d+f?)?)"
}
]
};
}
module.exports = angelscript;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/apache.js
var require_apache = __commonJS((exports, module) => {
function apache(hljs) {
const NUMBER_REF = {
className: "number",
begin: /[$%]\d+/
};
const NUMBER = {
className: "number",
begin: /\b\d+/
};
const IP_ADDRESS = {
className: "number",
begin: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?/
};
const PORT_NUMBER = {
className: "number",
begin: /:\d{1,5}/
};
return {
name: "Apache config",
aliases: ["apacheconf"],
case_insensitive: true,
contains: [
hljs.HASH_COMMENT_MODE,
{
className: "section",
begin: /<\/?/,
end: />/,
contains: [
IP_ADDRESS,
PORT_NUMBER,
hljs.inherit(hljs.QUOTE_STRING_MODE, { relevance: 0 })
]
},
{
className: "attribute",
begin: /\w+/,
relevance: 0,
keywords: { _: [
"order",
"deny",
"allow",
"setenv",
"rewriterule",
"rewriteengine",
"rewritecond",
"documentroot",
"sethandler",
"errordocument",
"loadmodule",
"options",
"header",
"listen",
"serverroot",
"servername"
] },
starts: {
end: /$/,
relevance: 0,
keywords: { literal: "on off all deny allow" },
contains: [
{
scope: "punctuation",
match: /\\\n/
},
{
className: "meta",
begin: /\s\[/,
end: /\]$/
},
{
className: "variable",
begin: /[\$%]\{/,
end: /\}/,
contains: [
"self",
NUMBER_REF
]
},
IP_ADDRESS,
NUMBER,
hljs.QUOTE_STRING_MODE
]
}
}
],
illegal: /\S/
};
}
module.exports = apache;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/applescript.js
var require_applescript = __commonJS((exports, module) => {
function applescript(hljs) {
const regex2 = hljs.regex;
const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, { illegal: null });
const PARAMS = {
className: "params",
begin: /\(/,
end: /\)/,
contains: [
"self",
hljs.C_NUMBER_MODE,
STRING
]
};
const COMMENT_MODE_1 = hljs.COMMENT(/--/, /$/);
const COMMENT_MODE_2 = hljs.COMMENT(/\(\*/, /\*\)/, { contains: [
"self",
COMMENT_MODE_1
] });
const COMMENTS = [
COMMENT_MODE_1,
COMMENT_MODE_2,
hljs.HASH_COMMENT_MODE
];
const KEYWORD_PATTERNS = [
/apart from/,
/aside from/,
/instead of/,
/out of/,
/greater than/,
/isn't|(doesn't|does not) (equal|come before|come after|contain)/,
/(greater|less) than( or equal)?/,
/(starts?|ends|begins?) with/,
/contained by/,
/comes (before|after)/,
/a (ref|reference)/,
/POSIX (file|path)/,
/(date|time) string/,
/quoted form/
];
const BUILT_IN_PATTERNS = [
/clipboard info/,
/the clipboard/,
/info for/,
/list (disks|folder)/,
/mount volume/,
/path to/,
/(close|open for) access/,
/(get|set) eof/,
/current date/,
/do shell script/,
/get volume settings/,
/random number/,
/set volume/,
/system attribute/,
/system info/,
/time to GMT/,
/(load|run|store) script/,
/scripting components/,
/ASCII (character|number)/,
/localized string/,
/choose (application|color|file|file name|folder|from list|remote application|URL)/,
/display (alert|dialog)/
];
return {
name: "AppleScript",
aliases: ["osascript"],
keywords: {
keyword: "about above after against and around as at back before beginning " + "behind below beneath beside between but by considering " + "contain contains continue copy div does eighth else end equal " + "equals error every exit fifth first for fourth from front " + "get given global if ignoring in into is it its last local me " + "middle mod my ninth not of on onto or over prop property put ref " + "reference repeat returning script second set seventh since " + "sixth some tell tenth that the|0 then third through thru " + "timeout times to transaction try until where while whose with " + "without",
literal: "AppleScript false linefeed return pi quote result space tab true",
built_in: "alias application boolean class constant date file integer list " + "number real record string text " + "activate beep count delay launch log offset read round " + "run say summarize write " + "character characters contents day frontmost id item length " + "month name|0 paragraph paragraphs rest reverse running time version " + "weekday word words year"
},
contains: [
STRING,
hljs.C_NUMBER_MODE,
{
className: "built_in",
begin: regex2.concat(/\b/, regex2.either(...BUILT_IN_PATTERNS), /\b/)
},
{
className: "built_in",
begin: /^\s*return\b/
},
{
className: "literal",
begin: /\b(text item delimiters|current application|missing value)\b/
},
{
className: "keyword",
begin: regex2.concat(/\b/, regex2.either(...KEYWORD_PATTERNS), /\b/)
},
{
beginKeywords: "on",
illegal: /[${=;\n]/,
contains: [
hljs.UNDERSCORE_TITLE_MODE,
PARAMS
]
},
...COMMENTS
],
illegal: /\/\/|->|=>|\[\[/
};
}
module.exports = applescript;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/arcade.js
var require_arcade = __commonJS((exports, module) => {
function arcade(hljs) {
const regex2 = hljs.regex;
const IDENT_RE = "[A-Za-z_][0-9A-Za-z_]*";
const KEYWORDS = {
keyword: [
"break",
"case",
"catch",
"continue",
"debugger",
"do",
"else",
"export",
"for",
"function",
"if",
"import",
"in",
"new",
"of",
"return",
"switch",
"try",
"var",
"void",
"while"
],
literal: [
"BackSlash",
"DoubleQuote",
"ForwardSlash",
"Infinity",
"NaN",
"NewLine",
"PI",
"SingleQuote",
"Tab",
"TextFormatting",
"false",
"null",
"true",
"undefined"
],
built_in: [
"Abs",
"Acos",
"All",
"Angle",
"Any",
"Area",
"AreaGeodetic",
"Array",
"Asin",
"Atan",
"Atan2",
"Attachments",
"Average",
"Back",
"Bearing",
"Boolean",
"Buffer",
"BufferGeodetic",
"Ceil",
"Centroid",
"ChangeTimeZone",
"Clip",
"Concatenate",
"Console",
"Constrain",
"Contains",
"ConvertDirection",
"ConvexHull",
"Cos",
"Count",
"Crosses",
"Cut",
"Date|0",
"DateAdd",
"DateDiff",
"DateOnly",
"Day",
"Decode",
"DefaultValue",
"Densify",
"DensifyGeodetic",
"Dictionary",
"Difference",
"Disjoint",
"Distance",
"DistanceGeodetic",
"DistanceToCoordinate",
"Distinct",
"Domain",
"DomainCode",
"DomainName",
"EnvelopeIntersects",
"Equals",
"Erase",
"Exp",
"Expects",
"Extent",
"Feature",
"FeatureInFilter",
"FeatureSet",
"FeatureSetByAssociation",
"FeatureSetById",
"FeatureSetByName",
"FeatureSetByPortalItem",
"FeatureSetByRelationshipClass",
"FeatureSetByRelationshipName",
"Filter",
"FilterBySubtypeCode",
"Find",
"First|0",
"Floor",
"FromCharCode",
"FromCodePoint",
"FromJSON",
"Front",
"GdbVersion",
"Generalize",
"Geometry",
"GetEnvironment",
"GetFeatureSet",
"GetFeatureSetInfo",
"GetUser",
"GroupBy",
"Guid",
"HasKey",
"HasValue",
"Hash",
"Hour",
"IIf",
"ISOMonth",
"ISOWeek",
"ISOWeekday",
"ISOYear",
"Includes",
"IndexOf",
"Insert",
"Intersection",
"Intersects",
"IsEmpty",
"IsNan",
"IsSelfIntersecting",
"IsSimple",
"KnowledgeGraphByPortalItem",
"Left|0",
"Length",
"Length3D",
"LengthGeodetic",
"Log",
"Lower",
"Map",
"Max",
"Mean",
"MeasureToCoordinate",
"Mid",
"Millisecond",
"Min",
"Minute",
"Month",
"MultiPartToSinglePart",
"Multipoint",
"NearestCoordinate",
"NearestVertex",
"NextSequenceValue",
"None",
"Now",
"Number",
"Offset",
"OrderBy",
"Overlaps",
"Point",
"PointToCoordinate",
"Polygon",
"Polyline",
"Pop",
"Portal",
"Pow",
"Proper",
"Push",
"QueryGraph",
"Random",
"Reduce",
"Relate",
"Replace",
"Resize",
"Reverse",
"Right|0",
"RingIsClockwise",
"Rotate",
"Round",
"Schema",
"Second",
"SetGeometry",
"Simplify",
"Sin",
"Slice",
"Sort",
"Splice",
"Split",
"Sqrt",
"StandardizeFilename",
"StandardizeGuid",
"Stdev",
"SubtypeCode",
"SubtypeName",
"Subtypes",
"Sum",
"SymmetricDifference",
"Tan",
"Text",
"Time",
"TimeZone",
"TimeZoneOffset",
"Timestamp",
"ToCharCode",
"ToCodePoint",
"ToHex",
"ToLocal",
"ToUTC",
"Today",
"Top|0",
"Touches",
"TrackAccelerationAt",
"TrackAccelerationWindow",
"TrackCurrentAcceleration",
"TrackCurrentDistance",
"TrackCurrentSpeed",
"TrackCurrentTime",
"TrackDistanceAt",
"TrackDistanceWindow",
"TrackDuration",
"TrackFieldWindow",
"TrackGeometryWindow",
"TrackIndex",
"TrackSpeedAt",
"TrackSpeedWindow",
"TrackStartTime",
"TrackWindow",
"Trim",
"TypeOf",
"Union",
"Upper",
"UrlEncode",
"Variance",
"Week",
"Weekday",
"When|0",
"Within",
"Year|0"
]
};
const PROFILE_VARS = [
"aggregatedFeatures",
"analytic",
"config",
"datapoint",
"datastore",
"editcontext",
"feature",
"featureSet",
"feedfeature",
"fencefeature",
"fencenotificationtype",
"graph",
"join",
"layer",
"locationupdate",
"map",
"measure",
"measure",
"originalFeature",
"record",
"reference",
"rowindex",
"sourcedatastore",
"sourcefeature",
"sourcelayer",
"target",
"targetdatastore",
"targetfeature",
"targetlayer",
"userInput",
"value",
"variables",
"view"
];
const SYMBOL = {
className: "symbol",
begin: "\\$" + regex2.either(...PROFILE_VARS)
};
const NUMBER = {
className: "number",
variants: [
{ begin: "\\b(0[bB][01]+)" },
{ begin: "\\b(0[oO][0-7]+)" },
{ begin: hljs.C_NUMBER_RE }
],
relevance: 0
};
const SUBST = {
className: "subst",
begin: "\\$\\{",
end: "\\}",
keywords: KEYWORDS,
contains: []
};
const TEMPLATE_STRING = {
className: "string",
begin: "`",
end: "`",
contains: [
hljs.BACKSLASH_ESCAPE,
SUBST
]
};
SUBST.contains = [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
TEMPLATE_STRING,
NUMBER,
hljs.REGEXP_MODE
];
const PARAMS_CONTAINS = SUBST.contains.concat([
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_LINE_COMMENT_MODE
]);
return {
name: "ArcGIS Arcade",
case_insensitive: true,
keywords: KEYWORDS,
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
TEMPLATE_STRING,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
SYMBOL,
NUMBER,
{
begin: /[{,]\s*/,
relevance: 0,
contains: [
{
begin: IDENT_RE + "\\s*:",
returnBegin: true,
relevance: 0,
contains: [
{
className: "attr",
begin: IDENT_RE,
relevance: 0
}
]
}
]
},
{
begin: "(" + hljs.RE_STARTERS_RE + "|\\b(return)\\b)\\s*",
keywords: "return",
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.REGEXP_MODE,
{
className: "function",
begin: "(\\(.*?\\)|" + IDENT_RE + ")\\s*=>",
returnBegin: true,
end: "\\s*=>",
contains: [
{
className: "params",
variants: [
{ begin: IDENT_RE },
{ begin: /\(\s*\)/ },
{
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
keywords: KEYWORDS,
contains: PARAMS_CONTAINS
}
]
}
]
}
],
relevance: 0
},
{
beginKeywords: "function",
end: /\{/,
excludeEnd: true,
contains: [
hljs.inherit(hljs.TITLE_MODE, {
className: "title.function",
begin: IDENT_RE
}),
{
className: "params",
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
contains: PARAMS_CONTAINS
}
],
illegal: /\[|%/
},
{ begin: /\$[(.]/ }
],
illegal: /#(?!!)/
};
}
module.exports = arcade;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/arduino.js
var require_arduino = __commonJS((exports, module) => {
function cPlusPlus(hljs) {
const regex2 = hljs.regex;
const C_LINE_COMMENT_MODE = hljs.COMMENT("//", "$", { contains: [{ begin: /\\\n/ }] });
const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
const FUNCTION_TYPE_RE = "(?!struct)(" + DECLTYPE_AUTO_RE + "|" + regex2.optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + regex2.optional(TEMPLATE_ARGUMENT_RE) + ")";
const CPP_PRIMITIVE_TYPES = {
className: "type",
begin: "\\b[a-z\\d_]*_t\\b"
};
const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
const STRINGS = {
className: "string",
variants: [
{
begin: '(u8?|U|L)?"',
end: '"',
illegal: "\\n",
contains: [hljs.BACKSLASH_ESCAPE]
},
{
begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
end: "'",
illegal: "."
},
hljs.END_SAME_AS_BEGIN({
begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
end: /\)([^()\\ ]{0,16})"/
})
]
};
const NUMBERS = {
className: "number",
variants: [
{
begin: "[+-]?(?:" + "(?:" + "[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?" + "|\\.[0-9](?:'?[0-9])*" + ")(?:[Ee][+-]?[0-9](?:'?[0-9])*)?" + "|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*" + "|0[Xx](?:" + "[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?" + "|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*" + ")[Pp][+-]?[0-9](?:'?[0-9])*" + ")(?:" + "[Ff](?:16|32|64|128)?" + "|(BF|bf)16" + "|[Ll]" + "|" + ")"
},
{
begin: "[+-]?\\b(?:" + "0[Bb][01](?:'?[01])*" + "|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*" + "|0(?:'?[0-7])*" + "|[1-9](?:'?[0-9])*" + ")(?:" + "[Uu](?:LL?|ll?)" + "|[Uu][Zz]?" + "|(?:LL?|ll?)[Uu]?" + "|[Zz][Uu]" + "|" + ")"
}
],
relevance: 0
};
const PREPROCESSOR = {
className: "meta",
begin: /#\s*[a-z]+\b/,
end: /$/,
keywords: { keyword: "if else elif endif define undef warning error line " + "pragma _Pragma ifdef ifndef include" },
contains: [
{
begin: /\\\n/,
relevance: 0
},
hljs.inherit(STRINGS, { className: "string" }),
{
className: "string",
begin: /<.*?>/
},
C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
};
const TITLE_MODE = {
className: "title",
begin: regex2.optional(NAMESPACE_RE) + hljs.IDENT_RE,
relevance: 0
};
const FUNCTION_TITLE = regex2.optional(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
const RESERVED_KEYWORDS = [
"alignas",
"alignof",
"and",
"and_eq",
"asm",
"atomic_cancel",
"atomic_commit",
"atomic_noexcept",
"auto",
"bitand",
"bitor",
"break",
"case",
"catch",
"class",
"co_await",
"co_return",
"co_yield",
"compl",
"concept",
"const_cast|10",
"consteval",
"constexpr",
"constinit",
"continue",
"decltype",
"default",
"delete",
"do",
"dynamic_cast|10",
"else",
"enum",
"explicit",
"export",
"extern",
"false",
"final",
"for",
"friend",
"goto",
"if",
"import",
"inline",
"module",
"mutable",
"namespace",
"new",
"noexcept",
"not",
"not_eq",
"nullptr",
"operator",
"or",
"or_eq",
"override",
"private",
"protected",
"public",
"reflexpr",
"register",
"reinterpret_cast|10",
"requires",
"return",
"sizeof",
"static_assert",
"static_cast|10",
"struct",
"switch",
"synchronized",
"template",
"this",
"thread_local",
"throw",
"transaction_safe",
"transaction_safe_dynamic",
"true",
"try",
"typedef",
"typeid",
"typename",
"union",
"using",
"virtual",
"volatile",
"while",
"xor",
"xor_eq"
];
const RESERVED_TYPES = [
"bool",
"char",
"char16_t",
"char32_t",
"char8_t",
"double",
"float",
"int",
"long",
"short",
"void",
"wchar_t",
"unsigned",
"signed",
"const",
"static"
];
const TYPE_HINTS = [
"any",
"auto_ptr",
"barrier",
"binary_semaphore",
"bitset",
"complex",
"condition_variable",
"condition_variable_any",
"counting_semaphore",
"deque",
"false_type",
"flat_map",
"flat_set",
"future",
"imaginary",
"initializer_list",
"istringstream",
"jthread",
"latch",
"lock_guard",
"multimap",
"multiset",
"mutex",
"optional",
"ostringstream",
"packaged_task",
"pair",
"promise",
"priority_queue",
"queue",
"recursive_mutex",
"recursive_timed_mutex",
"scoped_lock",
"set",
"shared_future",
"shared_lock",
"shared_mutex",
"shared_timed_mutex",
"shared_ptr",
"stack",
"string_view",
"stringstream",
"timed_mutex",
"thread",
"true_type",
"tuple",
"unique_lock",
"unique_ptr",
"unordered_map",
"unordered_multimap",
"unordered_multiset",
"unordered_set",
"variant",
"vector",
"weak_ptr",
"wstring",
"wstring_view"
];
const FUNCTION_HINTS = [
"abort",
"abs",
"acos",
"apply",
"as_const",
"asin",
"atan",
"atan2",
"calloc",
"ceil",
"cerr",
"cin",
"clog",
"cos",
"cosh",
"cout",
"declval",
"endl",
"exchange",
"exit",
"exp",
"fabs",
"floor",
"fmod",
"forward",
"fprintf",
"fputs",
"free",
"frexp",
"fscanf",
"future",
"invoke",
"isalnum",
"isalpha",
"iscntrl",
"isdigit",
"isgraph",
"islower",
"isprint",
"ispunct",
"isspace",
"isupper",
"isxdigit",
"labs",
"launder",
"ldexp",
"log",
"log10",
"make_pair",
"make_shared",
"make_shared_for_overwrite",
"make_tuple",
"make_unique",
"malloc",
"memchr",
"memcmp",
"memcpy",
"memset",
"modf",
"move",
"pow",
"printf",
"putchar",
"puts",
"realloc",
"scanf",
"sin",
"sinh",
"snprintf",
"sprintf",
"sqrt",
"sscanf",
"std",
"stderr",
"stdin",
"stdout",
"strcat",
"strchr",
"strcmp",
"strcpy",
"strcspn",
"strlen",
"strncat",
"strncmp",
"strncpy",
"strpbrk",
"strrchr",
"strspn",
"strstr",
"swap",
"tan",
"tanh",
"terminate",
"to_underlying",
"tolower",
"toupper",
"vfprintf",
"visit",
"vprintf",
"vsprintf"
];
const LITERALS = [
"NULL",
"false",
"nullopt",
"nullptr",
"true"
];
const BUILT_IN = ["_Pragma"];
const CPP_KEYWORDS = {
type: RESERVED_TYPES,
keyword: RESERVED_KEYWORDS,
literal: LITERALS,
built_in: BUILT_IN,
_type_hints: TYPE_HINTS
};
const FUNCTION_DISPATCH = {
className: "function.dispatch",
relevance: 0,
keywords: {
_hint: FUNCTION_HINTS
},
begin: regex2.concat(/\b/, /(?!decltype)/, /(?!if)/, /(?!for)/, /(?!switch)/, /(?!while)/, hljs.IDENT_RE, regex2.lookahead(/(<[^<>]+>|)\s*\(/))
};
const EXPRESSION_CONTAINS = [
FUNCTION_DISPATCH,
PREPROCESSOR,
CPP_PRIMITIVE_TYPES,
C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
NUMBERS,
STRINGS
];
const EXPRESSION_CONTEXT = {
variants: [
{
begin: /=/,
end: /;/
},
{
begin: /\(/,
end: /\)/
},
{
beginKeywords: "new throw return else",
end: /;/
}
],
keywords: CPP_KEYWORDS,
contains: EXPRESSION_CONTAINS.concat([
{
begin: /\(/,
end: /\)/,
keywords: CPP_KEYWORDS,
contains: EXPRESSION_CONTAINS.concat(["self"]),
relevance: 0
}
]),
relevance: 0
};
const FUNCTION_DECLARATION = {
className: "function",
begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
returnBegin: true,
end: /[{;=]/,
excludeEnd: true,
keywords: CPP_KEYWORDS,
illegal: /[^\w\s\*&:<>.]/,
contains: [
{
begin: DECLTYPE_AUTO_RE,
keywords: CPP_KEYWORDS,
relevance: 0
},
{
begin: FUNCTION_TITLE,
returnBegin: true,
contains: [TITLE_MODE],
relevance: 0
},
{
begin: /::/,
relevance: 0
},
{
begin: /:/,
endsWithParent: true,
contains: [
STRINGS,
NUMBERS
]
},
{
relevance: 0,
match: /,/
},
{
className: "params",
begin: /\(/,
end: /\)/,
keywords: CPP_KEYWORDS,
relevance: 0,
contains: [
C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
STRINGS,
NUMBERS,
CPP_PRIMITIVE_TYPES,
{
begin: /\(/,
end: /\)/,
keywords: CPP_KEYWORDS,
relevance: 0,
contains: [
"self",
C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
STRINGS,
NUMBERS,
CPP_PRIMITIVE_TYPES
]
}
]
},
CPP_PRIMITIVE_TYPES,
C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
PREPROCESSOR
]
};
return {
name: "C++",
aliases: [
"cc",
"c++",
"h++",
"hpp",
"hh",
"hxx",
"cxx"
],
keywords: CPP_KEYWORDS,
illegal: "",
classNameAliases: { "function.dispatch": "built_in" },
contains: [].concat(EXPRESSION_CONTEXT, FUNCTION_DECLARATION, FUNCTION_DISPATCH, EXPRESSION_CONTAINS, [
PREPROCESSOR,
{
begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",
end: ">",
keywords: CPP_KEYWORDS,
contains: [
"self",
CPP_PRIMITIVE_TYPES
]
},
{
begin: hljs.IDENT_RE + "::",
keywords: CPP_KEYWORDS
},
{
match: [
/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,
/\s+/,
/\w+/
],
className: {
1: "keyword",
3: "title.class"
}
}
])
};
}
function arduino(hljs) {
const ARDUINO_KW = {
type: [
"boolean",
"byte",
"word",
"String"
],
built_in: [
"KeyboardController",
"MouseController",
"SoftwareSerial",
"EthernetServer",
"EthernetClient",
"LiquidCrystal",
"RobotControl",
"GSMVoiceCall",
"EthernetUDP",
"EsploraTFT",
"HttpClient",
"RobotMotor",
"WiFiClient",
"GSMScanner",
"FileSystem",
"Scheduler",
"GSMServer",
"YunClient",
"YunServer",
"IPAddress",
"GSMClient",
"GSMModem",
"Keyboard",
"Ethernet",
"Console",
"GSMBand",
"Esplora",
"Stepper",
"Process",
"WiFiUDP",
"GSM_SMS",
"Mailbox",
"USBHost",
"Firmata",
"PImage",
"Client",
"Server",
"GSMPIN",
"FileIO",
"Bridge",
"Serial",
"EEPROM",
"Stream",
"Mouse",
"Audio",
"Servo",
"File",
"Task",
"GPRS",
"WiFi",
"Wire",
"TFT",
"GSM",
"SPI",
"SD"
],
_hints: [
"setup",
"loop",
"runShellCommandAsynchronously",
"analogWriteResolution",
"retrieveCallingNumber",
"printFirmwareVersion",
"analogReadResolution",
"sendDigitalPortPair",
"noListenOnLocalhost",
"readJoystickButton",
"setFirmwareVersion",
"readJoystickSwitch",
"scrollDisplayRight",
"getVoiceCallStatus",
"scrollDisplayLeft",
"writeMicroseconds",
"delayMicroseconds",
"beginTransmission",
"getSignalStrength",
"runAsynchronously",
"getAsynchronously",
"listenOnLocalhost",
"getCurrentCarrier",
"readAccelerometer",
"messageAvailable",
"sendDigitalPorts",
"lineFollowConfig",
"countryNameWrite",
"runShellCommand",
"readStringUntil",
"rewindDirectory",
"readTemperature",
"setClockDivider",
"readLightSensor",
"endTransmission",
"analogReference",
"detachInterrupt",
"countryNameRead",
"attachInterrupt",
"encryptionType",
"readBytesUntil",
"robotNameWrite",
"readMicrophone",
"robotNameRead",
"cityNameWrite",
"userNameWrite",
"readJoystickY",
"readJoystickX",
"mouseReleased",
"openNextFile",
"scanNetworks",
"noInterrupts",
"digitalWrite",
"beginSpeaker",
"mousePressed",
"isActionDone",
"mouseDragged",
"displayLogos",
"noAutoscroll",
"addParameter",
"remoteNumber",
"getModifiers",
"keyboardRead",
"userNameRead",
"waitContinue",
"processInput",
"parseCommand",
"printVersion",
"readNetworks",
"writeMessage",
"blinkVersion",
"cityNameRead",
"readMessage",
"setDataMode",
"parsePacket",
"isListening",
"setBitOrder",
"beginPacket",
"isDirectory",
"motorsWrite",
"drawCompass",
"digitalRead",
"clearScreen",
"serialEvent",
"rightToLeft",
"setTextSize",
"leftToRight",
"requestFrom",
"keyReleased",
"compassRead",
"analogWrite",
"interrupts",
"WiFiServer",
"disconnect",
"playMelody",
"parseFloat",
"autoscroll",
"getPINUsed",
"setPINUsed",
"setTimeout",
"sendAnalog",
"readSlider",
"analogRead",
"beginWrite",
"createChar",
"motorsStop",
"keyPressed",
"tempoWrite",
"readButton",
"subnetMask",
"debugPrint",
"macAddress",
"writeGreen",
"randomSeed",
"attachGPRS",
"readString",
"sendString",
"remotePort",
"releaseAll",
"mouseMoved",
"background",
"getXChange",
"getYChange",
"answerCall",
"getResult",
"voiceCall",
"endPacket",
"constrain",
"getSocket",
"writeJSON",
"getButton",
"available",
"connected",
"findUntil",
"readBytes",
"exitValue",
"readGreen",
"writeBlue",
"startLoop",
"IPAddress",
"isPressed",
"sendSysex",
"pauseMode",
"gatewayIP",
"setCursor",
"getOemKey",
"tuneWrite",
"noDisplay",
"loadImage",
"switchPIN",
"onRequest",
"onReceive",
"changePIN",
"playFile",
"noBuffer",
"parseInt",
"overflow",
"checkPIN",
"knobRead",
"beginTFT",
"bitClear",
"updateIR",
"bitWrite",
"position",
"writeRGB",
"highByte",
"writeRed",
"setSpeed",
"readBlue",
"noStroke",
"remoteIP",
"transfer",
"shutdown",
"hangCall",
"beginSMS",
"endWrite",
"attached",
"maintain",
"noCursor",
"checkReg",
"checkPUK",
"shiftOut",
"isValid",
"shiftIn",
"pulseIn",
"connect",
"println",
"localIP",
"pinMode",
"getIMEI",
"display",
"noBlink",
"process",
"getBand",
"running",
"beginSD",
"drawBMP",
"lowByte",
"setBand",
"release",
"bitRead",
"prepare",
"pointTo",
"readRed",
"setMode",
"noFill",
"remove",
"listen",
"stroke",
"detach",
"attach",
"noTone",
"exists",
"buffer",
"height",
"bitSet",
"circle",
"config",
"cursor",
"random",
"IRread",
"setDNS",
"endSMS",
"getKey",
"micros",
"millis",
"begin",
"print",
"write",
"ready",
"flush",
"width",
"isPIN",
"blink",
"clear",
"press",
"mkdir",
"rmdir",
"close",
"point",
"yield",
"image",
"BSSID",
"click",
"delay",
"read",
"text",
"move",
"peek",
"beep",
"rect",
"line",
"open",
"seek",
"fill",
"size",
"turn",
"stop",
"home",
"find",
"step",
"tone",
"sqrt",
"RSSI",
"SSID",
"end",
"bit",
"tan",
"cos",
"sin",
"pow",
"map",
"abs",
"max",
"min",
"get",
"run",
"put"
],
literal: [
"DIGITAL_MESSAGE",
"FIRMATA_STRING",
"ANALOG_MESSAGE",
"REPORT_DIGITAL",
"REPORT_ANALOG",
"INPUT_PULLUP",
"SET_PIN_MODE",
"INTERNAL2V56",
"SYSTEM_RESET",
"LED_BUILTIN",
"INTERNAL1V1",
"SYSEX_START",
"INTERNAL",
"EXTERNAL",
"DEFAULT",
"OUTPUT",
"INPUT",
"HIGH",
"LOW"
]
};
const ARDUINO = cPlusPlus(hljs);
const kws = ARDUINO.keywords;
kws.type = [
...kws.type,
...ARDUINO_KW.type
];
kws.literal = [
...kws.literal,
...ARDUINO_KW.literal
];
kws.built_in = [
...kws.built_in,
...ARDUINO_KW.built_in
];
kws._hints = ARDUINO_KW._hints;
ARDUINO.name = "Arduino";
ARDUINO.aliases = ["ino"];
ARDUINO.supersetOf = "cpp";
return ARDUINO;
}
module.exports = arduino;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/armasm.js
var require_armasm = __commonJS((exports, module) => {
function armasm(hljs) {
const COMMENT = { variants: [
hljs.COMMENT("^[ \\t]*(?=#)", "$", {
relevance: 0,
excludeBegin: true
}),
hljs.COMMENT("[;@]", "$", { relevance: 0 }),
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
] };
return {
name: "ARM Assembly",
case_insensitive: true,
aliases: ["arm"],
keywords: {
$pattern: "\\.?" + hljs.IDENT_RE,
meta: ".2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg " + "ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND ",
built_in: "r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 " + "w0 w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 w13 w14 w15 " + "w16 w17 w18 w19 w20 w21 w22 w23 w24 w25 w26 w27 w28 w29 w30 " + "x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 " + "x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 " + "pc lr sp ip sl sb fp " + "a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 " + "p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 " + "c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 " + "q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 " + "cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf " + "spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf " + "s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 " + "s16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 " + "d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 " + "d16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 " + "{PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @"
},
contains: [
{
className: "keyword",
begin: "\\b(" + "adc|" + "(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|" + "and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|" + "bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|" + "setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|" + "ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|" + "mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|" + "mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|" + "mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|" + "rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|" + "stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|" + "[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|" + "wfe|wfi|yield" + ")" + "(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?" + "[sptrx]?" + "(?=\\s)"
},
COMMENT,
hljs.QUOTE_STRING_MODE,
{
className: "string",
begin: "'",
end: "[^\\\\]'",
relevance: 0
},
{
className: "title",
begin: "\\|",
end: "\\|",
illegal: "\\n",
relevance: 0
},
{
className: "number",
variants: [
{
begin: "[#$=]?0x[0-9a-f]+"
},
{
begin: "[#$=]?0b[01]+"
},
{
begin: "[#$=]\\d+"
},
{
begin: "\\b\\d+"
}
],
relevance: 0
},
{
className: "symbol",
variants: [
{
begin: "^[ \\t]*[a-z_\\.\\$][a-z0-9_\\.\\$]+:"
},
{
begin: "^[a-z_\\.\\$][a-z0-9_\\.\\$]+"
},
{
begin: "[=#]\\w+"
}
],
relevance: 0
}
]
};
}
module.exports = armasm;
});
// node_modules/.pnpm/highlight.js@11.11.1/node_modules/highlight.js/lib/languages/xml.js
var require_xml = __commonJS((exports, module) => {
function xml(hljs) {
const regex2 = hljs.regex;
const TAG_NAME_RE = regex2.concat(/[\p{L}_]/u, regex2.optional(/[\p{L}0-9_.-]*:/u), /[\p{L}0-9_.-]*/u);
const XML_IDENT_RE = /[\p{L}0-9._:-]+/u;
const XML_ENTITIES = {
className: "symbol",
begin: /&[a-z]+;|[0-9]+;|[a-f0-9]+;/
};
const XML_META_KEYWORDS = {
begin: /\s/,
contains: [
{
className: "keyword",
begin: /#?[a-z_][a-z1-9_-]+/,
illegal: /\n/
}
]
};
const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, {
begin: /\(/,
end: /\)/
});
const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, { className: "string" });
const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, { className: "string" });
const TAG_INTERNALS = {
endsWithParent: true,
illegal: /,
relevance: 0,
contains: [
{
className: "attr",
begin: XML_IDENT_RE,
relevance: 0
},
{
begin: /=\s*/,
relevance: 0,
contains: [
{
className: "string",
endsParent: true,
variants: [
{
begin: /"/,
end: /"/,
contains: [XML_ENTITIES]
},
{
begin: /'/,
end: /'/,
contains: [XML_ENTITIES]
},
{ begin: /[^\s"'=<>`]+/ }
]
}
]
}
]
};
return {
name: "HTML, XML",
aliases: [
"html",
"xhtml",
"rss",
"atom",
"xjb",
"xsd",
"xsl",
"plist",
"wsf",
"svg"
],
case_insensitive: true,
unicodeRegex: true,
contains: [
{
className: "meta",
begin: //,
relevance: 10,
contains: [
XML_META_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE,
XML_META_PAR_KEYWORDS,
{
begin: /\[/,
end: /\]/,
contains: [
{
className: "meta",
begin: //,
contains: [
XML_META_KEYWORDS,
XML_META_PAR_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE
]
}
]
}
]
},
hljs.COMMENT(//, { relevance: 10 }),
{
begin: //,
relevance: 10
},
XML_ENTITIES,
{
className: "meta",
end: /\?>/,
variants: [
{
begin: /<\?xml/,
relevance: 10,
contains: [
QUOTE_META_STRING_MODE
]
},
{
begin: /<\?[a-z][a-z0-9]+/
}
]
},
{
className: "tag",
begin: /