\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || { groups: {} };
if (groups.code !== undefined) {
const code2 = Number.parseFloat(groups.code);
escapeCode = code2 === END_CODE ? undefined : code2;
} else if (groups.uri !== undefined) {
escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
}
}
const code = ansi_styles_default2.codes.get(Number(escapeCode));
if (pre[index + 1] === `
`) {
if (escapeUrl) {
returnValue += wrapAnsiHyperlink("");
}
if (escapeCode && code) {
returnValue += wrapAnsiCode(code);
}
} else if (character === `
`) {
if (escapeCode && code) {
returnValue += wrapAnsiCode(escapeCode);
}
if (escapeUrl) {
returnValue += wrapAnsiHyperlink(escapeUrl);
}
}
preStringIndex += character.length;
}
return returnValue;
};
var init_wrap_ansi = __esm(() => {
init_string_width();
init_strip_ansi();
init_ansi_styles2();
ESCAPES2 = new Set([
"\x1B",
""
]);
ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
});
// src/ink/wrapAnsi.ts
var wrapAnsiBun, wrapAnsi2;
var init_wrapAnsi = __esm(() => {
init_wrap_ansi();
wrapAnsiBun = typeof Bun !== "undefined" && typeof Bun.wrapAnsi === "function" ? Bun.wrapAnsi : null;
wrapAnsi2 = wrapAnsiBun ?? wrapAnsi;
});
// src/ink/wrap-text.ts
function sliceFit(text, start, end) {
const s = sliceAnsi(text, start, end);
return stringWidth(s) > end - start ? sliceAnsi(text, start, end - 1) : s;
}
function truncate2(text, columns, position) {
if (columns < 1)
return "";
if (columns === 1)
return ELLIPSIS;
const length = stringWidth(text);
if (length <= columns)
return text;
if (position === "start") {
return ELLIPSIS + sliceFit(text, length - columns + 1, length);
}
if (position === "middle") {
const half = Math.floor(columns / 2);
return sliceFit(text, 0, half) + ELLIPSIS + sliceFit(text, length - (columns - half) + 1, length);
}
return sliceFit(text, 0, columns - 1) + ELLIPSIS;
}
function wrapText2(text, maxWidth, wrapType) {
if (wrapType === "wrap") {
return wrapAnsi2(text, maxWidth, {
trim: false,
hard: true
});
}
if (wrapType === "wrap-trim") {
return wrapAnsi2(text, maxWidth, {
trim: true,
hard: true
});
}
if (wrapType.startsWith("truncate")) {
let position = "end";
if (wrapType === "truncate-middle") {
position = "middle";
}
if (wrapType === "truncate-start") {
position = "start";
}
return truncate2(text, maxWidth, position);
}
return text;
}
var ELLIPSIS = "…";
var init_wrap_text = __esm(() => {
init_sliceAnsi();
init_stringWidth();
init_wrapAnsi();
});
// src/ink/dom.ts
function collectRemovedRects(parent, removed, underAbsolute = false) {
if (removed.nodeName === "#text")
return;
const elem = removed;
const isAbsolute5 = underAbsolute || elem.style.position === "absolute";
const cached2 = nodeCache.get(elem);
if (cached2) {
addPendingClear(parent, cached2, isAbsolute5);
nodeCache.delete(elem);
}
for (const child of elem.childNodes) {
collectRemovedRects(parent, child, isAbsolute5);
}
}
function stylesEqual(a2, b) {
return shallowEqual(a2, b);
}
function shallowEqual(a2, b) {
if (a2 === b)
return true;
if (a2 === undefined || b === undefined)
return false;
const aKeys = Object.keys(a2);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length)
return false;
for (const key of aKeys) {
if (a2[key] !== b[key])
return false;
}
return true;
}
function isDOMElement(node) {
return node.nodeName !== "#text";
}
function findOwnerChainAtRow(root2, y2) {
let best = [];
walk(root2, 0);
return best;
function walk(node, offsetY) {
const yoga = node.yogaNode;
if (!yoga || yoga.getDisplay() === LayoutDisplay.None)
return;
const top = offsetY + yoga.getComputedTop();
const height = yoga.getComputedHeight();
if (y2 < top || y2 >= top + height)
return;
if (node.debugOwnerChain)
best = node.debugOwnerChain;
for (const child of node.childNodes) {
if (isDOMElement(child))
walk(child, top);
}
}
}
var createNode = (nodeName) => {
const needsYogaNode = nodeName !== "ink-virtual-text" && nodeName !== "ink-link" && nodeName !== "ink-progress";
const node = {
nodeName,
style: {},
attributes: {},
childNodes: [],
parentNode: undefined,
yogaNode: needsYogaNode ? createLayoutNode() : undefined,
dirty: false
};
if (nodeName === "ink-text") {
node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node));
} else if (nodeName === "ink-raw-ansi") {
node.yogaNode?.setMeasureFunc(measureRawAnsiNode.bind(null, node));
}
return node;
}, appendChildNode = (node, childNode) => {
if (childNode.parentNode) {
removeChildNode(childNode.parentNode, childNode);
}
childNode.parentNode = node;
node.childNodes.push(childNode);
if (childNode.yogaNode) {
node.yogaNode?.insertChild(childNode.yogaNode, node.yogaNode.getChildCount());
}
markDirty(node);
}, insertBeforeNode = (node, newChildNode, beforeChildNode) => {
if (newChildNode.parentNode) {
removeChildNode(newChildNode.parentNode, newChildNode);
}
newChildNode.parentNode = node;
const index = node.childNodes.indexOf(beforeChildNode);
if (index >= 0) {
let yogaIndex = 0;
if (newChildNode.yogaNode && node.yogaNode) {
for (let i2 = 0;i2 < index; i2++) {
if (node.childNodes[i2]?.yogaNode) {
yogaIndex++;
}
}
}
node.childNodes.splice(index, 0, newChildNode);
if (newChildNode.yogaNode && node.yogaNode) {
node.yogaNode.insertChild(newChildNode.yogaNode, yogaIndex);
}
markDirty(node);
return;
}
node.childNodes.push(newChildNode);
if (newChildNode.yogaNode) {
node.yogaNode?.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());
}
markDirty(node);
}, removeChildNode = (node, removeNode) => {
if (removeNode.yogaNode) {
removeNode.parentNode?.yogaNode?.removeChild(removeNode.yogaNode);
}
collectRemovedRects(node, removeNode);
removeNode.parentNode = undefined;
const index = node.childNodes.indexOf(removeNode);
if (index >= 0) {
node.childNodes.splice(index, 1);
}
markDirty(node);
}, setAttribute = (node, key, value) => {
if (key === "children") {
return;
}
if (node.attributes[key] === value) {
return;
}
node.attributes[key] = value;
markDirty(node);
}, setStyle = (node, style) => {
if (stylesEqual(node.style, style)) {
return;
}
node.style = style;
markDirty(node);
}, setTextStyles = (node, textStyles) => {
if (shallowEqual(node.textStyles, textStyles)) {
return;
}
node.textStyles = textStyles;
markDirty(node);
}, createTextNode = (text) => {
const node = {
nodeName: "#text",
nodeValue: text,
yogaNode: undefined,
parentNode: undefined,
style: {}
};
setTextNodeValue(node, text);
return node;
}, measureTextNode = function(node, width, widthMode) {
const rawText = node.nodeName === "#text" ? node.nodeValue : squash_text_nodes_default(node);
const text = expandTabs(rawText);
const dimensions = measure_text_default(text, width);
if (dimensions.width <= width) {
return dimensions;
}
if (dimensions.width >= 1 && width > 0 && width < 1) {
return dimensions;
}
if (text.includes(`
`) && widthMode === LayoutMeasureMode.Undefined) {
const effectiveWidth = Math.max(width, dimensions.width);
return measure_text_default(text, effectiveWidth);
}
const textWrap = node.style?.textWrap ?? "wrap";
const wrappedText = wrapText2(text, width, textWrap);
return measure_text_default(wrappedText, width);
}, measureRawAnsiNode = function(node) {
return {
width: node.attributes["rawWidth"],
height: node.attributes["rawHeight"]
};
}, markDirty = (node) => {
let current = node;
let markedYoga = false;
while (current) {
if (current.nodeName !== "#text") {
current.dirty = true;
if (!markedYoga && (current.nodeName === "ink-text" || current.nodeName === "ink-raw-ansi") && current.yogaNode) {
current.yogaNode.markDirty();
markedYoga = true;
}
}
current = current.parentNode;
}
}, scheduleRenderFrom = (node) => {
let cur = node;
while (cur?.parentNode)
cur = cur.parentNode;
if (cur && cur.nodeName !== "#text")
cur.onRender?.();
}, setTextNodeValue = (node, text) => {
if (typeof text !== "string") {
text = String(text);
}
if (node.nodeValue === text) {
return;
}
node.nodeValue = text;
markDirty(node);
}, clearYogaNodeReferences = (node) => {
if ("childNodes" in node) {
for (const child of node.childNodes) {
clearYogaNodeReferences(child);
}
}
node.yogaNode = undefined;
};
var init_dom = __esm(() => {
init_engine();
init_node4();
init_measure_text();
init_node_cache();
init_squash_text_nodes();
init_tabstops();
init_wrap_text();
});
// src/ink/events/event-handlers.ts
var HANDLER_FOR_EVENT, EVENT_HANDLER_PROPS;
var init_event_handlers = __esm(() => {
HANDLER_FOR_EVENT = {
keydown: { bubble: "onKeyDown", capture: "onKeyDownCapture" },
focus: { bubble: "onFocus", capture: "onFocusCapture" },
blur: { bubble: "onBlur", capture: "onBlurCapture" },
paste: { bubble: "onPaste", capture: "onPasteCapture" },
resize: { bubble: "onResize" },
click: { bubble: "onClick" }
};
EVENT_HANDLER_PROPS = new Set([
"onKeyDown",
"onKeyDownCapture",
"onFocus",
"onFocusCapture",
"onBlur",
"onBlurCapture",
"onPaste",
"onPasteCapture",
"onResize",
"onClick",
"onMouseEnter",
"onMouseLeave"
]);
});
// src/ink/events/dispatcher.ts
function getHandler(node, eventType, capture) {
const handlers = node._eventHandlers;
if (!handlers)
return;
const mapping = HANDLER_FOR_EVENT[eventType];
if (!mapping)
return;
const propName = capture ? mapping.capture : mapping.bubble;
if (!propName)
return;
return handlers[propName];
}
function collectListeners(target, event) {
const listeners = [];
let node = target;
while (node) {
const isTarget = node === target;
const captureHandler = getHandler(node, event.type, true);
const bubbleHandler = getHandler(node, event.type, false);
if (captureHandler) {
listeners.unshift({
node,
handler: captureHandler,
phase: isTarget ? "at_target" : "capturing"
});
}
if (bubbleHandler && (event.bubbles || isTarget)) {
listeners.push({
node,
handler: bubbleHandler,
phase: isTarget ? "at_target" : "bubbling"
});
}
node = node.parentNode;
}
return listeners;
}
function processDispatchQueue(listeners, event) {
let previousNode;
for (const { node, handler: handler2, phase } of listeners) {
if (event._isImmediatePropagationStopped()) {
break;
}
if (event._isPropagationStopped() && node !== previousNode) {
break;
}
event._setEventPhase(phase);
event._setCurrentTarget(node);
event._prepareForTarget(node);
try {
handler2(event);
} catch (error44) {
logError2(error44);
}
previousNode = node;
}
}
function getEventPriority(eventType) {
switch (eventType) {
case "keydown":
case "keyup":
case "click":
case "focus":
case "blur":
case "paste":
return import_constants13.DiscreteEventPriority;
case "resize":
case "scroll":
case "mousemove":
return import_constants13.ContinuousEventPriority;
default:
return import_constants13.DefaultEventPriority;
}
}
class Dispatcher {
currentEvent = null;
currentUpdatePriority = import_constants13.DefaultEventPriority;
discreteUpdates = null;
resolveEventPriority() {
if (this.currentUpdatePriority !== import_constants13.NoEventPriority) {
return this.currentUpdatePriority;
}
if (this.currentEvent) {
return getEventPriority(this.currentEvent.type);
}
return import_constants13.DefaultEventPriority;
}
dispatch(target, event) {
const previousEvent = this.currentEvent;
this.currentEvent = event;
try {
event._setTarget(target);
const listeners = collectListeners(target, event);
processDispatchQueue(listeners, event);
event._setEventPhase("none");
event._setCurrentTarget(null);
return !event.defaultPrevented;
} finally {
this.currentEvent = previousEvent;
}
}
dispatchDiscrete(target, event) {
if (!this.discreteUpdates) {
return this.dispatch(target, event);
}
return this.discreteUpdates((t, e) => this.dispatch(t, e), target, event, undefined, undefined);
}
dispatchContinuous(target, event) {
const previousPriority = this.currentUpdatePriority;
try {
this.currentUpdatePriority = import_constants13.ContinuousEventPriority;
return this.dispatch(target, event);
} finally {
this.currentUpdatePriority = previousPriority;
}
}
}
var import_constants13;
var init_dispatcher = __esm(() => {
init_log3();
init_event_handlers();
import_constants13 = __toESM(require_constants7(), 1);
});
// src/ink/events/terminal-event.ts
var TerminalEvent;
var init_terminal_event = __esm(() => {
TerminalEvent = class TerminalEvent extends Event2 {
type;
timeStamp;
bubbles;
cancelable;
_target = null;
_currentTarget = null;
_eventPhase = "none";
_propagationStopped = false;
_defaultPrevented = false;
constructor(type, init) {
super();
this.type = type;
this.timeStamp = performance.now();
this.bubbles = init?.bubbles ?? true;
this.cancelable = init?.cancelable ?? true;
}
get target() {
return this._target;
}
get currentTarget() {
return this._currentTarget;
}
get eventPhase() {
return this._eventPhase;
}
get defaultPrevented() {
return this._defaultPrevented;
}
stopPropagation() {
this._propagationStopped = true;
}
stopImmediatePropagation() {
super.stopImmediatePropagation();
this._propagationStopped = true;
}
preventDefault() {
if (this.cancelable) {
this._defaultPrevented = true;
}
}
_setTarget(target) {
this._target = target;
}
_setCurrentTarget(target) {
this._currentTarget = target;
}
_setEventPhase(phase) {
this._eventPhase = phase;
}
_isPropagationStopped() {
return this._propagationStopped;
}
_isImmediatePropagationStopped() {
return this.didStopImmediatePropagation();
}
_prepareForTarget(_target) {}
};
});
// src/ink/events/focus-event.ts
var FocusEvent;
var init_focus_event = __esm(() => {
init_terminal_event();
FocusEvent = class FocusEvent extends TerminalEvent {
relatedTarget;
constructor(type, relatedTarget = null) {
super(type, { bubbles: true, cancelable: false });
this.relatedTarget = relatedTarget;
}
};
});
// src/ink/focus.ts
class FocusManager {
activeElement = null;
dispatchFocusEvent;
enabled = true;
focusStack = [];
constructor(dispatchFocusEvent) {
this.dispatchFocusEvent = dispatchFocusEvent;
}
focus(node) {
if (node === this.activeElement)
return;
if (!this.enabled)
return;
const previous = this.activeElement;
if (previous) {
const idx = this.focusStack.indexOf(previous);
if (idx !== -1)
this.focusStack.splice(idx, 1);
this.focusStack.push(previous);
if (this.focusStack.length > MAX_FOCUS_STACK)
this.focusStack.shift();
this.dispatchFocusEvent(previous, new FocusEvent("blur", node));
}
this.activeElement = node;
this.dispatchFocusEvent(node, new FocusEvent("focus", previous));
}
blur() {
if (!this.activeElement)
return;
const previous = this.activeElement;
this.activeElement = null;
this.dispatchFocusEvent(previous, new FocusEvent("blur", null));
}
handleNodeRemoved(node, root2) {
this.focusStack = this.focusStack.filter((n2) => n2 !== node && isInTree(n2, root2));
if (!this.activeElement)
return;
if (this.activeElement !== node && isInTree(this.activeElement, root2)) {
return;
}
const removed = this.activeElement;
this.activeElement = null;
this.dispatchFocusEvent(removed, new FocusEvent("blur", null));
while (this.focusStack.length > 0) {
const candidate = this.focusStack.pop();
if (isInTree(candidate, root2)) {
this.activeElement = candidate;
this.dispatchFocusEvent(candidate, new FocusEvent("focus", removed));
return;
}
}
}
handleAutoFocus(node) {
this.focus(node);
}
handleClickFocus(node) {
const tabIndex = node.attributes["tabIndex"];
if (typeof tabIndex !== "number")
return;
this.focus(node);
}
enable() {
this.enabled = true;
}
disable() {
this.enabled = false;
}
focusNext(root2) {
this.moveFocus(1, root2);
}
focusPrevious(root2) {
this.moveFocus(-1, root2);
}
moveFocus(direction, root2) {
if (!this.enabled)
return;
const tabbable = collectTabbable(root2);
if (tabbable.length === 0)
return;
const currentIndex = this.activeElement ? tabbable.indexOf(this.activeElement) : -1;
const nextIndex = currentIndex === -1 ? direction === 1 ? 0 : tabbable.length - 1 : (currentIndex + direction + tabbable.length) % tabbable.length;
const next = tabbable[nextIndex];
if (next) {
this.focus(next);
}
}
}
function collectTabbable(root2) {
const result = [];
walkTree(root2, result);
return result;
}
function walkTree(node, result) {
const tabIndex = node.attributes["tabIndex"];
if (typeof tabIndex === "number" && tabIndex >= 0) {
result.push(node);
}
for (const child of node.childNodes) {
if (child.nodeName !== "#text") {
walkTree(child, result);
}
}
}
function isInTree(node, root2) {
let current = node;
while (current) {
if (current === root2)
return true;
current = current.parentNode;
}
return false;
}
function getRootNode(node) {
let current = node;
while (current) {
if (current.focusManager)
return current;
current = current.parentNode;
}
throw new Error("Node is not in a tree with a FocusManager");
}
function getFocusManager(node) {
return getRootNode(node).focusManager;
}
var MAX_FOCUS_STACK = 32;
var init_focus = __esm(() => {
init_focus_event();
});
// src/ink/styles.ts
function applyPositionEdge(node, edge, v) {
if (typeof v === "string") {
node.setPositionPercent(edge, Number.parseInt(v, 10));
} else if (typeof v === "number") {
node.setPosition(edge, v);
} else {
node.setPosition(edge, Number.NaN);
}
}
var applyPositionStyles = (node, style) => {
if ("position" in style) {
node.setPositionType(style.position === "absolute" ? LayoutPositionType.Absolute : LayoutPositionType.Relative);
}
if ("top" in style)
applyPositionEdge(node, "top", style.top);
if ("bottom" in style)
applyPositionEdge(node, "bottom", style.bottom);
if ("left" in style)
applyPositionEdge(node, "left", style.left);
if ("right" in style)
applyPositionEdge(node, "right", style.right);
}, applyOverflowStyles = (node, style) => {
const y2 = style.overflowY ?? style.overflow;
const x2 = style.overflowX ?? style.overflow;
if (y2 === "scroll" || x2 === "scroll") {
node.setOverflow(LayoutOverflow.Scroll);
} else if (y2 === "hidden" || x2 === "hidden") {
node.setOverflow(LayoutOverflow.Hidden);
} else if ("overflow" in style || "overflowX" in style || "overflowY" in style) {
node.setOverflow(LayoutOverflow.Visible);
}
}, applyMarginStyles = (node, style) => {
if ("margin" in style) {
node.setMargin(LayoutEdge.All, style.margin ?? 0);
}
if ("marginX" in style) {
node.setMargin(LayoutEdge.Horizontal, style.marginX ?? 0);
}
if ("marginY" in style) {
node.setMargin(LayoutEdge.Vertical, style.marginY ?? 0);
}
if ("marginLeft" in style) {
node.setMargin(LayoutEdge.Start, style.marginLeft || 0);
}
if ("marginRight" in style) {
node.setMargin(LayoutEdge.End, style.marginRight || 0);
}
if ("marginTop" in style) {
node.setMargin(LayoutEdge.Top, style.marginTop || 0);
}
if ("marginBottom" in style) {
node.setMargin(LayoutEdge.Bottom, style.marginBottom || 0);
}
}, applyPaddingStyles = (node, style) => {
if ("padding" in style) {
node.setPadding(LayoutEdge.All, style.padding ?? 0);
}
if ("paddingX" in style) {
node.setPadding(LayoutEdge.Horizontal, style.paddingX ?? 0);
}
if ("paddingY" in style) {
node.setPadding(LayoutEdge.Vertical, style.paddingY ?? 0);
}
if ("paddingLeft" in style) {
node.setPadding(LayoutEdge.Left, style.paddingLeft || 0);
}
if ("paddingRight" in style) {
node.setPadding(LayoutEdge.Right, style.paddingRight || 0);
}
if ("paddingTop" in style) {
node.setPadding(LayoutEdge.Top, style.paddingTop || 0);
}
if ("paddingBottom" in style) {
node.setPadding(LayoutEdge.Bottom, style.paddingBottom || 0);
}
}, applyFlexStyles = (node, style) => {
if ("flexGrow" in style) {
node.setFlexGrow(style.flexGrow ?? 0);
}
if ("flexShrink" in style) {
node.setFlexShrink(typeof style.flexShrink === "number" ? style.flexShrink : 1);
}
if ("flexWrap" in style) {
if (style.flexWrap === "nowrap") {
node.setFlexWrap(LayoutWrap.NoWrap);
}
if (style.flexWrap === "wrap") {
node.setFlexWrap(LayoutWrap.Wrap);
}
if (style.flexWrap === "wrap-reverse") {
node.setFlexWrap(LayoutWrap.WrapReverse);
}
}
if ("flexDirection" in style) {
if (style.flexDirection === "row") {
node.setFlexDirection(LayoutFlexDirection.Row);
}
if (style.flexDirection === "row-reverse") {
node.setFlexDirection(LayoutFlexDirection.RowReverse);
}
if (style.flexDirection === "column") {
node.setFlexDirection(LayoutFlexDirection.Column);
}
if (style.flexDirection === "column-reverse") {
node.setFlexDirection(LayoutFlexDirection.ColumnReverse);
}
}
if ("flexBasis" in style) {
if (typeof style.flexBasis === "number") {
node.setFlexBasis(style.flexBasis);
} else if (typeof style.flexBasis === "string") {
node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10));
} else {
node.setFlexBasis(Number.NaN);
}
}
if ("alignItems" in style) {
if (style.alignItems === "stretch" || !style.alignItems) {
node.setAlignItems(LayoutAlign.Stretch);
}
if (style.alignItems === "flex-start") {
node.setAlignItems(LayoutAlign.FlexStart);
}
if (style.alignItems === "center") {
node.setAlignItems(LayoutAlign.Center);
}
if (style.alignItems === "flex-end") {
node.setAlignItems(LayoutAlign.FlexEnd);
}
}
if ("alignSelf" in style) {
if (style.alignSelf === "auto" || !style.alignSelf) {
node.setAlignSelf(LayoutAlign.Auto);
}
if (style.alignSelf === "flex-start") {
node.setAlignSelf(LayoutAlign.FlexStart);
}
if (style.alignSelf === "center") {
node.setAlignSelf(LayoutAlign.Center);
}
if (style.alignSelf === "flex-end") {
node.setAlignSelf(LayoutAlign.FlexEnd);
}
}
if ("justifyContent" in style) {
if (style.justifyContent === "flex-start" || !style.justifyContent) {
node.setJustifyContent(LayoutJustify.FlexStart);
}
if (style.justifyContent === "center") {
node.setJustifyContent(LayoutJustify.Center);
}
if (style.justifyContent === "flex-end") {
node.setJustifyContent(LayoutJustify.FlexEnd);
}
if (style.justifyContent === "space-between") {
node.setJustifyContent(LayoutJustify.SpaceBetween);
}
if (style.justifyContent === "space-around") {
node.setJustifyContent(LayoutJustify.SpaceAround);
}
if (style.justifyContent === "space-evenly") {
node.setJustifyContent(LayoutJustify.SpaceEvenly);
}
}
}, applyDimensionStyles = (node, style) => {
if ("width" in style) {
if (typeof style.width === "number") {
node.setWidth(style.width);
} else if (typeof style.width === "string") {
node.setWidthPercent(Number.parseInt(style.width, 10));
} else {
node.setWidthAuto();
}
}
if ("height" in style) {
if (typeof style.height === "number") {
node.setHeight(style.height);
} else if (typeof style.height === "string") {
node.setHeightPercent(Number.parseInt(style.height, 10));
} else {
node.setHeightAuto();
}
}
if ("minWidth" in style) {
if (typeof style.minWidth === "string") {
node.setMinWidthPercent(Number.parseInt(style.minWidth, 10));
} else {
node.setMinWidth(style.minWidth ?? 0);
}
}
if ("minHeight" in style) {
if (typeof style.minHeight === "string") {
node.setMinHeightPercent(Number.parseInt(style.minHeight, 10));
} else {
node.setMinHeight(style.minHeight ?? 0);
}
}
if ("maxWidth" in style) {
if (typeof style.maxWidth === "string") {
node.setMaxWidthPercent(Number.parseInt(style.maxWidth, 10));
} else {
node.setMaxWidth(style.maxWidth ?? 0);
}
}
if ("maxHeight" in style) {
if (typeof style.maxHeight === "string") {
node.setMaxHeightPercent(Number.parseInt(style.maxHeight, 10));
} else {
node.setMaxHeight(style.maxHeight ?? 0);
}
}
}, applyDisplayStyles = (node, style) => {
if ("display" in style) {
node.setDisplay(style.display === "flex" ? LayoutDisplay.Flex : LayoutDisplay.None);
}
}, applyBorderStyles = (node, style, resolvedStyle) => {
const resolved = resolvedStyle ?? style;
if ("borderStyle" in style) {
const borderWidth = style.borderStyle ? 1 : 0;
node.setBorder(LayoutEdge.Top, resolved.borderTop !== false ? borderWidth : 0);
node.setBorder(LayoutEdge.Bottom, resolved.borderBottom !== false ? borderWidth : 0);
node.setBorder(LayoutEdge.Left, resolved.borderLeft !== false ? borderWidth : 0);
node.setBorder(LayoutEdge.Right, resolved.borderRight !== false ? borderWidth : 0);
} else {
if ("borderTop" in style && style.borderTop !== undefined) {
node.setBorder(LayoutEdge.Top, style.borderTop === false ? 0 : 1);
}
if ("borderBottom" in style && style.borderBottom !== undefined) {
node.setBorder(LayoutEdge.Bottom, style.borderBottom === false ? 0 : 1);
}
if ("borderLeft" in style && style.borderLeft !== undefined) {
node.setBorder(LayoutEdge.Left, style.borderLeft === false ? 0 : 1);
}
if ("borderRight" in style && style.borderRight !== undefined) {
node.setBorder(LayoutEdge.Right, style.borderRight === false ? 0 : 1);
}
}
}, applyGapStyles = (node, style) => {
if ("gap" in style) {
node.setGap(LayoutGutter.All, style.gap ?? 0);
}
if ("columnGap" in style) {
node.setGap(LayoutGutter.Column, style.columnGap ?? 0);
}
if ("rowGap" in style) {
node.setGap(LayoutGutter.Row, style.rowGap ?? 0);
}
}, styles4 = (node, style = {}, resolvedStyle) => {
applyPositionStyles(node, style);
applyOverflowStyles(node, style);
applyMarginStyles(node, style);
applyPaddingStyles(node, style);
applyFlexStyles(node, style);
applyDimensionStyles(node, style);
applyDisplayStyles(node, style);
applyBorderStyles(node, style, resolvedStyle);
applyGapStyles(node, style);
}, styles_default;
var init_styles = __esm(() => {
init_node4();
styles_default = styles4;
});
// src/ink/devtools.ts
var exports_devtools = {};
var init_devtools = () => {};
// src/ink/reconciler.ts
import { appendFileSync as appendFileSync3 } from "fs";
function setEventHandler(node, key, value) {
if (!node._eventHandlers) {
node._eventHandlers = {};
}
node._eventHandlers[key] = value;
}
function applyProp(node, key, value) {
if (key === "children")
return;
if (key === "style") {
setStyle(node, value);
if (node.yogaNode) {
styles_default(node.yogaNode, value);
}
return;
}
if (key === "textStyles") {
node.textStyles = value;
return;
}
if (EVENT_HANDLER_PROPS.has(key)) {
setEventHandler(node, key, value);
return;
}
setAttribute(node, key, value);
}
function getOwnerChain(fiber) {
const chain = [];
const seen = new Set;
let cur = fiber;
for (let i2 = 0;cur && i2 < 50; i2++) {
if (seen.has(cur))
break;
seen.add(cur);
const t = cur.elementType;
const name = typeof t === "function" ? t.displayName || t.name : typeof t === "string" ? undefined : t?.displayName || t?.name;
if (name && name !== chain[chain.length - 1])
chain.push(name);
cur = cur._debugOwner ?? cur.return;
}
return chain;
}
function isDebugRepaintsEnabled() {
if (debugRepaints === undefined) {
debugRepaints = isEnvTruthy(process.env.CLAUDE_CODE_DEBUG_REPAINTS);
}
return debugRepaints;
}
function recordYogaMs(ms) {
_lastYogaMs = ms;
}
function getLastYogaMs() {
return _lastYogaMs;
}
function markCommitStart() {
_commitStart = performance.now();
}
function getLastCommitMs() {
return _lastCommitMs;
}
function resetProfileCounters() {
_lastYogaMs = 0;
_lastCommitMs = 0;
_commitStart = 0;
}
var import_react_reconciler, diff = (before, after) => {
if (before === after) {
return;
}
if (!before) {
return after;
}
const changed = {};
let isChanged = false;
for (const key of Object.keys(before)) {
const isDeleted = after ? !Object.hasOwn(after, key) : true;
if (isDeleted) {
changed[key] = undefined;
isChanged = true;
}
}
if (after) {
for (const key of Object.keys(after)) {
if (after[key] !== before[key]) {
changed[key] = after[key];
isChanged = true;
}
}
}
return isChanged ? changed : undefined;
}, cleanupYogaNode = (node) => {
const yogaNode = node.yogaNode;
if (yogaNode) {
yogaNode.unsetMeasureFunc();
clearYogaNodeReferences(node);
yogaNode.freeRecursive();
}
}, debugRepaints, dispatcher, COMMIT_LOG, _commits = 0, _lastLog = 0, _lastCommitAt = 0, _maxGapMs = 0, _createCount = 0, _prepareAt = 0, _lastYogaMs = 0, _lastCommitMs = 0, _commitStart = 0, reconciler, reconciler_default;
var init_reconciler = __esm(() => {
init_yoga_layout();
init_envUtils();
init_dom();
init_dispatcher();
init_event_handlers();
init_focus();
init_node4();
init_styles();
import_react_reconciler = __toESM(require_react_reconciler(), 1);
if (true) {
try {
Promise.resolve().then(() => init_devtools());
} catch (error44) {
if (error44.code === "ERR_MODULE_NOT_FOUND") {
console.warn(`
The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,
but this failed as it was not installed. Debugging with React Devtools requires it.
To install use this command:
$ npm install --save-dev react-devtools-core
`.trim() + `
`);
} else {
throw error44;
}
}
}
dispatcher = new Dispatcher;
COMMIT_LOG = process.env.CLAUDE_CODE_COMMIT_LOG;
reconciler = import_react_reconciler.default({
getRootHostContext: () => ({ isInsideText: false }),
prepareForCommit: () => {
if (COMMIT_LOG)
_prepareAt = performance.now();
return null;
},
preparePortalMount: () => null,
clearContainer: () => false,
resetAfterCommit(rootNode) {
_lastCommitMs = _commitStart > 0 ? performance.now() - _commitStart : 0;
_commitStart = 0;
if (COMMIT_LOG) {
const now2 = performance.now();
_commits++;
const gap = _lastCommitAt > 0 ? now2 - _lastCommitAt : 0;
if (gap > _maxGapMs)
_maxGapMs = gap;
_lastCommitAt = now2;
const reconcileMs = _prepareAt > 0 ? now2 - _prepareAt : 0;
if (gap > 30 || reconcileMs > 20 || _createCount > 50) {
appendFileSync3(COMMIT_LOG, `${now2.toFixed(1)} gap=${gap.toFixed(1)}ms reconcile=${reconcileMs.toFixed(1)}ms creates=${_createCount}
`);
}
_createCount = 0;
if (now2 - _lastLog > 1000) {
appendFileSync3(COMMIT_LOG, `${now2.toFixed(1)} commits=${_commits}/s maxGap=${_maxGapMs.toFixed(1)}ms
`);
_commits = 0;
_maxGapMs = 0;
_lastLog = now2;
}
}
const _t0 = COMMIT_LOG ? performance.now() : 0;
if (typeof rootNode.onComputeLayout === "function") {
rootNode.onComputeLayout();
}
if (COMMIT_LOG) {
const layoutMs = performance.now() - _t0;
if (layoutMs > 20) {
const c6 = getYogaCounters();
appendFileSync3(COMMIT_LOG, `${_t0.toFixed(1)} SLOW_YOGA ${layoutMs.toFixed(1)}ms visited=${c6.visited} measured=${c6.measured} hits=${c6.cacheHits} live=${c6.live}
`);
}
}
if (false) {}
const _tr = COMMIT_LOG ? performance.now() : 0;
rootNode.onRender?.();
if (COMMIT_LOG) {
const renderMs = performance.now() - _tr;
if (renderMs > 10) {
appendFileSync3(COMMIT_LOG, `${_tr.toFixed(1)} SLOW_PAINT ${renderMs.toFixed(1)}ms
`);
}
}
},
getChildHostContext(parentHostContext, type) {
const previousIsInsideText = parentHostContext.isInsideText;
const isInsideText = type === "ink-text" || type === "ink-virtual-text" || type === "ink-link";
if (previousIsInsideText === isInsideText) {
return parentHostContext;
}
return { isInsideText };
},
shouldSetTextContent: () => false,
createInstance(originalType, newProps, _root, hostContext, internalHandle) {
if (hostContext.isInsideText && originalType === "ink-box") {
throw new Error(` can't be nested inside component`);
}
const type = originalType === "ink-text" && hostContext.isInsideText ? "ink-virtual-text" : originalType;
const node = createNode(type);
if (COMMIT_LOG)
_createCount++;
for (const [key, value] of Object.entries(newProps)) {
applyProp(node, key, value);
}
if (isDebugRepaintsEnabled()) {
node.debugOwnerChain = getOwnerChain(internalHandle);
}
return node;
},
createTextInstance(text, _root, hostContext) {
if (!hostContext.isInsideText) {
throw new Error(`Text string "${text}" must be rendered inside component`);
}
return createTextNode(text);
},
resetTextContent() {},
hideTextInstance(node) {
setTextNodeValue(node, "");
},
unhideTextInstance(node, text) {
setTextNodeValue(node, text);
},
getPublicInstance: (instance) => instance,
hideInstance(node) {
node.isHidden = true;
node.yogaNode?.setDisplay(LayoutDisplay.None);
markDirty(node);
},
unhideInstance(node) {
node.isHidden = false;
node.yogaNode?.setDisplay(LayoutDisplay.Flex);
markDirty(node);
},
appendInitialChild: appendChildNode,
appendChild: appendChildNode,
insertBefore: insertBeforeNode,
finalizeInitialChildren(_node, _type, props) {
return props["autoFocus"] === true;
},
commitMount(node) {
getFocusManager(node).handleAutoFocus(node);
},
isPrimaryRenderer: true,
supportsMutation: true,
supportsPersistence: false,
supportsHydration: false,
scheduleTimeout: setTimeout,
cancelTimeout: clearTimeout,
noTimeout: -1,
getCurrentUpdatePriority: () => dispatcher.currentUpdatePriority,
beforeActiveInstanceBlur() {},
afterActiveInstanceBlur() {},
detachDeletedInstance() {},
getInstanceFromNode: () => null,
prepareScopeUpdate() {},
getInstanceFromScope: () => null,
appendChildToContainer: appendChildNode,
insertInContainerBefore: insertBeforeNode,
removeChildFromContainer(node, removeNode) {
removeChildNode(node, removeNode);
cleanupYogaNode(removeNode);
getFocusManager(node).handleNodeRemoved(removeNode, node);
},
commitUpdate(node, _type, oldProps, newProps) {
const props = diff(oldProps, newProps);
const style = diff(oldProps["style"], newProps["style"]);
if (props) {
for (const [key, value] of Object.entries(props)) {
if (key === "style") {
setStyle(node, value);
continue;
}
if (key === "textStyles") {
setTextStyles(node, value);
continue;
}
if (EVENT_HANDLER_PROPS.has(key)) {
setEventHandler(node, key, value);
continue;
}
setAttribute(node, key, value);
}
}
if (style && node.yogaNode) {
styles_default(node.yogaNode, style, newProps["style"]);
}
},
commitTextUpdate(node, _oldText, newText) {
setTextNodeValue(node, newText);
},
removeChild(node, removeNode) {
removeChildNode(node, removeNode);
cleanupYogaNode(removeNode);
if (removeNode.nodeName !== "#text") {
const root2 = getRootNode(node);
root2.focusManager.handleNodeRemoved(removeNode, root2);
}
},
maySuspendCommit() {
return false;
},
preloadInstance() {
return true;
},
startSuspendingCommit() {},
suspendInstance() {},
waitForCommitToBeReady() {
return null;
},
NotPendingTransition: null,
HostTransitionContext: {
$$typeof: Symbol.for("react.context"),
_currentValue: null
},
setCurrentUpdatePriority(newPriority) {
dispatcher.currentUpdatePriority = newPriority;
},
resolveUpdatePriority() {
return dispatcher.resolveEventPriority();
},
resetFormInstance() {},
requestPostPaintCallback() {},
shouldAttemptEagerTransition() {
return false;
},
trackSchedulerEvent() {},
resolveEventType() {
return dispatcher.currentEvent?.type ?? null;
},
resolveEventTimeStamp() {
return dispatcher.currentEvent?.timeStamp ?? -1.1;
}
});
dispatcher.discreteUpdates = reconciler.discreteUpdates.bind(reconciler);
reconciler_default = reconciler;
});
// src/ink/layout/geometry.ts
function unionRect(a2, b) {
const minX = Math.min(a2.x, b.x);
const minY = Math.min(a2.y, b.y);
const maxX = Math.max(a2.x + a2.width, b.x + b.width);
const maxY = Math.max(a2.y + a2.height, b.y + b.height);
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
}
function clamp(value, min, max) {
if (min !== undefined && value < min)
return min;
if (max !== undefined && value > max)
return max;
return value;
}
var init_geometry = () => {};
// src/ink/warn.ts
function ifNotInteger(value, name) {
if (value === undefined)
return;
if (Number.isInteger(value))
return;
logForDebugging(`${name} should be an integer, got ${value}`, {
level: "warn"
});
}
var init_warn = __esm(() => {
init_debug();
});
// src/ink/screen.ts
class CharPool {
strings = [" ", ""];
stringMap = new Map([
[" ", 0],
["", 1]
]);
ascii = initCharAscii();
intern(char) {
if (char.length === 1) {
const code = char.charCodeAt(0);
if (code < 128) {
const cached2 = this.ascii[code];
if (cached2 !== -1)
return cached2;
const index2 = this.strings.length;
this.strings.push(char);
this.ascii[code] = index2;
return index2;
}
}
const existing = this.stringMap.get(char);
if (existing !== undefined)
return existing;
const index = this.strings.length;
this.strings.push(char);
this.stringMap.set(char, index);
return index;
}
get(index) {
return this.strings[index] ?? " ";
}
}
class HyperlinkPool {
strings = [""];
stringMap = new Map;
intern(hyperlink) {
if (!hyperlink)
return 0;
let id = this.stringMap.get(hyperlink);
if (id === undefined) {
id = this.strings.length;
this.strings.push(hyperlink);
this.stringMap.set(hyperlink, id);
}
return id;
}
get(id) {
return id === 0 ? undefined : this.strings[id];
}
}
class StylePool {
ids = new Map;
styles = [];
transitionCache = new Map;
none;
constructor() {
this.none = this.intern([]);
}
intern(styles5) {
const key = styles5.length === 0 ? "" : styles5.map((s) => s.code).join("\x00");
let id = this.ids.get(key);
if (id === undefined) {
const rawId = this.styles.length;
this.styles.push(styles5.length === 0 ? [] : styles5);
id = rawId << 1 | (styles5.length > 0 && hasVisibleSpaceEffect(styles5) ? 1 : 0);
this.ids.set(key, id);
}
return id;
}
get(id) {
return this.styles[id >>> 1] ?? [];
}
transition(fromId, toId) {
if (fromId === toId)
return "";
const key = fromId * 1048576 + toId;
let str = this.transitionCache.get(key);
if (str === undefined) {
str = ansiCodesToString(diffAnsiCodes(this.get(fromId), this.get(toId)));
this.transitionCache.set(key, str);
}
return str;
}
inverseCache = new Map;
withInverse(baseId) {
let id = this.inverseCache.get(baseId);
if (id === undefined) {
const baseCodes = this.get(baseId);
const hasInverse = baseCodes.some((c6) => c6.endCode === "\x1B[27m");
id = hasInverse ? baseId : this.intern([...baseCodes, INVERSE_CODE]);
this.inverseCache.set(baseId, id);
}
return id;
}
currentMatchCache = new Map;
withCurrentMatch(baseId) {
let id = this.currentMatchCache.get(baseId);
if (id === undefined) {
const baseCodes = this.get(baseId);
const codes = baseCodes.filter((c6) => c6.endCode !== "\x1B[39m" && c6.endCode !== "\x1B[49m");
codes.push(YELLOW_FG_CODE);
if (!baseCodes.some((c6) => c6.endCode === "\x1B[27m"))
codes.push(INVERSE_CODE);
if (!baseCodes.some((c6) => c6.endCode === "\x1B[22m"))
codes.push(BOLD_CODE);
if (!baseCodes.some((c6) => c6.endCode === "\x1B[24m"))
codes.push(UNDERLINE_CODE);
id = this.intern(codes);
this.currentMatchCache.set(baseId, id);
}
return id;
}
selectionBgCode = null;
selectionBgCache = new Map;
setSelectionBg(bg) {
if (this.selectionBgCode?.code === bg?.code)
return;
this.selectionBgCode = bg;
this.selectionBgCache.clear();
}
withSelectionBg(baseId) {
const bg = this.selectionBgCode;
if (bg === null)
return this.withInverse(baseId);
let id = this.selectionBgCache.get(baseId);
if (id === undefined) {
const kept = this.get(baseId).filter((c6) => c6.endCode !== "\x1B[49m" && c6.endCode !== "\x1B[27m");
kept.push(bg);
id = this.intern(kept);
this.selectionBgCache.set(baseId, id);
}
return id;
}
}
function hasVisibleSpaceEffect(styles5) {
for (const style of styles5) {
if (VISIBLE_ON_SPACE.has(style.endCode))
return true;
}
return false;
}
function initCharAscii() {
const table = new Int32Array(128);
table.fill(-1);
table[32] = EMPTY_CHAR_INDEX;
return table;
}
function packWord1(styleId, hyperlinkId, width) {
return styleId << STYLE_SHIFT | hyperlinkId << HYPERLINK_SHIFT | width;
}
function isEmptyCellByIndex(screen, index) {
const ci = index << 1;
return screen.cells[ci] === 0 && screen.cells[ci | 1] === 0;
}
function isEmptyCellAt(screen, x2, y2) {
if (x2 < 0 || y2 < 0 || x2 >= screen.width || y2 >= screen.height)
return true;
return isEmptyCellByIndex(screen, y2 * screen.width + x2);
}
function internHyperlink(screen, hyperlink) {
return screen.hyperlinkPool.intern(hyperlink);
}
function createScreen(width, height, styles5, charPool, hyperlinkPool) {
ifNotInteger(width, "createScreen width");
ifNotInteger(height, "createScreen height");
if (!Number.isInteger(width) || width < 0) {
width = Math.max(0, Math.floor(width) || 0);
}
if (!Number.isInteger(height) || height < 0) {
height = Math.max(0, Math.floor(height) || 0);
}
const size = width * height;
const buf = new ArrayBuffer(size << 3);
const cells = new Int32Array(buf);
const cells64 = new BigInt64Array(buf);
return {
width,
height,
cells,
cells64,
charPool,
hyperlinkPool,
emptyStyleId: styles5.none,
damage: undefined,
noSelect: new Uint8Array(size),
softWrap: new Int32Array(height)
};
}
function resetScreen(screen, width, height) {
ifNotInteger(width, "resetScreen width");
ifNotInteger(height, "resetScreen height");
if (!Number.isInteger(width) || width < 0) {
width = Math.max(0, Math.floor(width) || 0);
}
if (!Number.isInteger(height) || height < 0) {
height = Math.max(0, Math.floor(height) || 0);
}
const size = width * height;
if (screen.cells64.length < size) {
const buf = new ArrayBuffer(size << 3);
screen.cells = new Int32Array(buf);
screen.cells64 = new BigInt64Array(buf);
screen.noSelect = new Uint8Array(size);
}
if (screen.softWrap.length < height) {
screen.softWrap = new Int32Array(height);
}
screen.cells64.fill(EMPTY_CELL_VALUE, 0, size);
screen.noSelect.fill(0, 0, size);
screen.softWrap.fill(0, 0, height);
screen.width = width;
screen.height = height;
screen.damage = undefined;
}
function migrateScreenPools(screen, charPool, hyperlinkPool) {
const oldCharPool = screen.charPool;
const oldHyperlinkPool = screen.hyperlinkPool;
if (oldCharPool === charPool && oldHyperlinkPool === hyperlinkPool)
return;
const size = screen.width * screen.height;
const cells = screen.cells;
for (let ci = 0;ci < size << 1; ci += 2) {
const oldCharId = cells[ci];
cells[ci] = charPool.intern(oldCharPool.get(oldCharId));
const word1 = cells[ci + 1];
const oldHyperlinkId = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
if (oldHyperlinkId !== 0) {
const oldStr = oldHyperlinkPool.get(oldHyperlinkId);
const newHyperlinkId = hyperlinkPool.intern(oldStr);
const styleId = word1 >>> STYLE_SHIFT;
const width = word1 & WIDTH_MASK;
cells[ci + 1] = packWord1(styleId, newHyperlinkId, width);
}
}
screen.charPool = charPool;
screen.hyperlinkPool = hyperlinkPool;
}
function cellAt(screen, x2, y2) {
if (x2 < 0 || y2 < 0 || x2 >= screen.width || y2 >= screen.height)
return;
return cellAtIndex(screen, y2 * screen.width + x2);
}
function cellAtIndex(screen, index) {
const ci = index << 1;
const word1 = screen.cells[ci + 1];
const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
return {
char: screen.charPool.get(screen.cells[ci]),
styleId: word1 >>> STYLE_SHIFT,
width: word1 & WIDTH_MASK,
hyperlink: hid === 0 ? undefined : screen.hyperlinkPool.get(hid)
};
}
function visibleCellAtIndex(cells, charPool, hyperlinkPool, index, lastRenderedStyleId) {
const ci = index << 1;
const charId = cells[ci];
if (charId === 1)
return;
const word1 = cells[ci + 1];
if (charId === 0 && (word1 & 262140) === 0) {
const fgStyle = word1 >>> STYLE_SHIFT;
if (fgStyle === 0 || fgStyle === lastRenderedStyleId)
return;
}
const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
return {
char: charPool.get(charId),
styleId: word1 >>> STYLE_SHIFT,
width: word1 & WIDTH_MASK,
hyperlink: hid === 0 ? undefined : hyperlinkPool.get(hid)
};
}
function cellAtCI(screen, ci, out) {
const w1 = ci | 1;
const word1 = screen.cells[w1];
out.char = screen.charPool.get(screen.cells[ci]);
out.styleId = word1 >>> STYLE_SHIFT;
out.width = word1 & WIDTH_MASK;
const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
out.hyperlink = hid === 0 ? undefined : screen.hyperlinkPool.get(hid);
}
function charInCellAt(screen, x2, y2) {
if (x2 < 0 || y2 < 0 || x2 >= screen.width || y2 >= screen.height)
return;
const ci = y2 * screen.width + x2 << 1;
return screen.charPool.get(screen.cells[ci]);
}
function setCellAt(screen, x2, y2, cell) {
if (x2 < 0 || y2 < 0 || x2 >= screen.width || y2 >= screen.height)
return;
const ci = y2 * screen.width + x2 << 1;
const cells = screen.cells;
const prevWidth = cells[ci + 1] & WIDTH_MASK;
if (prevWidth === 1 /* Wide */ && cell.width !== 1 /* Wide */) {
const spacerX = x2 + 1;
if (spacerX < screen.width) {
const spacerCI = ci + 2;
if ((cells[spacerCI + 1] & WIDTH_MASK) === 2 /* SpacerTail */) {
cells[spacerCI] = EMPTY_CHAR_INDEX;
cells[spacerCI + 1] = packWord1(screen.emptyStyleId, 0, 0 /* Narrow */);
}
}
}
let clearedWideX = -1;
if (prevWidth === 2 /* SpacerTail */ && cell.width !== 2 /* SpacerTail */) {
if (x2 > 0) {
const wideCI = ci - 2;
if ((cells[wideCI + 1] & WIDTH_MASK) === 1 /* Wide */) {
cells[wideCI] = EMPTY_CHAR_INDEX;
cells[wideCI + 1] = packWord1(screen.emptyStyleId, 0, 0 /* Narrow */);
clearedWideX = x2 - 1;
}
}
}
cells[ci] = internCharString(screen, cell.char);
cells[ci + 1] = packWord1(cell.styleId, internHyperlink(screen, cell.hyperlink), cell.width);
const minX = clearedWideX >= 0 ? Math.min(x2, clearedWideX) : x2;
const damage = screen.damage;
if (damage) {
const right = damage.x + damage.width;
const bottom = damage.y + damage.height;
if (minX < damage.x) {
damage.width += damage.x - minX;
damage.x = minX;
} else if (x2 >= right) {
damage.width = x2 - damage.x + 1;
}
if (y2 < damage.y) {
damage.height += damage.y - y2;
damage.y = y2;
} else if (y2 >= bottom) {
damage.height = y2 - damage.y + 1;
}
} else {
screen.damage = { x: minX, y: y2, width: x2 - minX + 1, height: 1 };
}
if (cell.width === 1 /* Wide */) {
const spacerX = x2 + 1;
if (spacerX < screen.width) {
const spacerCI = ci + 2;
if ((cells[spacerCI + 1] & WIDTH_MASK) === 1 /* Wide */) {
const orphanCI = spacerCI + 2;
if (spacerX + 1 < screen.width && (cells[orphanCI + 1] & WIDTH_MASK) === 2 /* SpacerTail */) {
cells[orphanCI] = EMPTY_CHAR_INDEX;
cells[orphanCI + 1] = packWord1(screen.emptyStyleId, 0, 0 /* Narrow */);
}
}
cells[spacerCI] = SPACER_CHAR_INDEX;
cells[spacerCI + 1] = packWord1(screen.emptyStyleId, 0, 2 /* SpacerTail */);
const d = screen.damage;
if (d && spacerX >= d.x + d.width) {
d.width = spacerX - d.x + 1;
}
}
}
}
function setCellStyleId(screen, x2, y2, styleId) {
if (x2 < 0 || y2 < 0 || x2 >= screen.width || y2 >= screen.height)
return;
const ci = y2 * screen.width + x2 << 1;
const cells = screen.cells;
const word1 = cells[ci + 1];
const width = word1 & WIDTH_MASK;
if (width === 2 /* SpacerTail */ || width === 3 /* SpacerHead */)
return;
const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
cells[ci + 1] = packWord1(styleId, hid, width);
const d = screen.damage;
if (d) {
screen.damage = unionRect(d, { x: x2, y: y2, width: 1, height: 1 });
} else {
screen.damage = { x: x2, y: y2, width: 1, height: 1 };
}
}
function internCharString(screen, char) {
return screen.charPool.intern(char);
}
function blitRegion(dst, src, regionX, regionY, maxX, maxY) {
regionX = Math.max(0, regionX);
regionY = Math.max(0, regionY);
if (regionX >= maxX || regionY >= maxY)
return;
const rowLen = maxX - regionX;
const srcStride = src.width << 1;
const dstStride = dst.width << 1;
const rowBytes = rowLen << 1;
const srcCells = src.cells;
const dstCells = dst.cells;
const srcNoSel = src.noSelect;
const dstNoSel = dst.noSelect;
dst.softWrap.set(src.softWrap.subarray(regionY, maxY), regionY);
if (regionX === 0 && maxX === src.width && src.width === dst.width) {
const srcStart = regionY * srcStride;
const totalBytes = (maxY - regionY) * srcStride;
dstCells.set(srcCells.subarray(srcStart, srcStart + totalBytes), srcStart);
const nsStart = regionY * src.width;
const nsLen = (maxY - regionY) * src.width;
dstNoSel.set(srcNoSel.subarray(nsStart, nsStart + nsLen), nsStart);
} else {
let srcRowCI = regionY * srcStride + (regionX << 1);
let dstRowCI = regionY * dstStride + (regionX << 1);
let srcRowNS = regionY * src.width + regionX;
let dstRowNS = regionY * dst.width + regionX;
for (let y2 = regionY;y2 < maxY; y2++) {
dstCells.set(srcCells.subarray(srcRowCI, srcRowCI + rowBytes), dstRowCI);
dstNoSel.set(srcNoSel.subarray(srcRowNS, srcRowNS + rowLen), dstRowNS);
srcRowCI += srcStride;
dstRowCI += dstStride;
srcRowNS += src.width;
dstRowNS += dst.width;
}
}
const regionRect = {
x: regionX,
y: regionY,
width: rowLen,
height: maxY - regionY
};
if (dst.damage) {
dst.damage = unionRect(dst.damage, regionRect);
} else {
dst.damage = regionRect;
}
if (maxX < dst.width) {
let srcLastCI = regionY * src.width + (maxX - 1) << 1;
let dstSpacerCI = regionY * dst.width + maxX << 1;
let wroteSpacerOutsideRegion = false;
for (let y2 = regionY;y2 < maxY; y2++) {
if ((srcCells[srcLastCI + 1] & WIDTH_MASK) === 1 /* Wide */) {
dstCells[dstSpacerCI] = SPACER_CHAR_INDEX;
dstCells[dstSpacerCI + 1] = packWord1(dst.emptyStyleId, 0, 2 /* SpacerTail */);
wroteSpacerOutsideRegion = true;
}
srcLastCI += srcStride;
dstSpacerCI += dstStride;
}
if (wroteSpacerOutsideRegion && dst.damage) {
const rightEdge = dst.damage.x + dst.damage.width;
if (rightEdge === maxX) {
dst.damage = { ...dst.damage, width: dst.damage.width + 1 };
}
}
}
}
function shiftRows(screen, top, bottom, n2) {
if (n2 === 0 || top < 0 || bottom >= screen.height || top > bottom)
return;
const w = screen.width;
const cells64 = screen.cells64;
const noSel = screen.noSelect;
const sw = screen.softWrap;
const absN = Math.abs(n2);
if (absN > bottom - top) {
cells64.fill(EMPTY_CELL_VALUE, top * w, (bottom + 1) * w);
noSel.fill(0, top * w, (bottom + 1) * w);
sw.fill(0, top, bottom + 1);
return;
}
if (n2 > 0) {
cells64.copyWithin(top * w, (top + n2) * w, (bottom + 1) * w);
noSel.copyWithin(top * w, (top + n2) * w, (bottom + 1) * w);
sw.copyWithin(top, top + n2, bottom + 1);
cells64.fill(EMPTY_CELL_VALUE, (bottom - n2 + 1) * w, (bottom + 1) * w);
noSel.fill(0, (bottom - n2 + 1) * w, (bottom + 1) * w);
sw.fill(0, bottom - n2 + 1, bottom + 1);
} else {
cells64.copyWithin((top - n2) * w, top * w, (bottom + n2 + 1) * w);
noSel.copyWithin((top - n2) * w, top * w, (bottom + n2 + 1) * w);
sw.copyWithin(top - n2, top, bottom + n2 + 1);
cells64.fill(EMPTY_CELL_VALUE, top * w, (top - n2) * w);
noSel.fill(0, top * w, (top - n2) * w);
sw.fill(0, top, top - n2);
}
}
function extractHyperlinkFromStyles(styles5) {
for (const style of styles5) {
const code = style.code;
if (code.length < 5 || !code.startsWith(OSC8_PREFIX))
continue;
const match = code.match(OSC8_REGEX);
if (match) {
return match[1] || null;
}
}
return null;
}
function filterOutHyperlinkStyles(styles5) {
return styles5.filter((style) => !style.code.startsWith(OSC8_PREFIX) || !OSC8_REGEX.test(style.code));
}
function diffEach(prev, next, cb) {
const prevWidth = prev.width;
const nextWidth = next.width;
const prevHeight = prev.height;
const nextHeight = next.height;
let region;
if (prevWidth === 0 && prevHeight === 0) {
region = { x: 0, y: 0, width: nextWidth, height: nextHeight };
} else if (next.damage) {
region = next.damage;
if (prev.damage) {
region = unionRect(region, prev.damage);
}
} else if (prev.damage) {
region = prev.damage;
} else {
region = { x: 0, y: 0, width: 0, height: 0 };
}
if (prevHeight > nextHeight) {
region = unionRect(region, {
x: 0,
y: nextHeight,
width: prevWidth,
height: prevHeight - nextHeight
});
}
if (prevWidth > nextWidth) {
region = unionRect(region, {
x: nextWidth,
y: 0,
width: prevWidth - nextWidth,
height: prevHeight
});
}
const maxHeight = Math.max(prevHeight, nextHeight);
const maxWidth = Math.max(prevWidth, nextWidth);
const endY = Math.min(region.y + region.height, maxHeight);
const endX = Math.min(region.x + region.width, maxWidth);
if (prevWidth === nextWidth) {
return diffSameWidth(prev, next, region.x, endX, region.y, endY, cb);
}
return diffDifferentWidth(prev, next, region.x, endX, region.y, endY, cb);
}
function findNextDiff(a2, b, w0, count3) {
for (let i2 = 0;i2 < count3; i2++, w0 += 2) {
const w1 = w0 | 1;
if (a2[w0] !== b[w0] || a2[w1] !== b[w1])
return i2;
}
return count3;
}
function diffRowBoth(prevCells, nextCells, prev, next, ci, y2, startX, endX, prevCell, nextCell, cb) {
let x2 = startX;
while (x2 < endX) {
const skip = findNextDiff(prevCells, nextCells, ci, endX - x2);
x2 += skip;
ci += skip << 1;
if (x2 >= endX)
break;
cellAtCI(prev, ci, prevCell);
cellAtCI(next, ci, nextCell);
if (cb(x2, y2, prevCell, nextCell))
return true;
x2++;
ci += 2;
}
return false;
}
function diffRowRemoved(prev, ci, y2, startX, endX, prevCell, cb) {
for (let x2 = startX;x2 < endX; x2++, ci += 2) {
cellAtCI(prev, ci, prevCell);
if (cb(x2, y2, prevCell, undefined))
return true;
}
return false;
}
function diffRowAdded(nextCells, next, ci, y2, startX, endX, nextCell, cb) {
for (let x2 = startX;x2 < endX; x2++, ci += 2) {
if (nextCells[ci] === 0 && nextCells[ci | 1] === 0)
continue;
cellAtCI(next, ci, nextCell);
if (cb(x2, y2, undefined, nextCell))
return true;
}
return false;
}
function diffSameWidth(prev, next, startX, endX, startY, endY, cb) {
const prevCells = prev.cells;
const nextCells = next.cells;
const width = prev.width;
const prevHeight = prev.height;
const nextHeight = next.height;
const stride = width << 1;
const prevCell = {
char: " ",
styleId: 0,
width: 0 /* Narrow */,
hyperlink: undefined
};
const nextCell = {
char: " ",
styleId: 0,
width: 0 /* Narrow */,
hyperlink: undefined
};
const rowEndX = Math.min(endX, width);
let rowCI = startY * width + startX << 1;
for (let y2 = startY;y2 < endY; y2++) {
const prevIn = y2 < prevHeight;
const nextIn = y2 < nextHeight;
if (prevIn && nextIn) {
if (diffRowBoth(prevCells, nextCells, prev, next, rowCI, y2, startX, rowEndX, prevCell, nextCell, cb))
return true;
} else if (prevIn) {
if (diffRowRemoved(prev, rowCI, y2, startX, rowEndX, prevCell, cb))
return true;
} else if (nextIn) {
if (diffRowAdded(nextCells, next, rowCI, y2, startX, rowEndX, nextCell, cb))
return true;
}
rowCI += stride;
}
return false;
}
function diffDifferentWidth(prev, next, startX, endX, startY, endY, cb) {
const prevWidth = prev.width;
const nextWidth = next.width;
const prevCells = prev.cells;
const nextCells = next.cells;
const prevCell = {
char: " ",
styleId: 0,
width: 0 /* Narrow */,
hyperlink: undefined
};
const nextCell = {
char: " ",
styleId: 0,
width: 0 /* Narrow */,
hyperlink: undefined
};
const prevStride = prevWidth << 1;
const nextStride = nextWidth << 1;
let prevRowCI = startY * prevWidth + startX << 1;
let nextRowCI = startY * nextWidth + startX << 1;
for (let y2 = startY;y2 < endY; y2++) {
const prevIn = y2 < prev.height;
const nextIn = y2 < next.height;
const prevEndX = prevIn ? Math.min(endX, prevWidth) : startX;
const nextEndX = nextIn ? Math.min(endX, nextWidth) : startX;
const bothEndX = Math.min(prevEndX, nextEndX);
let prevCI = prevRowCI;
let nextCI = nextRowCI;
for (let x2 = startX;x2 < bothEndX; x2++) {
if (prevCells[prevCI] === nextCells[nextCI] && prevCells[prevCI + 1] === nextCells[nextCI + 1]) {
prevCI += 2;
nextCI += 2;
continue;
}
cellAtCI(prev, prevCI, prevCell);
cellAtCI(next, nextCI, nextCell);
prevCI += 2;
nextCI += 2;
if (cb(x2, y2, prevCell, nextCell))
return true;
}
if (prevEndX > bothEndX) {
prevCI = prevRowCI + (bothEndX - startX << 1);
for (let x2 = bothEndX;x2 < prevEndX; x2++) {
cellAtCI(prev, prevCI, prevCell);
prevCI += 2;
if (cb(x2, y2, prevCell, undefined))
return true;
}
}
if (nextEndX > bothEndX) {
nextCI = nextRowCI + (bothEndX - startX << 1);
for (let x2 = bothEndX;x2 < nextEndX; x2++) {
if (nextCells[nextCI] === 0 && nextCells[nextCI | 1] === 0) {
nextCI += 2;
continue;
}
cellAtCI(next, nextCI, nextCell);
nextCI += 2;
if (cb(x2, y2, undefined, nextCell))
return true;
}
}
prevRowCI += prevStride;
nextRowCI += nextStride;
}
return false;
}
function markNoSelectRegion(screen, x2, y2, width, height) {
const maxX = Math.min(x2 + width, screen.width);
const maxY = Math.min(y2 + height, screen.height);
const noSel = screen.noSelect;
const stride = screen.width;
for (let row = Math.max(0, y2);row < maxY; row++) {
const rowStart = row * stride;
noSel.fill(1, rowStart + Math.max(0, x2), rowStart + maxX);
}
}
var INVERSE_CODE, BOLD_CODE, UNDERLINE_CODE, YELLOW_FG_CODE, VISIBLE_ON_SPACE, EMPTY_CHAR_INDEX = 0, SPACER_CHAR_INDEX = 1, STYLE_SHIFT = 17, HYPERLINK_SHIFT = 2, HYPERLINK_MASK = 32767, WIDTH_MASK = 3, EMPTY_CELL_VALUE = 0n, OSC8_REGEX, OSC8_PREFIX;
var init_screen = __esm(() => {
init_build();
init_geometry();
init_ansi();
init_warn();
INVERSE_CODE = {
type: "ansi",
code: "\x1B[7m",
endCode: "\x1B[27m"
};
BOLD_CODE = {
type: "ansi",
code: "\x1B[1m",
endCode: "\x1B[22m"
};
UNDERLINE_CODE = {
type: "ansi",
code: "\x1B[4m",
endCode: "\x1B[24m"
};
YELLOW_FG_CODE = {
type: "ansi",
code: "\x1B[33m",
endCode: "\x1B[39m"
};
VISIBLE_ON_SPACE = new Set([
"\x1B[49m",
"\x1B[27m",
"\x1B[24m",
"\x1B[29m",
"\x1B[55m"
]);
OSC8_REGEX = new RegExp(`^${ESC}\\]8${SEP}${SEP}([^${BEL}]*)${BEL}$`);
OSC8_PREFIX = `${ESC}]8${SEP}`;
});
// src/ink/selection.ts
function createSelectionState() {
return {
anchor: null,
focus: null,
isDragging: false,
anchorSpan: null,
scrolledOffAbove: [],
scrolledOffBelow: [],
scrolledOffAboveSW: [],
scrolledOffBelowSW: [],
lastPressHadAlt: false
};
}
function startSelection(s, col, row) {
s.anchor = { col, row };
s.focus = null;
s.isDragging = true;
s.anchorSpan = null;
s.scrolledOffAbove = [];
s.scrolledOffBelow = [];
s.scrolledOffAboveSW = [];
s.scrolledOffBelowSW = [];
s.virtualAnchorRow = undefined;
s.virtualFocusRow = undefined;
s.lastPressHadAlt = false;
}
function updateSelection(s, col, row) {
if (!s.isDragging)
return;
if (!s.focus && s.anchor && s.anchor.col === col && s.anchor.row === row)
return;
s.focus = { col, row };
}
function finishSelection(s) {
s.isDragging = false;
}
function clearSelection(s) {
s.anchor = null;
s.focus = null;
s.isDragging = false;
s.anchorSpan = null;
s.scrolledOffAbove = [];
s.scrolledOffBelow = [];
s.scrolledOffAboveSW = [];
s.scrolledOffBelowSW = [];
s.virtualAnchorRow = undefined;
s.virtualFocusRow = undefined;
s.lastPressHadAlt = false;
}
function charClass(c6) {
if (c6 === " " || c6 === "")
return 0;
if (WORD_CHAR.test(c6))
return 1;
return 2;
}
function wordBoundsAt(screen, col, row) {
if (row < 0 || row >= screen.height)
return null;
const width = screen.width;
const noSelect = screen.noSelect;
const rowOff = row * width;
let c6 = col;
if (c6 > 0) {
const cell = cellAt(screen, c6, row);
if (cell && cell.width === 2 /* SpacerTail */)
c6 -= 1;
}
if (c6 < 0 || c6 >= width || noSelect[rowOff + c6] === 1)
return null;
const startCell = cellAt(screen, c6, row);
if (!startCell)
return null;
const cls = charClass(startCell.char);
let lo = c6;
while (lo > 0) {
const prev = lo - 1;
if (noSelect[rowOff + prev] === 1)
break;
const pc = cellAt(screen, prev, row);
if (!pc)
break;
if (pc.width === 2 /* SpacerTail */) {
if (prev === 0 || noSelect[rowOff + prev - 1] === 1)
break;
const head = cellAt(screen, prev - 1, row);
if (!head || charClass(head.char) !== cls)
break;
lo = prev - 1;
continue;
}
if (charClass(pc.char) !== cls)
break;
lo = prev;
}
let hi = c6;
while (hi < width - 1) {
const next = hi + 1;
if (noSelect[rowOff + next] === 1)
break;
const nc = cellAt(screen, next, row);
if (!nc)
break;
if (nc.width === 2 /* SpacerTail */) {
hi = next;
continue;
}
if (charClass(nc.char) !== cls)
break;
hi = next;
}
return { lo, hi };
}
function comparePoints(a2, b) {
if (a2.row !== b.row)
return a2.row < b.row ? -1 : 1;
if (a2.col !== b.col)
return a2.col < b.col ? -1 : 1;
return 0;
}
function selectWordAt(s, screen, col, row) {
const b = wordBoundsAt(screen, col, row);
if (!b)
return;
const lo = { col: b.lo, row };
const hi = { col: b.hi, row };
s.anchor = lo;
s.focus = hi;
s.isDragging = true;
s.anchorSpan = { lo, hi, kind: "word" };
}
function isUrlChar(c6) {
if (c6.length !== 1)
return false;
const code = c6.charCodeAt(0);
return code >= 33 && code <= 126 && !URL_BOUNDARY.has(c6);
}
function findPlainTextUrlAt(screen, col, row) {
if (row < 0 || row >= screen.height)
return;
const width = screen.width;
const noSelect = screen.noSelect;
const rowOff = row * width;
let c6 = col;
if (c6 > 0) {
const cell = cellAt(screen, c6, row);
if (cell && cell.width === 2 /* SpacerTail */)
c6 -= 1;
}
if (c6 < 0 || c6 >= width || noSelect[rowOff + c6] === 1)
return;
const startCell = cellAt(screen, c6, row);
if (!startCell || !isUrlChar(startCell.char))
return;
let lo = c6;
while (lo > 0) {
const prev = lo - 1;
if (noSelect[rowOff + prev] === 1)
break;
const pc = cellAt(screen, prev, row);
if (!pc || pc.width !== 0 /* Narrow */ || !isUrlChar(pc.char))
break;
lo = prev;
}
let hi = c6;
while (hi < width - 1) {
const next = hi + 1;
if (noSelect[rowOff + next] === 1)
break;
const nc = cellAt(screen, next, row);
if (!nc || nc.width !== 0 /* Narrow */ || !isUrlChar(nc.char))
break;
hi = next;
}
let token = "";
for (let i2 = lo;i2 <= hi; i2++)
token += cellAt(screen, i2, row).char;
const clickIdx = c6 - lo;
const schemeRe = /(?:https?|file):\/\//g;
let urlStart = -1;
let urlEnd = token.length;
for (let m;m = schemeRe.exec(token); ) {
if (m.index > clickIdx) {
urlEnd = m.index;
break;
}
urlStart = m.index;
}
if (urlStart < 0)
return;
let url3 = token.slice(urlStart, urlEnd);
const OPENER = { ")": "(", "]": "[", "}": "{" };
while (url3.length > 0) {
const last = url3.at(-1);
if (".,;:!?".includes(last)) {
url3 = url3.slice(0, -1);
continue;
}
const opener = OPENER[last];
if (!opener)
break;
let opens = 0;
let closes = 0;
for (let i2 = 0;i2 < url3.length; i2++) {
const ch = url3.charAt(i2);
if (ch === opener)
opens++;
else if (ch === last)
closes++;
}
if (closes > opens)
url3 = url3.slice(0, -1);
else
break;
}
if (clickIdx >= urlStart + url3.length)
return;
return url3;
}
function selectLineAt(s, screen, row) {
if (row < 0 || row >= screen.height)
return;
const lo = { col: 0, row };
const hi = { col: screen.width - 1, row };
s.anchor = lo;
s.focus = hi;
s.isDragging = true;
s.anchorSpan = { lo, hi, kind: "line" };
}
function extendSelection(s, screen, col, row) {
if (!s.isDragging || !s.anchorSpan)
return;
const span = s.anchorSpan;
let mLo;
let mHi;
if (span.kind === "word") {
const b = wordBoundsAt(screen, col, row);
mLo = { col: b ? b.lo : col, row };
mHi = { col: b ? b.hi : col, row };
} else {
const r = clamp(row, 0, screen.height - 1);
mLo = { col: 0, row: r };
mHi = { col: screen.width - 1, row: r };
}
if (comparePoints(mHi, span.lo) < 0) {
s.anchor = span.hi;
s.focus = mLo;
} else if (comparePoints(mLo, span.hi) > 0) {
s.anchor = span.lo;
s.focus = mHi;
} else {
s.anchor = span.lo;
s.focus = span.hi;
}
}
function moveFocus(s, col, row) {
if (!s.focus)
return;
s.anchorSpan = null;
s.focus = { col, row };
s.virtualFocusRow = undefined;
}
function shiftSelection(s, dRow, minRow, maxRow, width) {
if (!s.anchor || !s.focus)
return;
const vAnchor = (s.virtualAnchorRow ?? s.anchor.row) + dRow;
const vFocus = (s.virtualFocusRow ?? s.focus.row) + dRow;
if (vAnchor < minRow && vFocus < minRow || vAnchor > maxRow && vFocus > maxRow) {
clearSelection(s);
return;
}
const oldMin = Math.min(s.virtualAnchorRow ?? s.anchor.row, s.virtualFocusRow ?? s.focus.row);
const oldMax = Math.max(s.virtualAnchorRow ?? s.anchor.row, s.virtualFocusRow ?? s.focus.row);
const oldAboveDebt = Math.max(0, minRow - oldMin);
const oldBelowDebt = Math.max(0, oldMax - maxRow);
const newAboveDebt = Math.max(0, minRow - Math.min(vAnchor, vFocus));
const newBelowDebt = Math.max(0, Math.max(vAnchor, vFocus) - maxRow);
if (newAboveDebt < oldAboveDebt) {
const drop = oldAboveDebt - newAboveDebt;
s.scrolledOffAbove.length -= drop;
s.scrolledOffAboveSW.length = s.scrolledOffAbove.length;
}
if (newBelowDebt < oldBelowDebt) {
const drop = oldBelowDebt - newBelowDebt;
s.scrolledOffBelow.splice(0, drop);
s.scrolledOffBelowSW.splice(0, drop);
}
if (s.scrolledOffAbove.length > newAboveDebt) {
s.scrolledOffAbove = newAboveDebt > 0 ? s.scrolledOffAbove.slice(-newAboveDebt) : [];
s.scrolledOffAboveSW = newAboveDebt > 0 ? s.scrolledOffAboveSW.slice(-newAboveDebt) : [];
}
if (s.scrolledOffBelow.length > newBelowDebt) {
s.scrolledOffBelow = s.scrolledOffBelow.slice(0, newBelowDebt);
s.scrolledOffBelowSW = s.scrolledOffBelowSW.slice(0, newBelowDebt);
}
const shift = (p, vRow) => {
if (vRow < minRow)
return { col: 0, row: minRow };
if (vRow > maxRow)
return { col: width - 1, row: maxRow };
return { col: p.col, row: vRow };
};
s.anchor = shift(s.anchor, vAnchor);
s.focus = shift(s.focus, vFocus);
s.virtualAnchorRow = vAnchor < minRow || vAnchor > maxRow ? vAnchor : undefined;
s.virtualFocusRow = vFocus < minRow || vFocus > maxRow ? vFocus : undefined;
if (s.anchorSpan) {
const sp = (p) => {
const r = p.row + dRow;
if (r < minRow)
return { col: 0, row: minRow };
if (r > maxRow)
return { col: width - 1, row: maxRow };
return { col: p.col, row: r };
};
s.anchorSpan = {
lo: sp(s.anchorSpan.lo),
hi: sp(s.anchorSpan.hi),
kind: s.anchorSpan.kind
};
}
}
function shiftAnchor(s, dRow, minRow, maxRow) {
if (!s.anchor)
return;
const raw = (s.virtualAnchorRow ?? s.anchor.row) + dRow;
s.anchor = { col: s.anchor.col, row: clamp(raw, minRow, maxRow) };
s.virtualAnchorRow = raw < minRow || raw > maxRow ? raw : undefined;
if (s.anchorSpan) {
const shift = (p) => ({
col: p.col,
row: clamp(p.row + dRow, minRow, maxRow)
});
s.anchorSpan = {
lo: shift(s.anchorSpan.lo),
hi: shift(s.anchorSpan.hi),
kind: s.anchorSpan.kind
};
}
}
function shiftSelectionForFollow(s, dRow, minRow, maxRow) {
if (!s.anchor)
return false;
const rawAnchor = (s.virtualAnchorRow ?? s.anchor.row) + dRow;
const rawFocus = s.focus ? (s.virtualFocusRow ?? s.focus.row) + dRow : undefined;
if (rawAnchor < minRow && rawFocus !== undefined && rawFocus < minRow) {
clearSelection(s);
return true;
}
s.anchor = { col: s.anchor.col, row: clamp(rawAnchor, minRow, maxRow) };
if (s.focus && rawFocus !== undefined) {
s.focus = { col: s.focus.col, row: clamp(rawFocus, minRow, maxRow) };
}
s.virtualAnchorRow = rawAnchor < minRow || rawAnchor > maxRow ? rawAnchor : undefined;
s.virtualFocusRow = rawFocus !== undefined && (rawFocus < minRow || rawFocus > maxRow) ? rawFocus : undefined;
if (s.anchorSpan) {
const shift = (p) => ({
col: p.col,
row: clamp(p.row + dRow, minRow, maxRow)
});
s.anchorSpan = {
lo: shift(s.anchorSpan.lo),
hi: shift(s.anchorSpan.hi),
kind: s.anchorSpan.kind
};
}
return false;
}
function hasSelection(s) {
return s.anchor !== null && s.focus !== null;
}
function selectionBounds(s) {
if (!s.anchor || !s.focus)
return null;
return comparePoints(s.anchor, s.focus) <= 0 ? { start: s.anchor, end: s.focus } : { start: s.focus, end: s.anchor };
}
function extractRowText(screen, row, colStart, colEnd) {
const noSelect = screen.noSelect;
const rowOff = row * screen.width;
const contentEnd = row + 1 < screen.height ? screen.softWrap[row + 1] : 0;
const lastCol = contentEnd > 0 ? Math.min(colEnd, contentEnd - 1) : colEnd;
let line = "";
for (let col = colStart;col <= lastCol; col++) {
if (noSelect[rowOff + col] === 1)
continue;
const cell = cellAt(screen, col, row);
if (!cell)
continue;
if (cell.width === 2 /* SpacerTail */ || cell.width === 3 /* SpacerHead */) {
continue;
}
line += cell.char;
}
return contentEnd > 0 ? line : line.replace(/\s+$/, "");
}
function joinRows(lines, text, sw) {
if (sw && lines.length > 0) {
lines[lines.length - 1] += text;
} else {
lines.push(text);
}
}
function getSelectedText(s, screen) {
const b = selectionBounds(s);
if (!b)
return "";
const { start, end } = b;
const sw = screen.softWrap;
const lines = [];
for (let i2 = 0;i2 < s.scrolledOffAbove.length; i2++) {
joinRows(lines, s.scrolledOffAbove[i2], s.scrolledOffAboveSW[i2]);
}
for (let row = start.row;row <= end.row; row++) {
const rowStart = row === start.row ? start.col : 0;
const rowEnd = row === end.row ? end.col : screen.width - 1;
joinRows(lines, extractRowText(screen, row, rowStart, rowEnd), sw[row] > 0);
}
for (let i2 = 0;i2 < s.scrolledOffBelow.length; i2++) {
joinRows(lines, s.scrolledOffBelow[i2], s.scrolledOffBelowSW[i2]);
}
return lines.join(`
`);
}
function captureScrolledRows(s, screen, firstRow, lastRow, side) {
const b = selectionBounds(s);
if (!b || firstRow > lastRow)
return;
const { start, end } = b;
const lo = Math.max(firstRow, start.row);
const hi = Math.min(lastRow, end.row);
if (lo > hi)
return;
const width = screen.width;
const sw = screen.softWrap;
const captured = [];
const capturedSW = [];
for (let row = lo;row <= hi; row++) {
const colStart = row === start.row ? start.col : 0;
const colEnd = row === end.row ? end.col : width - 1;
captured.push(extractRowText(screen, row, colStart, colEnd));
capturedSW.push(sw[row] > 0);
}
if (side === "above") {
s.scrolledOffAbove.push(...captured);
s.scrolledOffAboveSW.push(...capturedSW);
if (s.anchor && s.anchor.row === start.row && lo === start.row) {
s.anchor = { col: 0, row: s.anchor.row };
if (s.anchorSpan) {
s.anchorSpan = {
kind: s.anchorSpan.kind,
lo: { col: 0, row: s.anchorSpan.lo.row },
hi: { col: width - 1, row: s.anchorSpan.hi.row }
};
}
}
} else {
s.scrolledOffBelow.unshift(...captured);
s.scrolledOffBelowSW.unshift(...capturedSW);
if (s.anchor && s.anchor.row === end.row && hi === end.row) {
s.anchor = { col: width - 1, row: s.anchor.row };
if (s.anchorSpan) {
s.anchorSpan = {
kind: s.anchorSpan.kind,
lo: { col: 0, row: s.anchorSpan.lo.row },
hi: { col: width - 1, row: s.anchorSpan.hi.row }
};
}
}
}
}
function applySelectionOverlay(screen, selection, stylePool) {
const b = selectionBounds(selection);
if (!b)
return;
const { start, end } = b;
const width = screen.width;
const noSelect = screen.noSelect;
for (let row = start.row;row <= end.row && row < screen.height; row++) {
const colStart = row === start.row ? start.col : 0;
const colEnd = row === end.row ? Math.min(end.col, width - 1) : width - 1;
const rowOff = row * width;
for (let col = colStart;col <= colEnd; col++) {
const idx = rowOff + col;
if (noSelect[idx] === 1)
continue;
const cell = cellAtIndex(screen, idx);
setCellStyleId(screen, col, row, stylePool.withSelectionBg(cell.styleId));
}
}
}
var WORD_CHAR, URL_BOUNDARY;
var init_selection = __esm(() => {
init_geometry();
init_screen();
WORD_CHAR = /[\p{L}\p{N}_/.\-+~\\]/u;
URL_BOUNDARY = new Set([..."<>\"'` "]);
});
// node_modules/semver/internal/constants.js
var require_constants8 = __commonJS((exports, module) => {
var SEMVER_SPEC_VERSION = "2.0.0";
var MAX_LENGTH = 256;
var MAX_SAFE_INTEGER3 = Number.MAX_SAFE_INTEGER || 9007199254740991;
var MAX_SAFE_COMPONENT_LENGTH = 16;
var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
var RELEASE_TYPES = [
"major",
"premajor",
"minor",
"preminor",
"patch",
"prepatch",
"prerelease"
];
module.exports = {
MAX_LENGTH,
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_SAFE_INTEGER: MAX_SAFE_INTEGER3,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 1,
FLAG_LOOSE: 2
};
});
// node_modules/semver/internal/debug.js
var require_debug2 = __commonJS((exports, module) => {
var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {};
module.exports = debug;
});
// node_modules/semver/internal/re.js
var require_re = __commonJS((exports, module) => {
var {
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_LENGTH
} = require_constants8();
var debug = require_debug2();
exports = module.exports = {};
var re = exports.re = [];
var safeRe = exports.safeRe = [];
var src = exports.src = [];
var safeSrc = exports.safeSrc = [];
var t = exports.t = {};
var R2 = 0;
var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
var safeRegexReplacements = [
["\\s", 1],
["\\d", MAX_LENGTH],
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
];
var makeSafeRegex = (value) => {
for (const [token, max] of safeRegexReplacements) {
value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
}
return value;
};
var createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value);
const index = R2++;
debug(name, index, value);
t[name] = index;
src[index] = value;
safeSrc[index] = safe;
re[index] = new RegExp(value, isGlobal ? "g" : undefined);
safeRe[index] = new RegExp(safe, isGlobal ? "g" : undefined);
};
createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);
createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
createToken("FULL", `^${src[t.FULLPLAIN]}$`);
createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
createToken("GTLT", "((?:<|>)?=?)");
createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
createToken("COERCEPLAIN", `${"(^|[^\\d])" + "(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`);
createToken("COERCERTL", src[t.COERCE], true);
createToken("COERCERTLFULL", src[t.COERCEFULL], true);
createToken("LONETILDE", "(?:~>?)");
createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
exports.tildeTrimReplace = "$1~";
createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
createToken("LONECARET", "(?:\\^)");
createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
exports.caretTrimReplace = "$1^";
createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
exports.comparatorTrimReplace = "$1$2$3";
createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`);
createToken("STAR", "(<|>)?=?\\s*\\*");
createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
});
// node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS((exports, module) => {
var looseOption = Object.freeze({ loose: true });
var emptyOpts = Object.freeze({});
var parseOptions = (options) => {
if (!options) {
return emptyOpts;
}
if (typeof options !== "object") {
return looseOption;
}
return options;
};
module.exports = parseOptions;
});
// node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS((exports, module) => {
var numeric = /^[0-9]+$/;
var compareIdentifiers = (a2, b) => {
if (typeof a2 === "number" && typeof b === "number") {
return a2 === b ? 0 : a2 < b ? -1 : 1;
}
const anum = numeric.test(a2);
const bnum = numeric.test(b);
if (anum && bnum) {
a2 = +a2;
b = +b;
}
return a2 === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a2 < b ? -1 : 1;
};
var rcompareIdentifiers = (a2, b) => compareIdentifiers(b, a2);
module.exports = {
compareIdentifiers,
rcompareIdentifiers
};
});
// node_modules/semver/classes/semver.js
var require_semver = __commonJS((exports, module) => {
var debug = require_debug2();
var { MAX_LENGTH, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER3 } = require_constants8();
var { safeRe: re, t } = require_re();
var parseOptions = require_parse_options();
var { compareIdentifiers } = require_identifiers();
class SemVer {
constructor(version2, options) {
options = parseOptions(options);
if (version2 instanceof SemVer) {
if (version2.loose === !!options.loose && version2.includePrerelease === !!options.includePrerelease) {
return version2;
} else {
version2 = version2.version;
}
} else if (typeof version2 !== "string") {
throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`);
}
if (version2.length > MAX_LENGTH) {
throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
}
debug("SemVer", version2, options);
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
const m = version2.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
if (!m) {
throw new TypeError(`Invalid Version: ${version2}`);
}
this.raw = version2;
this.major = +m[1];
this.minor = +m[2];
this.patch = +m[3];
if (this.major > MAX_SAFE_INTEGER3 || this.major < 0) {
throw new TypeError("Invalid major version");
}
if (this.minor > MAX_SAFE_INTEGER3 || this.minor < 0) {
throw new TypeError("Invalid minor version");
}
if (this.patch > MAX_SAFE_INTEGER3 || this.patch < 0) {
throw new TypeError("Invalid patch version");
}
if (!m[4]) {
this.prerelease = [];
} else {
this.prerelease = m[4].split(".").map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id;
if (num >= 0 && num < MAX_SAFE_INTEGER3) {
return num;
}
}
return id;
});
}
this.build = m[5] ? m[5].split(".") : [];
this.format();
}
format() {
this.version = `${this.major}.${this.minor}.${this.patch}`;
if (this.prerelease.length) {
this.version += `-${this.prerelease.join(".")}`;
}
return this.version;
}
toString() {
return this.version;
}
compare(other) {
debug("SemVer.compare", this.version, this.options, other);
if (!(other instanceof SemVer)) {
if (typeof other === "string" && other === this.version) {
return 0;
}
other = new SemVer(other, this.options);
}
if (other.version === this.version) {
return 0;
}
return this.compareMain(other) || this.comparePre(other);
}
compareMain(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
if (this.major < other.major) {
return -1;
}
if (this.major > other.major) {
return 1;
}
if (this.minor < other.minor) {
return -1;
}
if (this.minor > other.minor) {
return 1;
}
if (this.patch < other.patch) {
return -1;
}
if (this.patch > other.patch) {
return 1;
}
return 0;
}
comparePre(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
if (this.prerelease.length && !other.prerelease.length) {
return -1;
} else if (!this.prerelease.length && other.prerelease.length) {
return 1;
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0;
}
let i2 = 0;
do {
const a2 = this.prerelease[i2];
const b = other.prerelease[i2];
debug("prerelease compare", i2, a2, b);
if (a2 === undefined && b === undefined) {
return 0;
} else if (b === undefined) {
return 1;
} else if (a2 === undefined) {
return -1;
} else if (a2 === b) {
continue;
} else {
return compareIdentifiers(a2, b);
}
} while (++i2);
}
compareBuild(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
let i2 = 0;
do {
const a2 = this.build[i2];
const b = other.build[i2];
debug("build compare", i2, a2, b);
if (a2 === undefined && b === undefined) {
return 0;
} else if (b === undefined) {
return 1;
} else if (a2 === undefined) {
return -1;
} else if (a2 === b) {
continue;
} else {
return compareIdentifiers(a2, b);
}
} while (++i2);
}
inc(release, identifier, identifierBase) {
if (release.startsWith("pre")) {
if (!identifier && identifierBase === false) {
throw new Error("invalid increment argument: identifier is empty");
}
if (identifier) {
const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
if (!match || match[1] !== identifier) {
throw new Error(`invalid identifier: ${identifier}`);
}
}
}
switch (release) {
case "premajor":
this.prerelease.length = 0;
this.patch = 0;
this.minor = 0;
this.major++;
this.inc("pre", identifier, identifierBase);
break;
case "preminor":
this.prerelease.length = 0;
this.patch = 0;
this.minor++;
this.inc("pre", identifier, identifierBase);
break;
case "prepatch":
this.prerelease.length = 0;
this.inc("patch", identifier, identifierBase);
this.inc("pre", identifier, identifierBase);
break;
case "prerelease":
if (this.prerelease.length === 0) {
this.inc("patch", identifier, identifierBase);
}
this.inc("pre", identifier, identifierBase);
break;
case "release":
if (this.prerelease.length === 0) {
throw new Error(`version ${this.raw} is not a prerelease`);
}
this.prerelease.length = 0;
break;
case "major":
if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
this.major++;
}
this.minor = 0;
this.patch = 0;
this.prerelease = [];
break;
case "minor":
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++;
}
this.patch = 0;
this.prerelease = [];
break;
case "patch":
if (this.prerelease.length === 0) {
this.patch++;
}
this.prerelease = [];
break;
case "pre": {
const base2 = Number(identifierBase) ? 1 : 0;
if (this.prerelease.length === 0) {
this.prerelease = [base2];
} else {
let i2 = this.prerelease.length;
while (--i2 >= 0) {
if (typeof this.prerelease[i2] === "number") {
this.prerelease[i2]++;
i2 = -2;
}
}
if (i2 === -1) {
if (identifier === this.prerelease.join(".") && identifierBase === false) {
throw new Error("invalid increment argument: identifier already exists");
}
this.prerelease.push(base2);
}
}
if (identifier) {
let prerelease = [identifier, base2];
if (identifierBase === false) {
prerelease = [identifier];
}
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = prerelease;
}
} else {
this.prerelease = prerelease;
}
}
break;
}
default:
throw new Error(`invalid increment argument: ${release}`);
}
this.raw = this.format();
if (this.build.length) {
this.raw += `+${this.build.join(".")}`;
}
return this;
}
}
module.exports = SemVer;
});
// node_modules/semver/functions/parse.js
var require_parse3 = __commonJS((exports, module) => {
var SemVer = require_semver();
var parse7 = (version2, options, throwErrors = false) => {
if (version2 instanceof SemVer) {
return version2;
}
try {
return new SemVer(version2, options);
} catch (er) {
if (!throwErrors) {
return null;
}
throw er;
}
};
module.exports = parse7;
});
// node_modules/semver/functions/valid.js
var require_valid = __commonJS((exports, module) => {
var parse7 = require_parse3();
var valid = (version2, options) => {
const v = parse7(version2, options);
return v ? v.version : null;
};
module.exports = valid;
});
// node_modules/semver/functions/clean.js
var require_clean = __commonJS((exports, module) => {
var parse7 = require_parse3();
var clean = (version2, options) => {
const s = parse7(version2.trim().replace(/^[=v]+/, ""), options);
return s ? s.version : null;
};
module.exports = clean;
});
// node_modules/semver/functions/inc.js
var require_inc = __commonJS((exports, module) => {
var SemVer = require_semver();
var inc = (version2, release, options, identifier, identifierBase) => {
if (typeof options === "string") {
identifierBase = identifier;
identifier = options;
options = undefined;
}
try {
return new SemVer(version2 instanceof SemVer ? version2.version : version2, options).inc(release, identifier, identifierBase).version;
} catch (er) {
return null;
}
};
module.exports = inc;
});
// node_modules/semver/functions/diff.js
var require_diff = __commonJS((exports, module) => {
var parse7 = require_parse3();
var diff2 = (version1, version2) => {
const v1 = parse7(version1, null, true);
const v2 = parse7(version2, null, true);
const comparison = v1.compare(v2);
if (comparison === 0) {
return null;
}
const v1Higher = comparison > 0;
const highVersion = v1Higher ? v1 : v2;
const lowVersion = v1Higher ? v2 : v1;
const highHasPre = !!highVersion.prerelease.length;
const lowHasPre = !!lowVersion.prerelease.length;
if (lowHasPre && !highHasPre) {
if (!lowVersion.patch && !lowVersion.minor) {
return "major";
}
if (lowVersion.compareMain(highVersion) === 0) {
if (lowVersion.minor && !lowVersion.patch) {
return "minor";
}
return "patch";
}
}
const prefix = highHasPre ? "pre" : "";
if (v1.major !== v2.major) {
return prefix + "major";
}
if (v1.minor !== v2.minor) {
return prefix + "minor";
}
if (v1.patch !== v2.patch) {
return prefix + "patch";
}
return "prerelease";
};
module.exports = diff2;
});
// node_modules/semver/functions/major.js
var require_major = __commonJS((exports, module) => {
var SemVer = require_semver();
var major = (a2, loose) => new SemVer(a2, loose).major;
module.exports = major;
});
// node_modules/semver/functions/minor.js
var require_minor = __commonJS((exports, module) => {
var SemVer = require_semver();
var minor = (a2, loose) => new SemVer(a2, loose).minor;
module.exports = minor;
});
// node_modules/semver/functions/patch.js
var require_patch = __commonJS((exports, module) => {
var SemVer = require_semver();
var patch = (a2, loose) => new SemVer(a2, loose).patch;
module.exports = patch;
});
// node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS((exports, module) => {
var parse7 = require_parse3();
var prerelease = (version2, options) => {
const parsed = parse7(version2, options);
return parsed && parsed.prerelease.length ? parsed.prerelease : null;
};
module.exports = prerelease;
});
// node_modules/semver/functions/compare.js
var require_compare = __commonJS((exports, module) => {
var SemVer = require_semver();
var compare = (a2, b, loose) => new SemVer(a2, loose).compare(new SemVer(b, loose));
module.exports = compare;
});
// node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS((exports, module) => {
var compare = require_compare();
var rcompare = (a2, b, loose) => compare(b, a2, loose);
module.exports = rcompare;
});
// node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS((exports, module) => {
var compare = require_compare();
var compareLoose = (a2, b) => compare(a2, b, true);
module.exports = compareLoose;
});
// node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS((exports, module) => {
var SemVer = require_semver();
var compareBuild = (a2, b, loose) => {
const versionA = new SemVer(a2, loose);
const versionB = new SemVer(b, loose);
return versionA.compare(versionB) || versionA.compareBuild(versionB);
};
module.exports = compareBuild;
});
// node_modules/semver/functions/sort.js
var require_sort = __commonJS((exports, module) => {
var compareBuild = require_compare_build();
var sort = (list, loose) => list.sort((a2, b) => compareBuild(a2, b, loose));
module.exports = sort;
});
// node_modules/semver/functions/rsort.js
var require_rsort = __commonJS((exports, module) => {
var compareBuild = require_compare_build();
var rsort = (list, loose) => list.sort((a2, b) => compareBuild(b, a2, loose));
module.exports = rsort;
});
// node_modules/semver/functions/gt.js
var require_gt = __commonJS((exports, module) => {
var compare = require_compare();
var gt = (a2, b, loose) => compare(a2, b, loose) > 0;
module.exports = gt;
});
// node_modules/semver/functions/lt.js
var require_lt = __commonJS((exports, module) => {
var compare = require_compare();
var lt = (a2, b, loose) => compare(a2, b, loose) < 0;
module.exports = lt;
});
// node_modules/semver/functions/eq.js
var require_eq = __commonJS((exports, module) => {
var compare = require_compare();
var eq2 = (a2, b, loose) => compare(a2, b, loose) === 0;
module.exports = eq2;
});
// node_modules/semver/functions/neq.js
var require_neq = __commonJS((exports, module) => {
var compare = require_compare();
var neq = (a2, b, loose) => compare(a2, b, loose) !== 0;
module.exports = neq;
});
// node_modules/semver/functions/gte.js
var require_gte = __commonJS((exports, module) => {
var compare = require_compare();
var gte = (a2, b, loose) => compare(a2, b, loose) >= 0;
module.exports = gte;
});
// node_modules/semver/functions/lte.js
var require_lte = __commonJS((exports, module) => {
var compare = require_compare();
var lte = (a2, b, loose) => compare(a2, b, loose) <= 0;
module.exports = lte;
});
// node_modules/semver/functions/cmp.js
var require_cmp = __commonJS((exports, module) => {
var eq2 = require_eq();
var neq = require_neq();
var gt = require_gt();
var gte = require_gte();
var lt = require_lt();
var lte = require_lte();
var cmp = (a2, op, b, loose) => {
switch (op) {
case "===":
if (typeof a2 === "object") {
a2 = a2.version;
}
if (typeof b === "object") {
b = b.version;
}
return a2 === b;
case "!==":
if (typeof a2 === "object") {
a2 = a2.version;
}
if (typeof b === "object") {
b = b.version;
}
return a2 !== b;
case "":
case "=":
case "==":
return eq2(a2, b, loose);
case "!=":
return neq(a2, b, loose);
case ">":
return gt(a2, b, loose);
case ">=":
return gte(a2, b, loose);
case "<":
return lt(a2, b, loose);
case "<=":
return lte(a2, b, loose);
default:
throw new TypeError(`Invalid operator: ${op}`);
}
};
module.exports = cmp;
});
// node_modules/semver/functions/coerce.js
var require_coerce = __commonJS((exports, module) => {
var SemVer = require_semver();
var parse7 = require_parse3();
var { safeRe: re, t } = require_re();
var coerce = (version2, options) => {
if (version2 instanceof SemVer) {
return version2;
}
if (typeof version2 === "number") {
version2 = String(version2);
}
if (typeof version2 !== "string") {
return null;
}
options = options || {};
let match = null;
if (!options.rtl) {
match = version2.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
} else {
const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
let next;
while ((next = coerceRtlRegex.exec(version2)) && (!match || match.index + match[0].length !== version2.length)) {
if (!match || next.index + next[0].length !== match.index + match[0].length) {
match = next;
}
coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
}
coerceRtlRegex.lastIndex = -1;
}
if (match === null) {
return null;
}
const major = match[2];
const minor = match[3] || "0";
const patch = match[4] || "0";
const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
return parse7(`${major}.${minor}.${patch}${prerelease}${build}`, options);
};
module.exports = coerce;
});
// node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS((exports, module) => {
class LRUCache {
constructor() {
this.max = 1000;
this.map = new Map;
}
get(key) {
const value = this.map.get(key);
if (value === undefined) {
return;
} else {
this.map.delete(key);
this.map.set(key, value);
return value;
}
}
delete(key) {
return this.map.delete(key);
}
set(key, value) {
const deleted = this.delete(key);
if (!deleted && value !== undefined) {
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value;
this.delete(firstKey);
}
this.map.set(key, value);
}
return this;
}
}
module.exports = LRUCache;
});
// node_modules/semver/classes/range.js
var require_range2 = __commonJS((exports, module) => {
var SPACE_CHARACTERS = /\s+/g;
class Range {
constructor(range, options) {
options = parseOptions(options);
if (range instanceof Range) {
if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
return range;
} else {
return new Range(range.raw, options);
}
}
if (range instanceof Comparator) {
this.raw = range.value;
this.set = [[range]];
this.formatted = undefined;
return this;
}
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c6) => c6.length);
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
}
if (this.set.length > 1) {
const first = this.set[0];
this.set = this.set.filter((c6) => !isNullSet(c6[0]));
if (this.set.length === 0) {
this.set = [first];
} else if (this.set.length > 1) {
for (const c6 of this.set) {
if (c6.length === 1 && isAny(c6[0])) {
this.set = [c6];
break;
}
}
}
}
this.formatted = undefined;
}
get range() {
if (this.formatted === undefined) {
this.formatted = "";
for (let i2 = 0;i2 < this.set.length; i2++) {
if (i2 > 0) {
this.formatted += "||";
}
const comps = this.set[i2];
for (let k = 0;k < comps.length; k++) {
if (k > 0) {
this.formatted += " ";
}
this.formatted += comps[k].toString().trim();
}
}
}
return this.formatted;
}
format() {
return this.range;
}
toString() {
return this.range;
}
parseRange(range) {
const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
const memoKey = memoOpts + ":" + range;
const cached2 = cache3.get(memoKey);
if (cached2) {
return cached2;
}
const loose = this.options.loose;
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
debug("hyphen replace", range);
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
debug("comparator trim", range);
range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
debug("tilde trim", range);
range = range.replace(re[t.CARETTRIM], caretTrimReplace);
debug("caret trim", range);
let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
if (loose) {
rangeList = rangeList.filter((comp) => {
debug("loose invalid filter", comp, this.options);
return !!comp.match(re[t.COMPARATORLOOSE]);
});
}
debug("range list", rangeList);
const rangeMap = new Map;
const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp];
}
rangeMap.set(comp.value, comp);
}
if (rangeMap.size > 1 && rangeMap.has("")) {
rangeMap.delete("");
}
const result = [...rangeMap.values()];
cache3.set(memoKey, result);
return result;
}
intersects(range, options) {
if (!(range instanceof Range)) {
throw new TypeError("a Range is required");
}
return this.set.some((thisComparators) => {
return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options);
});
});
});
});
}
test(version2) {
if (!version2) {
return false;
}
if (typeof version2 === "string") {
try {
version2 = new SemVer(version2, this.options);
} catch (er) {
return false;
}
}
for (let i2 = 0;i2 < this.set.length; i2++) {
if (testSet(this.set[i2], version2, this.options)) {
return true;
}
}
return false;
}
}
module.exports = Range;
var LRU = require_lrucache();
var cache3 = new LRU;
var parseOptions = require_parse_options();
var Comparator = require_comparator();
var debug = require_debug2();
var SemVer = require_semver();
var {
safeRe: re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = require_re();
var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants8();
var isNullSet = (c6) => c6.value === "<0.0.0-0";
var isAny = (c6) => c6.value === "";
var isSatisfiable = (comparators, options) => {
let result = true;
const remainingComparators = comparators.slice();
let testComparator = remainingComparators.pop();
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options);
});
testComparator = remainingComparators.pop();
}
return result;
};
var parseComparator = (comp, options) => {
comp = comp.replace(re[t.BUILD], "");
debug("comp", comp, options);
comp = replaceCarets(comp, options);
debug("caret", comp);
comp = replaceTildes(comp, options);
debug("tildes", comp);
comp = replaceXRanges(comp, options);
debug("xrange", comp);
comp = replaceStars(comp, options);
debug("stars", comp);
return comp;
};
var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
var replaceTildes = (comp, options) => {
return comp.trim().split(/\s+/).map((c6) => replaceTilde(c6, options)).join(" ");
};
var replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
return comp.replace(r, (_, M2, m, p, pr) => {
debug("tilde", comp, _, M2, m, p, pr);
let ret;
if (isX(M2)) {
ret = "";
} else if (isX(m)) {
ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
} else if (isX(p)) {
ret = `>=${M2}.${m}.0 <${M2}.${+m + 1}.0-0`;
} else if (pr) {
debug("replaceTilde pr", pr);
ret = `>=${M2}.${m}.${p}-${pr} <${M2}.${+m + 1}.0-0`;
} else {
ret = `>=${M2}.${m}.${p} <${M2}.${+m + 1}.0-0`;
}
debug("tilde return", ret);
return ret;
});
};
var replaceCarets = (comp, options) => {
return comp.trim().split(/\s+/).map((c6) => replaceCaret(c6, options)).join(" ");
};
var replaceCaret = (comp, options) => {
debug("caret", comp, options);
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
const z2 = options.includePrerelease ? "-0" : "";
return comp.replace(r, (_, M2, m, p, pr) => {
debug("caret", comp, _, M2, m, p, pr);
let ret;
if (isX(M2)) {
ret = "";
} else if (isX(m)) {
ret = `>=${M2}.0.0${z2} <${+M2 + 1}.0.0-0`;
} else if (isX(p)) {
if (M2 === "0") {
ret = `>=${M2}.${m}.0${z2} <${M2}.${+m + 1}.0-0`;
} else {
ret = `>=${M2}.${m}.0${z2} <${+M2 + 1}.0.0-0`;
}
} else if (pr) {
debug("replaceCaret pr", pr);
if (M2 === "0") {
if (m === "0") {
ret = `>=${M2}.${m}.${p}-${pr} <${M2}.${m}.${+p + 1}-0`;
} else {
ret = `>=${M2}.${m}.${p}-${pr} <${M2}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M2}.${m}.${p}-${pr} <${+M2 + 1}.0.0-0`;
}
} else {
debug("no pr");
if (M2 === "0") {
if (m === "0") {
ret = `>=${M2}.${m}.${p}${z2} <${M2}.${m}.${+p + 1}-0`;
} else {
ret = `>=${M2}.${m}.${p}${z2} <${M2}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M2}.${m}.${p} <${+M2 + 1}.0.0-0`;
}
}
debug("caret return", ret);
return ret;
});
};
var replaceXRanges = (comp, options) => {
debug("replaceXRanges", comp, options);
return comp.split(/\s+/).map((c6) => replaceXRange(c6, options)).join(" ");
};
var replaceXRange = (comp, options) => {
comp = comp.trim();
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
return comp.replace(r, (ret, gtlt, M2, m, p, pr) => {
debug("xRange", comp, ret, gtlt, M2, m, p, pr);
const xM = isX(M2);
const xm = xM || isX(m);
const xp = xm || isX(p);
const anyX = xp;
if (gtlt === "=" && anyX) {
gtlt = "";
}
pr = options.includePrerelease ? "-0" : "";
if (xM) {
if (gtlt === ">" || gtlt === "<") {
ret = "<0.0.0-0";
} else {
ret = "*";
}
} else if (gtlt && anyX) {
if (xm) {
m = 0;
}
p = 0;
if (gtlt === ">") {
gtlt = ">=";
if (xm) {
M2 = +M2 + 1;
m = 0;
p = 0;
} else {
m = +m + 1;
p = 0;
}
} else if (gtlt === "<=") {
gtlt = "<";
if (xm) {
M2 = +M2 + 1;
} else {
m = +m + 1;
}
}
if (gtlt === "<") {
pr = "-0";
}
ret = `${gtlt + M2}.${m}.${p}${pr}`;
} else if (xm) {
ret = `>=${M2}.0.0${pr} <${+M2 + 1}.0.0-0`;
} else if (xp) {
ret = `>=${M2}.${m}.0${pr} <${M2}.${+m + 1}.0-0`;
}
debug("xRange return", ret);
return ret;
});
};
var replaceStars = (comp, options) => {
debug("replaceStars", comp, options);
return comp.trim().replace(re[t.STAR], "");
};
var replaceGTE0 = (comp, options) => {
debug("replaceGTE0", comp, options);
return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
};
var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
if (isX(fM)) {
from = "";
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
} else if (fpr) {
from = `>=${from}`;
} else {
from = `>=${from}${incPr ? "-0" : ""}`;
}
if (isX(tM)) {
to = "";
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`;
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`;
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`;
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`;
} else {
to = `<=${to}`;
}
return `${from} ${to}`.trim();
};
var testSet = (set2, version2, options) => {
for (let i2 = 0;i2 < set2.length; i2++) {
if (!set2[i2].test(version2)) {
return false;
}
}
if (version2.prerelease.length && !options.includePrerelease) {
for (let i2 = 0;i2 < set2.length; i2++) {
debug(set2[i2].semver);
if (set2[i2].semver === Comparator.ANY) {
continue;
}
if (set2[i2].semver.prerelease.length > 0) {
const allowed = set2[i2].semver;
if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) {
return true;
}
}
}
return false;
}
return true;
};
});
// node_modules/semver/classes/comparator.js
var require_comparator = __commonJS((exports, module) => {
var ANY = Symbol("SemVer ANY");
class Comparator {
static get ANY() {
return ANY;
}
constructor(comp, options) {
options = parseOptions(options);
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp;
} else {
comp = comp.value;
}
}
comp = comp.trim().split(/\s+/).join(" ");
debug("comparator", comp, options);
this.options = options;
this.loose = !!options.loose;
this.parse(comp);
if (this.semver === ANY) {
this.value = "";
} else {
this.value = this.operator + this.semver.version;
}
debug("comp", this);
}
parse(comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
const m = comp.match(r);
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`);
}
this.operator = m[1] !== undefined ? m[1] : "";
if (this.operator === "=") {
this.operator = "";
}
if (!m[2]) {
this.semver = ANY;
} else {
this.semver = new SemVer(m[2], this.options.loose);
}
}
toString() {
return this.value;
}
test(version2) {
debug("Comparator.test", version2, this.options.loose);
if (this.semver === ANY || version2 === ANY) {
return true;
}
if (typeof version2 === "string") {
try {
version2 = new SemVer(version2, this.options);
} catch (er) {
return false;
}
}
return cmp(version2, this.operator, this.semver, this.options);
}
intersects(comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError("a Comparator is required");
}
if (this.operator === "") {
if (this.value === "") {
return true;
}
return new Range(comp.value, options).test(this.value);
} else if (comp.operator === "") {
if (comp.value === "") {
return true;
}
return new Range(this.value, options).test(comp.semver);
}
options = parseOptions(options);
if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
return false;
}
if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
return false;
}
if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
return true;
}
if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
return true;
}
if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
return true;
}
if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
return true;
}
if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
return true;
}
return false;
}
}
module.exports = Comparator;
var parseOptions = require_parse_options();
var { safeRe: re, t } = require_re();
var cmp = require_cmp();
var debug = require_debug2();
var SemVer = require_semver();
var Range = require_range2();
});
// node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS((exports, module) => {
var Range = require_range2();
var satisfies = (version2, range, options) => {
try {
range = new Range(range, options);
} catch (er) {
return false;
}
return range.test(version2);
};
module.exports = satisfies;
});
// node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS((exports, module) => {
var Range = require_range2();
var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c6) => c6.value).join(" ").trim().split(" "));
module.exports = toComparators;
});
// node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS((exports, module) => {
var SemVer = require_semver();
var Range = require_range2();
var maxSatisfying = (versions2, range, options) => {
let max = null;
let maxSV = null;
let rangeObj = null;
try {
rangeObj = new Range(range, options);
} catch (er) {
return null;
}
versions2.forEach((v) => {
if (rangeObj.test(v)) {
if (!max || maxSV.compare(v) === -1) {
max = v;
maxSV = new SemVer(max, options);
}
}
});
return max;
};
module.exports = maxSatisfying;
});
// node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS((exports, module) => {
var SemVer = require_semver();
var Range = require_range2();
var minSatisfying = (versions2, range, options) => {
let min = null;
let minSV = null;
let rangeObj = null;
try {
rangeObj = new Range(range, options);
} catch (er) {
return null;
}
versions2.forEach((v) => {
if (rangeObj.test(v)) {
if (!min || minSV.compare(v) === 1) {
min = v;
minSV = new SemVer(min, options);
}
}
});
return min;
};
module.exports = minSatisfying;
});
// node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS((exports, module) => {
var SemVer = require_semver();
var Range = require_range2();
var gt = require_gt();
var minVersion = (range, loose) => {
range = new Range(range, loose);
let minver = new SemVer("0.0.0");
if (range.test(minver)) {
return minver;
}
minver = new SemVer("0.0.0-0");
if (range.test(minver)) {
return minver;
}
minver = null;
for (let i2 = 0;i2 < range.set.length; ++i2) {
const comparators = range.set[i2];
let setMin = null;
comparators.forEach((comparator) => {
const compver = new SemVer(comparator.semver.version);
switch (comparator.operator) {
case ">":
if (compver.prerelease.length === 0) {
compver.patch++;
} else {
compver.prerelease.push(0);
}
compver.raw = compver.format();
case "":
case ">=":
if (!setMin || gt(compver, setMin)) {
setMin = compver;
}
break;
case "<":
case "<=":
break;
default:
throw new Error(`Unexpected operation: ${comparator.operator}`);
}
});
if (setMin && (!minver || gt(minver, setMin))) {
minver = setMin;
}
}
if (minver && range.test(minver)) {
return minver;
}
return null;
};
module.exports = minVersion;
});
// node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS((exports, module) => {
var Range = require_range2();
var validRange = (range, options) => {
try {
return new Range(range, options).range || "*";
} catch (er) {
return null;
}
};
module.exports = validRange;
});
// node_modules/semver/ranges/outside.js
var require_outside = __commonJS((exports, module) => {
var SemVer = require_semver();
var Comparator = require_comparator();
var { ANY } = Comparator;
var Range = require_range2();
var satisfies = require_satisfies();
var gt = require_gt();
var lt = require_lt();
var lte = require_lte();
var gte = require_gte();
var outside = (version2, range, hilo, options) => {
version2 = new SemVer(version2, options);
range = new Range(range, options);
let gtfn, ltefn, ltfn, comp, ecomp;
switch (hilo) {
case ">":
gtfn = gt;
ltefn = lte;
ltfn = lt;
comp = ">";
ecomp = ">=";
break;
case "<":
gtfn = lt;
ltefn = gte;
ltfn = gt;
comp = "<";
ecomp = "<=";
break;
default:
throw new TypeError('Must provide a hilo val of "<" or ">"');
}
if (satisfies(version2, range, options)) {
return false;
}
for (let i2 = 0;i2 < range.set.length; ++i2) {
const comparators = range.set[i2];
let high = null;
let low = null;
comparators.forEach((comparator) => {
if (comparator.semver === ANY) {
comparator = new Comparator(">=0.0.0");
}
high = high || comparator;
low = low || comparator;
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator;
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator;
}
});
if (high.operator === comp || high.operator === ecomp) {
return false;
}
if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) {
return false;
} else if (low.operator === ecomp && ltfn(version2, low.semver)) {
return false;
}
}
return true;
};
module.exports = outside;
});
// node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS((exports, module) => {
var outside = require_outside();
var gtr = (version2, range, options) => outside(version2, range, ">", options);
module.exports = gtr;
});
// node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS((exports, module) => {
var outside = require_outside();
var ltr = (version2, range, options) => outside(version2, range, "<", options);
module.exports = ltr;
});
// node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS((exports, module) => {
var Range = require_range2();
var intersects = (r1, r2, options) => {
r1 = new Range(r1, options);
r2 = new Range(r2, options);
return r1.intersects(r2, options);
};
module.exports = intersects;
});
// node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS((exports, module) => {
var satisfies = require_satisfies();
var compare = require_compare();
module.exports = (versions2, range, options) => {
const set2 = [];
let first = null;
let prev = null;
const v = versions2.sort((a2, b) => compare(a2, b, options));
for (const version2 of v) {
const included = satisfies(version2, range, options);
if (included) {
prev = version2;
if (!first) {
first = version2;
}
} else {
if (prev) {
set2.push([first, prev]);
}
prev = null;
first = null;
}
}
if (first) {
set2.push([first, null]);
}
const ranges = [];
for (const [min, max] of set2) {
if (min === max) {
ranges.push(min);
} else if (!max && min === v[0]) {
ranges.push("*");
} else if (!max) {
ranges.push(`>=${min}`);
} else if (min === v[0]) {
ranges.push(`<=${max}`);
} else {
ranges.push(`${min} - ${max}`);
}
}
const simplified = ranges.join(" || ");
const original = typeof range.raw === "string" ? range.raw : String(range);
return simplified.length < original.length ? simplified : range;
};
});
// node_modules/semver/ranges/subset.js
var require_subset = __commonJS((exports, module) => {
var Range = require_range2();
var Comparator = require_comparator();
var { ANY } = Comparator;
var satisfies = require_satisfies();
var compare = require_compare();
var subset = (sub, dom, options = {}) => {
if (sub === dom) {
return true;
}
sub = new Range(sub, options);
dom = new Range(dom, options);
let sawNonNull = false;
OUTER:
for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options);
sawNonNull = sawNonNull || isSub !== null;
if (isSub) {
continue OUTER;
}
}
if (sawNonNull) {
return false;
}
}
return true;
};
var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
var minimumVersion = [new Comparator(">=0.0.0")];
var simpleSubset = (sub, dom, options) => {
if (sub === dom) {
return true;
}
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) {
return true;
} else if (options.includePrerelease) {
sub = minimumVersionWithPreRelease;
} else {
sub = minimumVersion;
}
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) {
return true;
} else {
dom = minimumVersion;
}
}
const eqSet = new Set;
let gt, lt;
for (const c6 of sub) {
if (c6.operator === ">" || c6.operator === ">=") {
gt = higherGT(gt, c6, options);
} else if (c6.operator === "<" || c6.operator === "<=") {
lt = lowerLT(lt, c6, options);
} else {
eqSet.add(c6.semver);
}
}
if (eqSet.size > 1) {
return null;
}
let gtltComp;
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options);
if (gtltComp > 0) {
return null;
} else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
return null;
}
}
for (const eq2 of eqSet) {
if (gt && !satisfies(eq2, String(gt), options)) {
return null;
}
if (lt && !satisfies(eq2, String(lt), options)) {
return null;
}
for (const c6 of dom) {
if (!satisfies(eq2, String(c6), options)) {
return false;
}
}
return true;
}
let higher, lower;
let hasDomLT, hasDomGT;
let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false;
}
for (const c6 of dom) {
hasDomGT = hasDomGT || c6.operator === ">" || c6.operator === ">=";
hasDomLT = hasDomLT || c6.operator === "<" || c6.operator === "<=";
if (gt) {
if (needDomGTPre) {
if (c6.semver.prerelease && c6.semver.prerelease.length && c6.semver.major === needDomGTPre.major && c6.semver.minor === needDomGTPre.minor && c6.semver.patch === needDomGTPre.patch) {
needDomGTPre = false;
}
}
if (c6.operator === ">" || c6.operator === ">=") {
higher = higherGT(gt, c6, options);
if (higher === c6 && higher !== gt) {
return false;
}
} else if (gt.operator === ">=" && !satisfies(gt.semver, String(c6), options)) {
return false;
}
}
if (lt) {
if (needDomLTPre) {
if (c6.semver.prerelease && c6.semver.prerelease.length && c6.semver.major === needDomLTPre.major && c6.semver.minor === needDomLTPre.minor && c6.semver.patch === needDomLTPre.patch) {
needDomLTPre = false;
}
}
if (c6.operator === "<" || c6.operator === "<=") {
lower = lowerLT(lt, c6, options);
if (lower === c6 && lower !== lt) {
return false;
}
} else if (lt.operator === "<=" && !satisfies(lt.semver, String(c6), options)) {
return false;
}
}
if (!c6.operator && (lt || gt) && gtltComp !== 0) {
return false;
}
}
if (gt && hasDomLT && !lt && gtltComp !== 0) {
return false;
}
if (lt && hasDomGT && !gt && gtltComp !== 0) {
return false;
}
if (needDomGTPre || needDomLTPre) {
return false;
}
return true;
};
var higherGT = (a2, b, options) => {
if (!a2) {
return b;
}
const comp = compare(a2.semver, b.semver, options);
return comp > 0 ? a2 : comp < 0 ? b : b.operator === ">" && a2.operator === ">=" ? b : a2;
};
var lowerLT = (a2, b, options) => {
if (!a2) {
return b;
}
const comp = compare(a2.semver, b.semver, options);
return comp < 0 ? a2 : comp > 0 ? b : b.operator === "<" && a2.operator === "<=" ? b : a2;
};
module.exports = subset;
});
// node_modules/semver/index.js
var require_semver2 = __commonJS((exports, module) => {
var internalRe = require_re();
var constants4 = require_constants8();
var SemVer = require_semver();
var identifiers = require_identifiers();
var parse7 = require_parse3();
var valid = require_valid();
var clean = require_clean();
var inc = require_inc();
var diff2 = require_diff();
var major = require_major();
var minor = require_minor();
var patch = require_patch();
var prerelease = require_prerelease();
var compare = require_compare();
var rcompare = require_rcompare();
var compareLoose = require_compare_loose();
var compareBuild = require_compare_build();
var sort = require_sort();
var rsort = require_rsort();
var gt = require_gt();
var lt = require_lt();
var eq2 = require_eq();
var neq = require_neq();
var gte = require_gte();
var lte = require_lte();
var cmp = require_cmp();
var coerce = require_coerce();
var Comparator = require_comparator();
var Range = require_range2();
var satisfies = require_satisfies();
var toComparators = require_to_comparators();
var maxSatisfying = require_max_satisfying();
var minSatisfying = require_min_satisfying();
var minVersion = require_min_version();
var validRange = require_valid2();
var outside = require_outside();
var gtr = require_gtr();
var ltr = require_ltr();
var intersects = require_intersects();
var simplifyRange = require_simplify();
var subset = require_subset();
module.exports = {
parse: parse7,
valid,
clean,
inc,
diff: diff2,
major,
minor,
patch,
prerelease,
compare,
rcompare,
compareLoose,
compareBuild,
sort,
rsort,
gt,
lt,
eq: eq2,
neq,
gte,
lte,
cmp,
coerce,
Comparator,
Range,
satisfies,
toComparators,
maxSatisfying,
minSatisfying,
minVersion,
validRange,
outside,
gtr,
ltr,
intersects,
simplifyRange,
subset,
SemVer,
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants4.SEMVER_SPEC_VERSION,
RELEASE_TYPES: constants4.RELEASE_TYPES,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers
};
});
// src/utils/semver.ts
function getNpmSemver() {
if (!_npmSemver) {
_npmSemver = require_semver2();
}
return _npmSemver;
}
function gt(a2, b) {
if (typeof Bun !== "undefined") {
return Bun.semver.order(a2, b) === 1;
}
return getNpmSemver().gt(a2, b, { loose: true });
}
function gte(a2, b) {
if (typeof Bun !== "undefined") {
return Bun.semver.order(a2, b) >= 0;
}
return getNpmSemver().gte(a2, b, { loose: true });
}
function lt(a2, b) {
if (typeof Bun !== "undefined") {
return Bun.semver.order(a2, b) === -1;
}
return getNpmSemver().lt(a2, b, { loose: true });
}
function satisfies(version2, range) {
if (typeof Bun !== "undefined") {
return Bun.semver.satisfies(version2, range);
}
return getNpmSemver().satisfies(version2, range, { loose: true });
}
var _npmSemver;
// src/ink/clearTerminal.ts
function isWindowsTerminal() {
return process.platform === "win32" && !!process.env.WT_SESSION;
}
function isMintty() {
if (process.env.TERM_PROGRAM === "mintty") {
return true;
}
if (process.platform === "win32" && process.env.MSYSTEM) {
return true;
}
return false;
}
function isModernWindowsTerminal() {
if (isWindowsTerminal()) {
return true;
}
if (process.platform === "win32" && process.env.TERM_PROGRAM === "vscode" && process.env.TERM_PROGRAM_VERSION) {
return true;
}
if (isMintty()) {
return true;
}
return false;
}
function getClearTerminalSequence() {
if (process.platform === "win32") {
if (isModernWindowsTerminal()) {
return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME;
} else {
return ERASE_SCREEN + CURSOR_HOME_WINDOWS;
}
}
return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME;
}
var CURSOR_HOME_WINDOWS, clearTerminal;
var init_clearTerminal = __esm(() => {
init_csi();
CURSOR_HOME_WINDOWS = csi(0, "f");
clearTerminal = getClearTerminalSequence();
});
// src/ink/termio/dec.ts
function decset(mode) {
return csi(`?${mode}h`);
}
function decreset(mode) {
return csi(`?${mode}l`);
}
var DEC, BSU, ESU, EBP, DBP, EFE, DFE, SHOW_CURSOR, HIDE_CURSOR, ENTER_ALT_SCREEN, EXIT_ALT_SCREEN, ENABLE_MOUSE_TRACKING, DISABLE_MOUSE_TRACKING;
var init_dec = __esm(() => {
init_csi();
DEC = {
CURSOR_VISIBLE: 25,
ALT_SCREEN: 47,
ALT_SCREEN_CLEAR: 1049,
MOUSE_NORMAL: 1000,
MOUSE_BUTTON: 1002,
MOUSE_ANY: 1003,
MOUSE_SGR: 1006,
FOCUS_EVENTS: 1004,
BRACKETED_PASTE: 2004,
SYNCHRONIZED_UPDATE: 2026
};
BSU = decset(DEC.SYNCHRONIZED_UPDATE);
ESU = decreset(DEC.SYNCHRONIZED_UPDATE);
EBP = decset(DEC.BRACKETED_PASTE);
DBP = decreset(DEC.BRACKETED_PASTE);
EFE = decset(DEC.FOCUS_EVENTS);
DFE = decreset(DEC.FOCUS_EVENTS);
SHOW_CURSOR = decset(DEC.CURSOR_VISIBLE);
HIDE_CURSOR = decreset(DEC.CURSOR_VISIBLE);
ENTER_ALT_SCREEN = decset(DEC.ALT_SCREEN_CLEAR);
EXIT_ALT_SCREEN = decreset(DEC.ALT_SCREEN_CLEAR);
ENABLE_MOUSE_TRACKING = decset(DEC.MOUSE_NORMAL) + decset(DEC.MOUSE_BUTTON) + decset(DEC.MOUSE_ANY) + decset(DEC.MOUSE_SGR);
DISABLE_MOUSE_TRACKING = decreset(DEC.MOUSE_SGR) + decreset(DEC.MOUSE_ANY) + decreset(DEC.MOUSE_BUTTON) + decreset(DEC.MOUSE_NORMAL);
});
// src/ink/termio/osc.ts
import { Buffer as Buffer8 } from "buffer";
function osc(...parts) {
const terminator = env3.terminal === "kitty" ? ST : BEL;
return `${OSC_PREFIX}${parts.join(SEP)}${terminator}`;
}
function wrapForMultiplexer(sequence) {
if (process.env["TMUX"]) {
const escaped = sequence.replaceAll("\x1B", "\x1B\x1B");
return `\x1BPtmux;${escaped}\x1B\\`;
}
if (process.env["STY"]) {
return `\x1BP${sequence}\x1B\\`;
}
return sequence;
}
function getClipboardPath() {
const nativeAvailable = process.platform === "darwin" && !process.env["SSH_CONNECTION"];
if (nativeAvailable)
return "native";
if (process.env["TMUX"])
return "tmux-buffer";
return "osc52";
}
function tmuxPassthrough(payload) {
return `${ESC}Ptmux;${payload.replaceAll(ESC, ESC + ESC)}${ST}`;
}
async function tmuxLoadBuffer(text) {
if (!process.env["TMUX"])
return false;
const args = process.env["LC_TERMINAL"] === "iTerm2" ? ["load-buffer", "-"] : ["load-buffer", "-w", "-"];
const { code } = await execFileNoThrow("tmux", args, {
input: text,
useCwd: false,
timeout: 2000
});
return code === 0;
}
async function setClipboard(text) {
const b64 = Buffer8.from(text, "utf8").toString("base64");
const raw = osc(OSC2.CLIPBOARD, "c", b64);
if (!process.env["SSH_CONNECTION"])
copyNative(text);
const tmuxBufferLoaded = await tmuxLoadBuffer(text);
if (tmuxBufferLoaded)
return tmuxPassthrough(`${ESC}]52;c;${b64}${BEL}`);
return raw;
}
function copyNative(text) {
const opts = { input: text, useCwd: false, timeout: 2000 };
switch (process.platform) {
case "darwin":
execFileNoThrow("pbcopy", [], opts);
return;
case "linux": {
if (linuxCopy === null)
return;
if (linuxCopy === "wl-copy") {
execFileNoThrow("wl-copy", [], opts);
return;
}
if (linuxCopy === "xclip") {
execFileNoThrow("xclip", ["-selection", "clipboard"], opts);
return;
}
if (linuxCopy === "xsel") {
execFileNoThrow("xsel", ["--clipboard", "--input"], opts);
return;
}
execFileNoThrow("wl-copy", [], opts).then((r) => {
if (r.code === 0) {
linuxCopy = "wl-copy";
return;
}
execFileNoThrow("xclip", ["-selection", "clipboard"], opts).then((r2) => {
if (r2.code === 0) {
linuxCopy = "xclip";
return;
}
execFileNoThrow("xsel", ["--clipboard", "--input"], opts).then((r3) => {
linuxCopy = r3.code === 0 ? "xsel" : null;
});
});
});
return;
}
case "win32":
execFileNoThrow("clip", [], opts);
return;
}
}
function parseOSC(content) {
const semicolonIdx = content.indexOf(";");
const command = semicolonIdx >= 0 ? content.slice(0, semicolonIdx) : content;
const data = semicolonIdx >= 0 ? content.slice(semicolonIdx + 1) : "";
const commandNum = parseInt(command, 10);
if (commandNum === OSC2.SET_TITLE_AND_ICON) {
return { type: "title", action: { type: "both", title: data } };
}
if (commandNum === OSC2.SET_ICON) {
return { type: "title", action: { type: "iconName", name: data } };
}
if (commandNum === OSC2.SET_TITLE) {
return { type: "title", action: { type: "windowTitle", title: data } };
}
if (commandNum === OSC2.HYPERLINK) {
const parts = data.split(";");
const paramsStr = parts[0] ?? "";
const url3 = parts.slice(1).join(";");
if (url3 === "") {
return { type: "link", action: { type: "end" } };
}
const params = {};
if (paramsStr) {
for (const pair of paramsStr.split(":")) {
const eqIdx = pair.indexOf("=");
if (eqIdx >= 0) {
params[pair.slice(0, eqIdx)] = pair.slice(eqIdx + 1);
}
}
}
return {
type: "link",
action: {
type: "start",
url: url3,
params: Object.keys(params).length > 0 ? params : undefined
}
};
}
if (commandNum === OSC2.TAB_STATUS) {
return { type: "tabStatus", action: parseTabStatus(data) };
}
return { type: "unknown", sequence: `\x1B]${content}` };
}
function parseOscColor(spec) {
const hex = spec.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (hex) {
return {
type: "rgb",
r: parseInt(hex[1], 16),
g: parseInt(hex[2], 16),
b: parseInt(hex[3], 16)
};
}
const rgb = spec.match(/^rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})$/i);
if (rgb) {
const scale = (s) => Math.round(parseInt(s, 16) / (16 ** s.length - 1) * 255);
return {
type: "rgb",
r: scale(rgb[1]),
g: scale(rgb[2]),
b: scale(rgb[3])
};
}
return null;
}
function parseTabStatus(data) {
const action = {};
for (const [key, value] of splitTabStatusPairs(data)) {
switch (key) {
case "indicator":
action.indicator = value === "" ? null : parseOscColor(value);
break;
case "status":
action.status = value === "" ? null : value;
break;
case "status-color":
action.statusColor = value === "" ? null : parseOscColor(value);
break;
}
}
return action;
}
function* splitTabStatusPairs(data) {
let key = "";
let val = "";
let inVal = false;
let esc2 = false;
for (const c6 of data) {
if (esc2) {
if (inVal)
val += c6;
else
key += c6;
esc2 = false;
} else if (c6 === "\\") {
esc2 = true;
} else if (c6 === ";") {
yield [key, val];
key = "";
val = "";
inVal = false;
} else if (c6 === "=" && !inVal) {
inVal = true;
} else if (inVal) {
val += c6;
} else {
key += c6;
}
}
if (key || inVal)
yield [key, val];
}
function link(url3, params) {
if (!url3)
return LINK_END;
const p = { id: osc8Id(url3), ...params };
const paramStr = Object.entries(p).map(([k, v]) => `${k}=${v}`).join(":");
return osc(OSC2.HYPERLINK, paramStr, url3);
}
function osc8Id(url3) {
let h2 = 0;
for (let i2 = 0;i2 < url3.length; i2++)
h2 = (h2 << 5) - h2 + url3.charCodeAt(i2) | 0;
return (h2 >>> 0).toString(36);
}
function supportsTabStatus() {
return process.env.USER_TYPE === "ant";
}
function tabStatus(fields) {
const parts = [];
const rgb = (c6) => c6.type === "rgb" ? `#${[c6.r, c6.g, c6.b].map((n2) => n2.toString(16).padStart(2, "0")).join("")}` : "";
if ("indicator" in fields)
parts.push(`indicator=${fields.indicator ? rgb(fields.indicator) : ""}`);
if ("status" in fields)
parts.push(`status=${fields.status?.replaceAll("\\", "\\\\").replaceAll(";", "\\;") ?? ""}`);
if ("statusColor" in fields)
parts.push(`status-color=${fields.statusColor ? rgb(fields.statusColor) : ""}`);
return osc(OSC2.TAB_STATUS, parts.join(";"));
}
var OSC_PREFIX, ST, linuxCopy, OSC2, LINK_END, ITERM2, PROGRESS, CLEAR_ITERM2_PROGRESS, CLEAR_TERMINAL_TITLE, CLEAR_TAB_STATUS;
var init_osc = __esm(() => {
init_env();
init_execFileNoThrow();
init_ansi();
OSC_PREFIX = ESC + String.fromCharCode(ESC_TYPE.OSC);
ST = ESC + "\\";
OSC2 = {
SET_TITLE_AND_ICON: 0,
SET_ICON: 1,
SET_TITLE: 2,
SET_COLOR: 4,
SET_CWD: 7,
HYPERLINK: 8,
ITERM2: 9,
SET_FG_COLOR: 10,
SET_BG_COLOR: 11,
SET_CURSOR_COLOR: 12,
CLIPBOARD: 52,
KITTY: 99,
RESET_COLOR: 104,
RESET_FG_COLOR: 110,
RESET_BG_COLOR: 111,
RESET_CURSOR_COLOR: 112,
SEMANTIC_PROMPT: 133,
GHOSTTY: 777,
TAB_STATUS: 21337
};
LINK_END = osc(OSC2.HYPERLINK, "", "");
ITERM2 = {
NOTIFY: 0,
BADGE: 2,
PROGRESS: 4
};
PROGRESS = {
CLEAR: 0,
SET: 1,
ERROR: 2,
INDETERMINATE: 3
};
CLEAR_ITERM2_PROGRESS = `${OSC_PREFIX}${OSC2.ITERM2};${ITERM2.PROGRESS};${PROGRESS.CLEAR};${BEL}`;
CLEAR_TERMINAL_TITLE = `${OSC_PREFIX}${OSC2.SET_TITLE_AND_ICON};${BEL}`;
CLEAR_TAB_STATUS = osc(OSC2.TAB_STATUS, "indicator=;status=;status-color=");
});
// src/ink/terminal.ts
function isProgressReportingAvailable() {
if (!process.stdout.isTTY) {
return false;
}
if (process.env.WT_SESSION) {
return false;
}
if (process.env.ConEmuANSI || process.env.ConEmuPID || process.env.ConEmuTask) {
return true;
}
const version2 = import_semver.coerce(process.env.TERM_PROGRAM_VERSION);
if (!version2) {
return false;
}
if (process.env.TERM_PROGRAM === "ghostty") {
return gte(version2.version, "1.2.0");
}
if (process.env.TERM_PROGRAM === "iTerm.app") {
return gte(version2.version, "3.6.6");
}
return false;
}
function isSynchronizedOutputSupported() {
if (process.env.TMUX)
return false;
const termProgram = process.env.TERM_PROGRAM;
const term = process.env.TERM;
if (termProgram === "iTerm.app" || termProgram === "WezTerm" || termProgram === "WarpTerminal" || termProgram === "ghostty" || termProgram === "contour" || termProgram === "vscode" || termProgram === "alacritty") {
return true;
}
if (term?.includes("kitty") || process.env.KITTY_WINDOW_ID)
return true;
if (term === "xterm-ghostty")
return true;
if (term?.startsWith("foot"))
return true;
if (term?.includes("alacritty"))
return true;
if (process.env.ZED_TERM)
return true;
if (process.env.WT_SESSION)
return true;
const vteVersion = process.env.VTE_VERSION;
if (vteVersion) {
const version2 = parseInt(vteVersion, 10);
if (version2 >= 6800)
return true;
}
return false;
}
function setXtversionName(name) {
if (xtversionName === undefined)
xtversionName = name;
}
function isXtermJs() {
if (process.env.TERM_PROGRAM === "vscode")
return true;
return xtversionName?.startsWith("xterm.js") ?? false;
}
function supportsExtendedKeys() {
return EXTENDED_KEYS_TERMINALS.includes(env3.terminal ?? "");
}
function hasCursorUpViewportYankBug() {
return process.platform === "win32" || !!process.env.WT_SESSION;
}
function writeDiffToTerminal(terminal, diff2, skipSyncMarkers = false) {
if (diff2.length === 0) {
return;
}
const useSync = !skipSyncMarkers;
let buffer = useSync ? BSU : "";
for (const patch of diff2) {
switch (patch.type) {
case "stdout":
buffer += patch.content;
break;
case "clear":
if (patch.count > 0) {
buffer += eraseLines(patch.count);
}
break;
case "clearTerminal":
buffer += getClearTerminalSequence();
break;
case "cursorHide":
buffer += HIDE_CURSOR;
break;
case "cursorShow":
buffer += SHOW_CURSOR;
break;
case "cursorMove":
buffer += cursorMove(patch.x, patch.y);
break;
case "cursorTo":
buffer += cursorTo(patch.col);
break;
case "carriageReturn":
buffer += "\r";
break;
case "hyperlink":
buffer += link(patch.uri);
break;
case "styleStr":
buffer += patch.str;
break;
}
}
if (useSync)
buffer += ESU;
terminal.stdout.write(buffer);
}
var import_semver, xtversionName, EXTENDED_KEYS_TERMINALS, SYNC_OUTPUT_SUPPORTED;
var init_terminal = __esm(() => {
init_env();
init_clearTerminal();
init_csi();
init_dec();
init_osc();
import_semver = __toESM(require_semver2(), 1);
EXTENDED_KEYS_TERMINALS = [
"iTerm.app",
"kitty",
"WezTerm",
"ghostty",
"tmux",
"windows-terminal"
];
SYNC_OUTPUT_SUPPORTED = isSynchronizedOutputSupported();
});
// src/ink/terminal-focus-state.ts
function setTerminalFocused(v) {
focusState = v ? "focused" : "blurred";
for (const cb of subscribers) {
cb();
}
if (!v) {
for (const resolve9 of resolvers) {
resolve9();
}
resolvers.clear();
}
}
function getTerminalFocused() {
return focusState !== "blurred";
}
function getTerminalFocusState() {
return focusState;
}
function subscribeTerminalFocus(cb) {
subscribers.add(cb);
return () => {
subscribers.delete(cb);
};
}
var focusState = "unknown", resolvers, subscribers;
var init_terminal_focus_state = __esm(() => {
resolvers = new Set;
subscribers = new Set;
});
// src/ink/terminal-querier.ts
function xtversion() {
return {
request: csi(">0q"),
match: (r) => r.type === "xtversion"
};
}
class TerminalQuerier {
stdout;
queue = [];
constructor(stdout) {
this.stdout = stdout;
}
send(query) {
return new Promise((resolve9) => {
this.queue.push({
kind: "query",
match: query.match,
resolve: (r) => resolve9(r)
});
this.stdout.write(query.request);
});
}
flush() {
return new Promise((resolve9) => {
this.queue.push({ kind: "sentinel", resolve: resolve9 });
this.stdout.write(SENTINEL);
});
}
onResponse(r) {
const idx = this.queue.findIndex((p) => p.kind === "query" && p.match(r));
if (idx !== -1) {
const [q] = this.queue.splice(idx, 1);
if (q?.kind === "query")
q.resolve(r);
return;
}
if (r.type === "da1") {
const s = this.queue.findIndex((p) => p.kind === "sentinel");
if (s === -1)
return;
for (const p of this.queue.splice(0, s + 1)) {
if (p.kind === "query")
p.resolve(undefined);
else
p.resolve();
}
}
}
}
var SENTINEL;
var init_terminal_querier = __esm(() => {
init_csi();
init_osc();
SENTINEL = csi("c");
});
// src/ink/components/AppContext.ts
var import_react4, AppContext, AppContext_default;
var init_AppContext = __esm(() => {
import_react4 = __toESM(require_react(), 1);
AppContext = import_react4.createContext({
exit() {}
});
AppContext.displayName = "InternalAppContext";
AppContext_default = AppContext;
});
// src/ink/constants.ts
var FRAME_INTERVAL_MS = 16;
// src/ink/components/TerminalFocusContext.tsx
function TerminalFocusProvider(t0) {
const $2 = c5(6);
const {
children
} = t0;
const isTerminalFocused = import_react5.useSyncExternalStore(subscribeTerminalFocus, getTerminalFocused);
const terminalFocusState = import_react5.useSyncExternalStore(subscribeTerminalFocus, getTerminalFocusState);
let t1;
if ($2[0] !== isTerminalFocused || $2[1] !== terminalFocusState) {
t1 = {
isTerminalFocused,
terminalFocusState
};
$2[0] = isTerminalFocused;
$2[1] = terminalFocusState;
$2[2] = t1;
} else {
t1 = $2[2];
}
const value = t1;
let t2;
if ($2[3] !== children || $2[4] !== value) {
t2 = /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(TerminalFocusContext.Provider, {
value,
children
}, undefined, false, undefined, this);
$2[3] = children;
$2[4] = value;
$2[5] = t2;
} else {
t2 = $2[5];
}
return t2;
}
var import_react5, jsx_dev_runtime2, TerminalFocusContext, TerminalFocusContext_default;
var init_TerminalFocusContext = __esm(() => {
init_terminal_focus_state();
import_react5 = __toESM(require_react(), 1);
jsx_dev_runtime2 = __toESM(require_jsx_dev_runtime(), 1);
TerminalFocusContext = import_react5.createContext({
isTerminalFocused: true,
terminalFocusState: "unknown"
});
TerminalFocusContext.displayName = "TerminalFocusContext";
TerminalFocusContext_default = TerminalFocusContext;
});
// src/ink/hooks/use-terminal-focus.ts
function useTerminalFocus() {
const { isTerminalFocused } = import_react6.useContext(TerminalFocusContext_default);
return isTerminalFocused;
}
var import_react6;
var init_use_terminal_focus = __esm(() => {
init_TerminalFocusContext();
import_react6 = __toESM(require_react(), 1);
});
// src/ink/components/ClockContext.tsx
function createClock(tickIntervalMs) {
const subscribers2 = new Map;
let interval = null;
let currentTickIntervalMs = tickIntervalMs;
let startTime = 0;
let tickTime = 0;
function tick() {
tickTime = Date.now() - startTime;
for (const onChange of subscribers2.keys()) {
onChange();
}
}
function updateInterval() {
const anyKeepAlive = [...subscribers2.values()].some(Boolean);
if (anyKeepAlive) {
if (interval) {
clearInterval(interval);
interval = null;
}
if (startTime === 0) {
startTime = Date.now();
}
interval = setInterval(tick, currentTickIntervalMs);
} else if (interval) {
clearInterval(interval);
interval = null;
}
}
return {
subscribe(onChange, keepAlive) {
subscribers2.set(onChange, keepAlive);
updateInterval();
return () => {
subscribers2.delete(onChange);
updateInterval();
};
},
now() {
if (startTime === 0) {
startTime = Date.now();
}
if (interval && tickTime) {
return tickTime;
}
return Date.now() - startTime;
},
setTickInterval(ms) {
if (ms === currentTickIntervalMs)
return;
currentTickIntervalMs = ms;
updateInterval();
}
};
}
function ClockProvider(t0) {
const $2 = c5(7);
const {
children
} = t0;
const [clock] = import_react7.useState(_temp);
const focused = useTerminalFocus();
let t1;
let t2;
if ($2[0] !== clock || $2[1] !== focused) {
t1 = () => {
clock.setTickInterval(focused ? FRAME_INTERVAL_MS : BLURRED_TICK_INTERVAL_MS);
};
t2 = [clock, focused];
$2[0] = clock;
$2[1] = focused;
$2[2] = t1;
$2[3] = t2;
} else {
t1 = $2[2];
t2 = $2[3];
}
import_react7.useEffect(t1, t2);
let t3;
if ($2[4] !== children || $2[5] !== clock) {
t3 = /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ClockContext.Provider, {
value: clock,
children
}, undefined, false, undefined, this);
$2[4] = children;
$2[5] = clock;
$2[6] = t3;
} else {
t3 = $2[6];
}
return t3;
}
function _temp() {
return createClock(FRAME_INTERVAL_MS);
}
var import_react7, jsx_dev_runtime3, ClockContext, BLURRED_TICK_INTERVAL_MS;
var init_ClockContext = __esm(() => {
init_use_terminal_focus();
import_react7 = __toESM(require_react(), 1);
jsx_dev_runtime3 = __toESM(require_jsx_dev_runtime(), 1);
ClockContext = import_react7.createContext(null);
BLURRED_TICK_INTERVAL_MS = FRAME_INTERVAL_MS * 2;
});
// src/ink/components/CursorDeclarationContext.ts
var import_react8, CursorDeclarationContext, CursorDeclarationContext_default;
var init_CursorDeclarationContext = __esm(() => {
import_react8 = __toESM(require_react(), 1);
CursorDeclarationContext = import_react8.createContext(() => {});
CursorDeclarationContext_default = CursorDeclarationContext;
});
// native-stub:code-excerpt
var noop9 = () => null, handler2, stub2, code_excerpt_default, SandboxManager2;
var init_code_excerpt = __esm(() => {
handler2 = {
get(_, prop) {
if (prop === "__esModule")
return true;
if (prop === "default")
return new Proxy({}, handler2);
if (prop === "ExportResultCode")
return { SUCCESS: 0, FAILED: 1 };
if (prop === "resourceFromAttributes")
return () => ({});
if (prop === "SandboxRuntimeConfigSchema")
return { parse: () => ({}) };
return noop9;
}
};
stub2 = new Proxy(noop9, handler2);
code_excerpt_default = stub2;
SandboxManager2 = new Proxy({}, { get: () => noop9 });
});
// native-stub:stack-utils
var noop10 = () => null, handler3, stub3, stack_utils_default, SandboxManager3;
var init_stack_utils = __esm(() => {
handler3 = {
get(_, prop) {
if (prop === "__esModule")
return true;
if (prop === "default")
return new Proxy({}, handler3);
if (prop === "ExportResultCode")
return { SUCCESS: 0, FAILED: 1 };
if (prop === "resourceFromAttributes")
return () => ({});
if (prop === "SandboxRuntimeConfigSchema")
return { parse: () => ({}) };
return noop10;
}
};
stub3 = new Proxy(noop10, handler3);
stack_utils_default = stub3;
SandboxManager3 = new Proxy({}, { get: () => noop10 });
});
// src/ink/global.d.ts
var init_global_d = () => {};
// src/ink/components/Box.tsx
function Box(t0) {
const $2 = c5(42);
let autoFocus;
let children;
let flexDirection;
let flexGrow;
let flexShrink;
let flexWrap;
let onBlur;
let onBlurCapture;
let onClick;
let onFocus;
let onFocusCapture;
let onKeyDown;
let onKeyDownCapture;
let onMouseEnter;
let onMouseLeave;
let ref;
let style;
let tabIndex;
if ($2[0] !== t0) {
const {
children: t12,
flexWrap: t22,
flexDirection: t32,
flexGrow: t42,
flexShrink: t5,
ref: t6,
tabIndex: t7,
autoFocus: t8,
onClick: t9,
onFocus: t10,
onFocusCapture: t11,
onBlur: t122,
onBlurCapture: t13,
onMouseEnter: t14,
onMouseLeave: t15,
onKeyDown: t16,
onKeyDownCapture: t17,
...t18
} = t0;
children = t12;
ref = t6;
tabIndex = t7;
autoFocus = t8;
onClick = t9;
onFocus = t10;
onFocusCapture = t11;
onBlur = t122;
onBlurCapture = t13;
onMouseEnter = t14;
onMouseLeave = t15;
onKeyDown = t16;
onKeyDownCapture = t17;
style = t18;
flexWrap = t22 === undefined ? "nowrap" : t22;
flexDirection = t32 === undefined ? "row" : t32;
flexGrow = t42 === undefined ? 0 : t42;
flexShrink = t5 === undefined ? 1 : t5;
ifNotInteger(style.margin, "margin");
ifNotInteger(style.marginX, "marginX");
ifNotInteger(style.marginY, "marginY");
ifNotInteger(style.marginTop, "marginTop");
ifNotInteger(style.marginBottom, "marginBottom");
ifNotInteger(style.marginLeft, "marginLeft");
ifNotInteger(style.marginRight, "marginRight");
ifNotInteger(style.padding, "padding");
ifNotInteger(style.paddingX, "paddingX");
ifNotInteger(style.paddingY, "paddingY");
ifNotInteger(style.paddingTop, "paddingTop");
ifNotInteger(style.paddingBottom, "paddingBottom");
ifNotInteger(style.paddingLeft, "paddingLeft");
ifNotInteger(style.paddingRight, "paddingRight");
ifNotInteger(style.gap, "gap");
ifNotInteger(style.columnGap, "columnGap");
ifNotInteger(style.rowGap, "rowGap");
$2[0] = t0;
$2[1] = autoFocus;
$2[2] = children;
$2[3] = flexDirection;
$2[4] = flexGrow;
$2[5] = flexShrink;
$2[6] = flexWrap;
$2[7] = onBlur;
$2[8] = onBlurCapture;
$2[9] = onClick;
$2[10] = onFocus;
$2[11] = onFocusCapture;
$2[12] = onKeyDown;
$2[13] = onKeyDownCapture;
$2[14] = onMouseEnter;
$2[15] = onMouseLeave;
$2[16] = ref;
$2[17] = style;
$2[18] = tabIndex;
} else {
autoFocus = $2[1];
children = $2[2];
flexDirection = $2[3];
flexGrow = $2[4];
flexShrink = $2[5];
flexWrap = $2[6];
onBlur = $2[7];
onBlurCapture = $2[8];
onClick = $2[9];
onFocus = $2[10];
onFocusCapture = $2[11];
onKeyDown = $2[12];
onKeyDownCapture = $2[13];
onMouseEnter = $2[14];
onMouseLeave = $2[15];
ref = $2[16];
style = $2[17];
tabIndex = $2[18];
}
const t1 = style.overflowX ?? style.overflow ?? "visible";
const t2 = style.overflowY ?? style.overflow ?? "visible";
let t3;
if ($2[19] !== flexDirection || $2[20] !== flexGrow || $2[21] !== flexShrink || $2[22] !== flexWrap || $2[23] !== style || $2[24] !== t1 || $2[25] !== t2) {
t3 = {
flexWrap,
flexDirection,
flexGrow,
flexShrink,
...style,
overflowX: t1,
overflowY: t2
};
$2[19] = flexDirection;
$2[20] = flexGrow;
$2[21] = flexShrink;
$2[22] = flexWrap;
$2[23] = style;
$2[24] = t1;
$2[25] = t2;
$2[26] = t3;
} else {
t3 = $2[26];
}
let t4;
if ($2[27] !== autoFocus || $2[28] !== children || $2[29] !== onBlur || $2[30] !== onBlurCapture || $2[31] !== onClick || $2[32] !== onFocus || $2[33] !== onFocusCapture || $2[34] !== onKeyDown || $2[35] !== onKeyDownCapture || $2[36] !== onMouseEnter || $2[37] !== onMouseLeave || $2[38] !== ref || $2[39] !== t3 || $2[40] !== tabIndex) {
t4 = /* @__PURE__ */ jsx_dev_runtime4.jsxDEV("ink-box", {
ref,
tabIndex,
autoFocus,
onClick,
onFocus,
onFocusCapture,
onBlur,
onBlurCapture,
onMouseEnter,
onMouseLeave,
onKeyDown,
onKeyDownCapture,
style: t3,
children
}, undefined, false, undefined, this);
$2[27] = autoFocus;
$2[28] = children;
$2[29] = onBlur;
$2[30] = onBlurCapture;
$2[31] = onClick;
$2[32] = onFocus;
$2[33] = onFocusCapture;
$2[34] = onKeyDown;
$2[35] = onKeyDownCapture;
$2[36] = onMouseEnter;
$2[37] = onMouseLeave;
$2[38] = ref;
$2[39] = t3;
$2[40] = tabIndex;
$2[41] = t4;
} else {
t4 = $2[41];
}
return t4;
}
var jsx_dev_runtime4, Box_default;
var init_Box = __esm(() => {
init_global_d();
init_warn();
jsx_dev_runtime4 = __toESM(require_jsx_dev_runtime(), 1);
Box_default = Box;
});
// src/ink/components/Text.tsx
function Text(t0) {
const $2 = c5(29);
const {
color,
backgroundColor,
bold: bold2,
dim: dim2,
italic: t1,
underline: t2,
strikethrough: t3,
inverse: t4,
wrap: t5,
children
} = t0;
const italic2 = t1 === undefined ? false : t1;
const underline2 = t2 === undefined ? false : t2;
const strikethrough2 = t3 === undefined ? false : t3;
const inverse2 = t4 === undefined ? false : t4;
const wrap = t5 === undefined ? "wrap" : t5;
if (children === undefined || children === null) {
return null;
}
let t6;
if ($2[0] !== color) {
t6 = color && {
color
};
$2[0] = color;
$2[1] = t6;
} else {
t6 = $2[1];
}
let t7;
if ($2[2] !== backgroundColor) {
t7 = backgroundColor && {
backgroundColor
};
$2[2] = backgroundColor;
$2[3] = t7;
} else {
t7 = $2[3];
}
let t8;
if ($2[4] !== dim2) {
t8 = dim2 && {
dim: dim2
};
$2[4] = dim2;
$2[5] = t8;
} else {
t8 = $2[5];
}
let t9;
if ($2[6] !== bold2) {
t9 = bold2 && {
bold: bold2
};
$2[6] = bold2;
$2[7] = t9;
} else {
t9 = $2[7];
}
let t10;
if ($2[8] !== italic2) {
t10 = italic2 && {
italic: italic2
};
$2[8] = italic2;
$2[9] = t10;
} else {
t10 = $2[9];
}
let t11;
if ($2[10] !== underline2) {
t11 = underline2 && {
underline: underline2
};
$2[10] = underline2;
$2[11] = t11;
} else {
t11 = $2[11];
}
let t12;
if ($2[12] !== strikethrough2) {
t12 = strikethrough2 && {
strikethrough: strikethrough2
};
$2[12] = strikethrough2;
$2[13] = t12;
} else {
t12 = $2[13];
}
let t13;
if ($2[14] !== inverse2) {
t13 = inverse2 && {
inverse: inverse2
};
$2[14] = inverse2;
$2[15] = t13;
} else {
t13 = $2[15];
}
let t14;
if ($2[16] !== t10 || $2[17] !== t11 || $2[18] !== t12 || $2[19] !== t13 || $2[20] !== t6 || $2[21] !== t7 || $2[22] !== t8 || $2[23] !== t9) {
t14 = {
...t6,
...t7,
...t8,
...t9,
...t10,
...t11,
...t12,
...t13
};
$2[16] = t10;
$2[17] = t11;
$2[18] = t12;
$2[19] = t13;
$2[20] = t6;
$2[21] = t7;
$2[22] = t8;
$2[23] = t9;
$2[24] = t14;
} else {
t14 = $2[24];
}
const textStyles = t14;
const t15 = memoizedStylesForWrap[wrap];
let t16;
if ($2[25] !== children || $2[26] !== t15 || $2[27] !== textStyles) {
t16 = /* @__PURE__ */ jsx_dev_runtime5.jsxDEV("ink-text", {
style: t15,
textStyles,
children
}, undefined, false, undefined, this);
$2[25] = children;
$2[26] = t15;
$2[27] = textStyles;
$2[28] = t16;
} else {
t16 = $2[28];
}
return t16;
}
var jsx_dev_runtime5, memoizedStylesForWrap;
var init_Text = __esm(() => {
jsx_dev_runtime5 = __toESM(require_jsx_dev_runtime(), 1);
memoizedStylesForWrap = {
wrap: {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "wrap"
},
"wrap-trim": {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "wrap-trim"
},
end: {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "end"
},
middle: {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "middle"
},
"truncate-end": {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "truncate-end"
},
truncate: {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "truncate"
},
"truncate-middle": {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "truncate-middle"
},
"truncate-start": {
flexGrow: 0,
flexShrink: 1,
flexDirection: "row",
textWrap: "truncate-start"
}
};
});
// src/ink/components/ErrorOverview.tsx
import { readFileSync as readFileSync7 } from "fs";
function getStackUtils() {
return stackUtils ??= new stack_utils_default({
cwd: process.cwd(),
internals: stack_utils_default.nodeInternals()
});
}
function ErrorOverview({
error: error44
}) {
const stack = error44.stack ? error44.stack.split(`
`).slice(1) : undefined;
const origin2 = stack ? getStackUtils().parseLine(stack[0]) : undefined;
const filePath = cleanupPath(origin2?.file);
let excerpt;
let lineWidth2 = 0;
if (filePath && origin2?.line) {
try {
const sourceCode = readFileSync7(filePath, "utf8");
excerpt = code_excerpt_default(sourceCode, origin2.line);
if (excerpt) {
for (const {
line
} of excerpt) {
lineWidth2 = Math.max(lineWidth2, String(line).length);
}
}
} catch {}
}
return /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
flexDirection: "column",
padding: 1,
children: [
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
children: [
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
backgroundColor: "ansi:red",
color: "ansi:white",
children: [
" ",
"ERROR",
" "
]
}, undefined, true, undefined, this),
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
children: [
" ",
error44.message
]
}, undefined, true, undefined, this)
]
}, undefined, true, undefined, this),
origin2 && filePath && /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
marginTop: 1,
children: /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
dim: true,
children: [
filePath,
":",
origin2.line,
":",
origin2.column
]
}, undefined, true, undefined, this)
}, undefined, false, undefined, this),
origin2 && excerpt && /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
marginTop: 1,
flexDirection: "column",
children: excerpt.map(({
line: line_0,
value
}) => /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
children: [
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
width: lineWidth2 + 1,
children: /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
dim: line_0 !== origin2.line,
backgroundColor: line_0 === origin2.line ? "ansi:red" : undefined,
color: line_0 === origin2.line ? "ansi:white" : undefined,
children: [
String(line_0).padStart(lineWidth2, " "),
":"
]
}, undefined, true, undefined, this)
}, undefined, false, undefined, this),
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
backgroundColor: line_0 === origin2.line ? "ansi:red" : undefined,
color: line_0 === origin2.line ? "ansi:white" : undefined,
children: " " + value
}, line_0, false, undefined, this)
]
}, line_0, true, undefined, this))
}, undefined, false, undefined, this),
error44.stack && /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
marginTop: 1,
flexDirection: "column",
children: error44.stack.split(`
`).slice(1).map((line_1) => {
const parsedLine = getStackUtils().parseLine(line_1);
if (!parsedLine) {
return /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
children: [
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
dim: true,
children: "- "
}, undefined, false, undefined, this),
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
bold: true,
children: line_1
}, undefined, false, undefined, this)
]
}, line_1, true, undefined, this);
}
return /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
children: [
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
dim: true,
children: "- "
}, undefined, false, undefined, this),
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
bold: true,
children: parsedLine.function
}, undefined, false, undefined, this),
/* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
dim: true,
children: [
" ",
"(",
cleanupPath(parsedLine.file) ?? "",
":",
parsedLine.line,
":",
parsedLine.column,
")"
]
}, undefined, true, undefined, this)
]
}, line_1, true, undefined, this);
})
}, undefined, false, undefined, this)
]
}, undefined, true, undefined, this);
}
var jsx_dev_runtime6, cleanupPath = (path10) => {
return path10?.replace(`file://${process.cwd()}/`, "");
}, stackUtils;
var init_ErrorOverview = __esm(() => {
init_code_excerpt();
init_stack_utils();
init_Box();
init_Text();
jsx_dev_runtime6 = __toESM(require_jsx_dev_runtime(), 1);
});
// src/ink/components/TerminalSizeContext.tsx
var import_react9, TerminalSizeContext;
var init_TerminalSizeContext = __esm(() => {
import_react9 = __toESM(require_react(), 1);
TerminalSizeContext = import_react9.createContext(null);
});
// src/ink/components/App.tsx
function processKeysInBatch(app, items, _unused1, _unused2) {
if (items.some((i2) => i2.kind === "key" || i2.kind === "mouse" && !((i2.button & 32) !== 0 && (i2.button & 3) === 3))) {
updateLastInteractionTime();
}
for (const item of items) {
if (item.kind === "response") {
app.querier.onResponse(item.response);
continue;
}
if (item.kind === "mouse") {
handleMouseEvent(app, item);
continue;
}
const sequence = item.sequence;
if (sequence === FOCUS_IN) {
app.handleTerminalFocus(true);
const event2 = new TerminalFocusEvent("terminalfocus");
app.internal_eventEmitter.emit("terminalfocus", event2);
continue;
}
if (sequence === FOCUS_OUT) {
app.handleTerminalFocus(false);
if (app.props.selection.isDragging) {
finishSelection(app.props.selection);
app.props.onSelectionChange();
}
const event2 = new TerminalFocusEvent("terminalblur");
app.internal_eventEmitter.emit("terminalblur", event2);
continue;
}
if (!getTerminalFocused()) {
setTerminalFocused(true);
}
if (item.name === "z" && item.ctrl && SUPPORTS_SUSPEND) {
app.handleSuspend();
continue;
}
app.handleInput(sequence);
const event = new InputEvent(item);
app.internal_eventEmitter.emit("input", event);
app.props.dispatchKeyboardEvent(item);
}
}
function handleMouseEvent(app, m) {
if (isMouseClicksDisabled())
return;
const sel = app.props.selection;
const col = m.col - 1;
const row = m.row - 1;
const baseButton = m.button & 3;
if (m.action === "press") {
if ((m.button & 32) !== 0 && baseButton === 3) {
if (sel.isDragging) {
finishSelection(sel);
app.props.onSelectionChange();
}
if (col === app.lastHoverCol && row === app.lastHoverRow)
return;
app.lastHoverCol = col;
app.lastHoverRow = row;
app.props.onHoverAt(col, row);
return;
}
if (baseButton !== 0) {
app.clickCount = 0;
return;
}
if ((m.button & 32) !== 0) {
app.props.onSelectionDrag(col, row);
return;
}
if (sel.isDragging) {
finishSelection(sel);
app.props.onSelectionChange();
}
const now2 = Date.now();
const nearLast = now2 - app.lastClickTime < MULTI_CLICK_TIMEOUT_MS && Math.abs(col - app.lastClickCol) <= MULTI_CLICK_DISTANCE && Math.abs(row - app.lastClickRow) <= MULTI_CLICK_DISTANCE;
app.clickCount = nearLast ? app.clickCount + 1 : 1;
app.lastClickTime = now2;
app.lastClickCol = col;
app.lastClickRow = row;
if (app.clickCount >= 2) {
if (app.pendingHyperlinkTimer) {
clearTimeout(app.pendingHyperlinkTimer);
app.pendingHyperlinkTimer = null;
}
const count3 = app.clickCount === 2 ? 2 : 3;
app.props.onMultiClick(col, row, count3);
return;
}
startSelection(sel, col, row);
sel.lastPressHadAlt = (m.button & 8) !== 0;
app.props.onSelectionChange();
return;
}
if (baseButton !== 0) {
if (!sel.isDragging)
return;
finishSelection(sel);
app.props.onSelectionChange();
return;
}
finishSelection(sel);
if (!hasSelection(sel) && sel.anchor) {
if (!app.props.onClickAt(col, row)) {
const url3 = app.props.getHyperlinkAt(col, row);
if (url3 && process.env.TERM_PROGRAM !== "vscode" && !isXtermJs()) {
if (app.pendingHyperlinkTimer) {
clearTimeout(app.pendingHyperlinkTimer);
}
app.pendingHyperlinkTimer = setTimeout((app2, url4) => {
app2.pendingHyperlinkTimer = null;
app2.props.onOpenHyperlink(url4);
}, MULTI_CLICK_TIMEOUT_MS, app, url3);
}
}
}
app.props.onSelectionChange();
}
var import_react10, jsx_dev_runtime7, SUPPORTS_SUSPEND, STDIN_RESUME_GAP_MS = 5000, MULTI_CLICK_TIMEOUT_MS = 500, MULTI_CLICK_DISTANCE = 1, App;
var init_App = __esm(() => {
init_state();
init_debug();
init_earlyInput();
init_envUtils();
init_fullscreen();
init_log3();
init_emitter();
init_input_event();
init_terminal_focus_event();
init_parse_keypress();
init_reconciler();
init_selection();
init_terminal();
init_terminal_focus_state();
init_terminal_querier();
init_csi();
init_dec();
init_AppContext();
init_ClockContext();
init_CursorDeclarationContext();
init_ErrorOverview();
init_StdinContext();
init_TerminalFocusContext();
init_TerminalSizeContext();
import_react10 = __toESM(require_react(), 1);
jsx_dev_runtime7 = __toESM(require_jsx_dev_runtime(), 1);
SUPPORTS_SUSPEND = process.platform !== "win32";
App = class App extends import_react10.PureComponent {
static displayName = "InternalApp";
static getDerivedStateFromError(error44) {
return {
error: error44
};
}
state = {
error: undefined
};
rawModeEnabledCount = 0;
internal_eventEmitter = new EventEmitter3;
keyParseState = INITIAL_STATE;
incompleteEscapeTimer = null;
NORMAL_TIMEOUT = 50;
PASTE_TIMEOUT = 500;
querier = new TerminalQuerier(this.props.stdout);
lastClickTime = 0;
lastClickCol = -1;
lastClickRow = -1;
clickCount = 0;
pendingHyperlinkTimer = null;
lastHoverCol = -1;
lastHoverRow = -1;
lastStdinTime = Date.now();
isRawModeSupported() {
return this.props.stdin.isTTY;
}
render() {
return /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(TerminalSizeContext.Provider, {
value: {
columns: this.props.terminalColumns,
rows: this.props.terminalRows
},
children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(AppContext_default.Provider, {
value: {
exit: this.handleExit
},
children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(StdinContext_default.Provider, {
value: {
stdin: this.props.stdin,
setRawMode: this.handleSetRawMode,
isRawModeSupported: this.isRawModeSupported(),
internal_exitOnCtrlC: this.props.exitOnCtrlC,
internal_eventEmitter: this.internal_eventEmitter,
internal_querier: this.querier
},
children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(TerminalFocusProvider, {
children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(ClockProvider, {
children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(CursorDeclarationContext_default.Provider, {
value: this.props.onCursorDeclaration ?? (() => {}),
children: this.state.error ? /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(ErrorOverview, {
error: this.state.error
}, undefined, false, undefined, this) : this.props.children
}, undefined, false, undefined, this)
}, undefined, false, undefined, this)
}, undefined, false, undefined, this)
}, undefined, false, undefined, this)
}, undefined, false, undefined, this)
}, undefined, false, undefined, this);
}
componentDidMount() {
if (this.props.stdout.isTTY && !isEnvTruthy(process.env.CLAUDE_CODE_ACCESSIBILITY)) {
this.props.stdout.write(HIDE_CURSOR);
}
}
componentWillUnmount() {
if (this.props.stdout.isTTY) {
this.props.stdout.write(SHOW_CURSOR);
}
if (this.incompleteEscapeTimer) {
clearTimeout(this.incompleteEscapeTimer);
this.incompleteEscapeTimer = null;
}
if (this.pendingHyperlinkTimer) {
clearTimeout(this.pendingHyperlinkTimer);
this.pendingHyperlinkTimer = null;
}
if (this.isRawModeSupported()) {
this.handleSetRawMode(false);
}
}
componentDidCatch(error44) {
this.handleExit(error44);
}
handleSetRawMode = (isEnabled) => {
const {
stdin
} = this.props;
if (!this.isRawModeSupported()) {
if (stdin === process.stdin) {
throw new Error(`Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);
} else {
throw new Error(`Raw mode is not supported on the stdin provided to Ink.
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);
}
}
stdin.setEncoding("utf8");
if (isEnabled) {
if (this.rawModeEnabledCount === 0) {
stopCapturingEarlyInput();
stdin.ref();
stdin.setRawMode(true);
stdin.addListener("readable", this.handleReadable);
stdin.resume();
this.props.stdout.write(EBP);
this.props.stdout.write(EFE);
if (supportsExtendedKeys()) {
this.props.stdout.write(ENABLE_KITTY_KEYBOARD);
this.props.stdout.write(ENABLE_MODIFY_OTHER_KEYS);
}
setImmediate(() => {
Promise.all([this.querier.send(xtversion()), this.querier.flush()]).then(([r]) => {
if (r) {
setXtversionName(r.name);
logForDebugging(`XTVERSION: terminal identified as "${r.name}"`);
} else {
logForDebugging("XTVERSION: no reply (terminal ignored query)");
}
});
});
}
this.rawModeEnabledCount++;
return;
}
if (--this.rawModeEnabledCount === 0) {
this.props.stdout.write(DISABLE_MODIFY_OTHER_KEYS);
this.props.stdout.write(DISABLE_KITTY_KEYBOARD);
this.props.stdout.write(DFE);
this.props.stdout.write(DBP);
stdin.setRawMode(false);
stdin.removeListener("readable", this.handleReadable);
stdin.pause();
stdin.unref();
}
};
flushIncomplete = () => {
this.incompleteEscapeTimer = null;
if (!this.keyParseState.incomplete)
return;
if (this.props.stdin.readableLength > 0) {
this.incompleteEscapeTimer = setTimeout(this.flushIncomplete, this.NORMAL_TIMEOUT);
return;
}
this.processInput(null);
};
processInput = (input) => {
const [keys2, newState] = parseMultipleKeypresses(this.keyParseState, input);
this.keyParseState = newState;
if (keys2.length > 0) {
reconciler_default.discreteUpdates(processKeysInBatch, this, keys2, undefined, undefined);
}
if (this.keyParseState.incomplete) {
if (this.incompleteEscapeTimer) {
clearTimeout(this.incompleteEscapeTimer);
}
this.incompleteEscapeTimer = setTimeout(this.flushIncomplete, this.keyParseState.mode === "IN_PASTE" ? this.PASTE_TIMEOUT : this.NORMAL_TIMEOUT);
}
};
handleReadable = () => {
const now2 = Date.now();
if (now2 - this.lastStdinTime > STDIN_RESUME_GAP_MS) {
this.props.onStdinResume?.();
}
this.lastStdinTime = now2;
try {
let chunk;
while ((chunk = this.props.stdin.read()) !== null) {
this.processInput(chunk);
}
} catch (error44) {
logError2(error44);
const {
stdin
} = this.props;
if (this.rawModeEnabledCount > 0 && !stdin.listeners("readable").includes(this.handleReadable)) {
logForDebugging("handleReadable: re-attaching stdin readable listener after error recovery", {
level: "warn"
});
stdin.addListener("readable", this.handleReadable);
}
}
};
handleInput = (input) => {
if (input === "\x03" && this.props.exitOnCtrlC) {
this.handleExit();
}
};
handleExit = (error44) => {
if (this.isRawModeSupported()) {
this.handleSetRawMode(false);
}
this.props.onExit(error44);
};
handleTerminalFocus = (isFocused) => {
setTerminalFocused(isFocused);
};
handleSuspend = () => {
if (!this.isRawModeSupported()) {
return;
}
const rawModeCountBeforeSuspend = this.rawModeEnabledCount;
while (this.rawModeEnabledCount > 0) {
this.handleSetRawMode(false);
}
if (this.props.stdout.isTTY) {
this.props.stdout.write(SHOW_CURSOR + DFE + DISABLE_MOUSE_TRACKING);
}
this.internal_eventEmitter.emit("suspend");
const resumeHandler = () => {
for (let i2 = 0;i2 < rawModeCountBeforeSuspend; i2++) {
if (this.isRawModeSupported()) {
this.handleSetRawMode(true);
}
}
if (this.props.stdout.isTTY) {
if (!isEnvTruthy(process.env.CLAUDE_CODE_ACCESSIBILITY)) {
this.props.stdout.write(HIDE_CURSOR);
}
this.props.stdout.write(EFE);
}
this.internal_eventEmitter.emit("resume");
process.removeListener("SIGCONT", resumeHandler);
};
process.on("SIGCONT", resumeHandler);
process.kill(process.pid, "SIGSTOP");
};
};
});
// src/ink/events/keyboard-event.ts
function keyFromParsed(parsed) {
const seq = parsed.sequence ?? "";
const name = parsed.name ?? "";
if (parsed.ctrl)
return name;
if (seq.length === 1) {
const code = seq.charCodeAt(0);
if (code >= 32 && code !== 127)
return seq;
}
return name || seq;
}
var KeyboardEvent;
var init_keyboard_event = __esm(() => {
init_terminal_event();
KeyboardEvent = class KeyboardEvent extends TerminalEvent {
key;
ctrl;
shift;
meta;
superKey;
fn;
constructor(parsedKey) {
super("keydown", { bubbles: true, cancelable: true });
this.key = keyFromParsed(parsedKey);
this.ctrl = parsedKey.ctrl;
this.shift = parsedKey.shift;
this.meta = parsedKey.meta || parsedKey.option;
this.superKey = parsedKey.super;
this.fn = parsedKey.fn;
}
};
});
// src/ink/frame.ts
function emptyFrame(rows, columns, stylePool, charPool, hyperlinkPool) {
return {
screen: createScreen(0, 0, stylePool, charPool, hyperlinkPool),
viewport: { width: columns, height: rows },
cursor: { x: 0, y: 0, visible: true }
};
}
var init_frame = __esm(() => {
init_screen();
});
// src/ink/events/click-event.ts
var ClickEvent;
var init_click_event = __esm(() => {
ClickEvent = class ClickEvent extends Event2 {
col;
row;
localCol = 0;
localRow = 0;
cellIsBlank;
constructor(col, row, cellIsBlank) {
super();
this.col = col;
this.row = row;
this.cellIsBlank = cellIsBlank;
}
};
});
// src/ink/hit-test.ts
function hitTest(node, col, row) {
const rect = nodeCache.get(node);
if (!rect)
return null;
if (col < rect.x || col >= rect.x + rect.width || row < rect.y || row >= rect.y + rect.height) {
return null;
}
for (let i2 = node.childNodes.length - 1;i2 >= 0; i2--) {
const child = node.childNodes[i2];
if (child.nodeName === "#text")
continue;
const hit = hitTest(child, col, row);
if (hit)
return hit;
}
return node;
}
function dispatchClick(root2, col, row, cellIsBlank = false) {
let target = hitTest(root2, col, row) ?? undefined;
if (!target)
return false;
if (root2.focusManager) {
let focusTarget = target;
while (focusTarget) {
if (typeof focusTarget.attributes["tabIndex"] === "number") {
root2.focusManager.handleClickFocus(focusTarget);
break;
}
focusTarget = focusTarget.parentNode;
}
}
const event = new ClickEvent(col, row, cellIsBlank);
let handled = false;
while (target) {
const handler4 = target._eventHandlers?.onClick;
if (handler4) {
handled = true;
const rect = nodeCache.get(target);
if (rect) {
event.localCol = col - rect.x;
event.localRow = row - rect.y;
}
handler4(event);
if (event.didStopImmediatePropagation())
return true;
}
target = target.parentNode;
}
return handled;
}
function dispatchHover(root2, col, row, hovered) {
const next = new Set;
let node = hitTest(root2, col, row) ?? undefined;
while (node) {
const h2 = node._eventHandlers;
if (h2?.onMouseEnter || h2?.onMouseLeave)
next.add(node);
node = node.parentNode;
}
for (const old of hovered) {
if (!next.has(old)) {
hovered.delete(old);
if (old.parentNode) {
old._eventHandlers?.onMouseLeave?.();
}
}
}
for (const n2 of next) {
if (!hovered.has(n2)) {
hovered.add(n2);
n2._eventHandlers?.onMouseEnter?.();
}
}
}
var init_hit_test = __esm(() => {
init_click_event();
init_node_cache();
});
// src/ink/instances.ts
var instances, instances_default;
var init_instances = __esm(() => {
instances = new Map;
instances_default = instances;
});
// src/ink/log-update.ts
class LogUpdate {
options;
state;
constructor(options) {
this.options = options;
this.state = {
previousOutput: ""
};
}
renderPreviousOutput_DEPRECATED(prevFrame) {
if (!this.options.isTTY) {
return [NEWLINE];
}
return this.getRenderOpsForDone(prevFrame);
}
reset() {
this.state.previousOutput = "";
}
renderFullFrame(frame) {
const { screen } = frame;
const lines = [];
let currentStyles = [];
let currentHyperlink = undefined;
for (let y2 = 0;y2 < screen.height; y2++) {
let line = "";
for (let x2 = 0;x2 < screen.width; x2++) {
const cell = cellAt(screen, x2, y2);
if (cell && cell.width !== 2 /* SpacerTail */) {
if (cell.hyperlink !== currentHyperlink) {
if (currentHyperlink !== undefined) {
line += LINK_END;
}
if (cell.hyperlink !== undefined) {
line += link(cell.hyperlink);
}
currentHyperlink = cell.hyperlink;
}
const cellStyles = this.options.stylePool.get(cell.styleId);
const styleDiff = diffAnsiCodes(currentStyles, cellStyles);
if (styleDiff.length > 0) {
line += ansiCodesToString(styleDiff);
currentStyles = cellStyles;
}
line += cell.char;
}
}
if (currentHyperlink !== undefined) {
line += LINK_END;
currentHyperlink = undefined;
}
const resetCodes = diffAnsiCodes(currentStyles, []);
if (resetCodes.length > 0) {
line += ansiCodesToString(resetCodes);
currentStyles = [];
}
lines.push(line.trimEnd());
}
if (lines.length === 0) {
return [];
}
return [{ type: "stdout", content: lines.join(`
`) }];
}
getRenderOpsForDone(prev) {
this.state.previousOutput = "";
if (!prev.cursor.visible) {
return [{ type: "cursorShow" }];
}
return [];
}
render(prev, next, altScreen = false, decstbmSafe = true) {
if (!this.options.isTTY) {
return this.renderFullFrame(next);
}
const startTime = performance.now();
const stylePool = this.options.stylePool;
if (next.viewport.height < prev.viewport.height || prev.viewport.width !== 0 && next.viewport.width !== prev.viewport.width) {
return fullResetSequence_CAUSES_FLICKER(next, "resize", stylePool);
}
let scrollPatch = [];
if (altScreen && next.scrollHint && decstbmSafe) {
const { top, bottom, delta } = next.scrollHint;
if (top >= 0 && bottom < prev.screen.height && bottom < next.screen.height) {
shiftRows(prev.screen, top, bottom, delta);
scrollPatch = [
{
type: "stdout",
content: setScrollRegion(top + 1, bottom + 1) + (delta > 0 ? scrollUp(delta) : scrollDown(-delta)) + RESET_SCROLL_REGION + CURSOR_HOME
}
];
}
}
const cursorAtBottom = prev.cursor.y >= prev.screen.height;
const isGrowing = next.screen.height > prev.screen.height;
const prevHadScrollback = cursorAtBottom && prev.screen.height >= prev.viewport.height;
const isShrinking = next.screen.height < prev.screen.height;
const nextFitsViewport = next.screen.height <= prev.viewport.height;
if (prevHadScrollback && nextFitsViewport && isShrinking) {
logForDebugging(`Full reset (shrink->below): prevHeight=${prev.screen.height}, nextHeight=${next.screen.height}, viewport=${prev.viewport.height}`);
return fullResetSequence_CAUSES_FLICKER(next, "offscreen", stylePool);
}
if (prev.screen.height >= prev.viewport.height && prev.screen.height > 0 && cursorAtBottom && !isGrowing) {
const viewportY2 = prev.screen.height - prev.viewport.height;
const scrollbackRows = viewportY2 + 1;
let scrollbackChangeY = -1;
diffEach(prev.screen, next.screen, (_x, y2) => {
if (y2 < scrollbackRows) {
scrollbackChangeY = y2;
return true;
}
});
if (scrollbackChangeY >= 0) {
const prevLine = readLine(prev.screen, scrollbackChangeY);
const nextLine = readLine(next.screen, scrollbackChangeY);
return fullResetSequence_CAUSES_FLICKER(next, "offscreen", stylePool, {
triggerY: scrollbackChangeY,
prevLine,
nextLine
});
}
}
const screen = new VirtualScreen(prev.cursor, next.viewport.width);
const heightDelta = Math.max(next.screen.height, 1) - Math.max(prev.screen.height, 1);
const shrinking = heightDelta < 0;
const growing = heightDelta > 0;
if (shrinking) {
const linesToClear = prev.screen.height - next.screen.height;
if (linesToClear > prev.viewport.height) {
return fullResetSequence_CAUSES_FLICKER(next, "offscreen", this.options.stylePool);
}
screen.txn((prev2) => [
[
{ type: "clear", count: linesToClear },
{ type: "cursorMove", x: 0, y: -1 }
],
{ dx: -prev2.x, dy: -linesToClear }
]);
}
const cursorRestoreScroll = prevHadScrollback ? 1 : 0;
const viewportY = growing ? Math.max(0, prev.screen.height - prev.viewport.height + cursorRestoreScroll) : Math.max(prev.screen.height, next.screen.height) - next.viewport.height + cursorRestoreScroll;
let currentStyleId = stylePool.none;
let currentHyperlink = undefined;
let needsFullReset = false;
let resetTriggerY = -1;
diffEach(prev.screen, next.screen, (x2, y2, removed, added) => {
if (growing && y2 >= prev.screen.height) {
return;
}
if (added && (added.width === 2 /* SpacerTail */ || added.width === 3 /* SpacerHead */)) {
return;
}
if (removed && (removed.width === 2 /* SpacerTail */ || removed.width === 3 /* SpacerHead */) && !added) {
return;
}
if (added && isEmptyCellAt(next.screen, x2, y2) && !removed) {
return;
}
if (y2 < viewportY) {
needsFullReset = true;
resetTriggerY = y2;
return true;
}
moveCursorTo(screen, x2, y2);
if (added) {
const targetHyperlink = added.hyperlink;
currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, targetHyperlink);
const styleStr = stylePool.transition(currentStyleId, added.styleId);
if (writeCellWithStyleStr(screen, added, styleStr)) {
currentStyleId = added.styleId;
}
} else if (removed) {
const styleIdToReset = currentStyleId;
const hyperlinkToReset = currentHyperlink;
currentStyleId = stylePool.none;
currentHyperlink = undefined;
screen.txn(() => {
const patches = [];
transitionStyle(patches, stylePool, styleIdToReset, stylePool.none);
transitionHyperlink(patches, hyperlinkToReset, undefined);
patches.push({ type: "stdout", content: " " });
return [patches, { dx: 1, dy: 0 }];
});
}
});
if (needsFullReset) {
return fullResetSequence_CAUSES_FLICKER(next, "offscreen", stylePool, {
triggerY: resetTriggerY,
prevLine: readLine(prev.screen, resetTriggerY),
nextLine: readLine(next.screen, resetTriggerY)
});
}
currentStyleId = transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none);
currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, undefined);
if (growing) {
renderFrameSlice(screen, next, prev.screen.height, next.screen.height, stylePool);
}
if (altScreen) {} else if (next.cursor.y >= next.screen.height) {
screen.txn((prev2) => {
const rowsToCreate = next.cursor.y - prev2.y;
if (rowsToCreate > 0) {
const patches = new Array(1 + rowsToCreate);
patches[0] = CARRIAGE_RETURN;
for (let i2 = 0;i2 < rowsToCreate; i2++) {
patches[1 + i2] = NEWLINE;
}
return [patches, { dx: -prev2.x, dy: rowsToCreate }];
}
const dy = next.cursor.y - prev2.y;
if (dy !== 0 || prev2.x !== next.cursor.x) {
const patches = [CARRIAGE_RETURN];
patches.push({ type: "cursorMove", x: next.cursor.x, y: dy });
return [patches, { dx: next.cursor.x - prev2.x, dy }];
}
return [[], { dx: 0, dy: 0 }];
});
} else {
moveCursorTo(screen, next.cursor.x, next.cursor.y);
}
const elapsed = performance.now() - startTime;
if (elapsed > 50) {
const damage = next.screen.damage;
const damageInfo = damage ? `${damage.width}x${damage.height} at (${damage.x},${damage.y})` : "none";
logForDebugging(`Slow render: ${elapsed.toFixed(1)}ms, screen: ${next.screen.height}x${next.screen.width}, damage: ${damageInfo}, changes: ${screen.diff.length}`);
}
return scrollPatch.length > 0 ? [...scrollPatch, ...screen.diff] : screen.diff;
}
}
function transitionHyperlink(diff2, current, target) {
if (current !== target) {
diff2.push({ type: "hyperlink", uri: target ?? "" });
return target;
}
return current;
}
function transitionStyle(diff2, stylePool, currentId, targetId) {
const str = stylePool.transition(currentId, targetId);
if (str.length > 0) {
diff2.push({ type: "styleStr", str });
}
return targetId;
}
function readLine(screen, y2) {
let line = "";
for (let x2 = 0;x2 < screen.width; x2++) {
line += charInCellAt(screen, x2, y2) ?? " ";
}
return line.trimEnd();
}
function fullResetSequence_CAUSES_FLICKER(frame, reason, stylePool, debug) {
const screen = new VirtualScreen({ x: 0, y: 0 }, frame.viewport.width);
renderFrame(screen, frame, stylePool);
return [{ type: "clearTerminal", reason, debug }, ...screen.diff];
}
function renderFrame(screen, frame, stylePool) {
renderFrameSlice(screen, frame, 0, frame.screen.height, stylePool);
}
function renderFrameSlice(screen, frame, startY, endY, stylePool) {
let currentStyleId = stylePool.none;
let currentHyperlink = undefined;
let lastRenderedStyleId = -1;
const { width: screenWidth, cells, charPool, hyperlinkPool } = frame.screen;
let index = startY * screenWidth;
for (let y2 = startY;y2 < endY; y2 += 1) {
if (screen.cursor.y < y2) {
const rowsToAdvance = y2 - screen.cursor.y;
screen.txn((prev) => {
const patches = new Array(1 + rowsToAdvance);
patches[0] = CARRIAGE_RETURN;
for (let i2 = 0;i2 < rowsToAdvance; i2++) {
patches[1 + i2] = NEWLINE;
}
return [patches, { dx: -prev.x, dy: rowsToAdvance }];
});
}
lastRenderedStyleId = -1;
for (let x2 = 0;x2 < screenWidth; x2 += 1, index += 1) {
const cell = visibleCellAtIndex(cells, charPool, hyperlinkPool, index, lastRenderedStyleId);
if (!cell) {
continue;
}
moveCursorTo(screen, x2, y2);
const targetHyperlink = cell.hyperlink;
currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, targetHyperlink);
const styleStr = stylePool.transition(currentStyleId, cell.styleId);
if (writeCellWithStyleStr(screen, cell, styleStr)) {
currentStyleId = cell.styleId;
lastRenderedStyleId = cell.styleId;
}
}
currentStyleId = transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none);
currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, undefined);
screen.txn((prev) => [[CARRIAGE_RETURN, NEWLINE], { dx: -prev.x, dy: 1 }]);
}
transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none);
transitionHyperlink(screen.diff, currentHyperlink, undefined);
return screen;
}
function writeCellWithStyleStr(screen, cell, styleStr) {
const cellWidth = cell.width === 1 /* Wide */ ? 2 : 1;
const px = screen.cursor.x;
const vw = screen.viewportWidth;
if (cellWidth === 2 && px < vw) {
const threshold = cell.char.length > 2 ? vw : vw + 1;
if (px + 2 >= threshold) {
return false;
}
}
const diff2 = screen.diff;
if (styleStr.length > 0) {
diff2.push({ type: "styleStr", str: styleStr });
}
const needsCompensation = cellWidth === 2 && needsWidthCompensation(cell.char);
if (needsCompensation && px + 1 < vw) {
diff2.push({ type: "cursorTo", col: px + 2 });
diff2.push({ type: "stdout", content: " " });
diff2.push({ type: "cursorTo", col: px + 1 });
}
diff2.push({ type: "stdout", content: cell.char });
if (needsCompensation) {
diff2.push({ type: "cursorTo", col: px + cellWidth + 1 });
}
if (px >= vw) {
screen.cursor.x = cellWidth;
screen.cursor.y++;
} else {
screen.cursor.x = px + cellWidth;
}
return true;
}
function moveCursorTo(screen, targetX, targetY) {
screen.txn((prev) => {
const dx = targetX - prev.x;
const dy = targetY - prev.y;
const inPendingWrap = prev.x >= screen.viewportWidth;
if (inPendingWrap) {
return [
[CARRIAGE_RETURN, { type: "cursorMove", x: targetX, y: dy }],
{ dx, dy }
];
}
if (dy !== 0) {
return [
[CARRIAGE_RETURN, { type: "cursorMove", x: targetX, y: dy }],
{ dx, dy }
];
}
return [[{ type: "cursorMove", x: dx, y: dy }], { dx, dy }];
});
}
function needsWidthCompensation(char) {
const cp = char.codePointAt(0);
if (cp === undefined)
return false;
if (cp >= 129648 && cp <= 129791 || cp >= 129792 && cp <= 130047) {
return true;
}
if (char.length >= 2) {
for (let i2 = 0;i2 < char.length; i2++) {
if (char.charCodeAt(i2) === 65039)
return true;
}
}
return false;
}
class VirtualScreen {
viewportWidth;
cursor;
diff = [];
constructor(origin2, viewportWidth) {
this.viewportWidth = viewportWidth;
this.cursor = { ...origin2 };
}
txn(fn) {
const [patches, next] = fn(this.cursor);
for (const patch of patches) {
this.diff.push(patch);
}
this.cursor.x += next.dx;
this.cursor.y += next.dy;
}
}
var CARRIAGE_RETURN, NEWLINE;
var init_log_update = __esm(() => {
init_build();
init_debug();
init_screen();
init_csi();
init_osc();
CARRIAGE_RETURN = { type: "carriageReturn" };
NEWLINE = { type: "stdout", content: `
` };
});
// src/ink/optimizer.ts
function optimize(diff2) {
if (diff2.length <= 1) {
return diff2;
}
const result = [];
let len = 0;
for (const patch of diff2) {
const type = patch.type;
if (type === "stdout") {
if (patch.content === "")
continue;
} else if (type === "cursorMove") {
if (patch.x === 0 && patch.y === 0)
continue;
} else if (type === "clear") {
if (patch.count === 0)
continue;
}
if (len > 0) {
const lastIdx = len - 1;
const last = result[lastIdx];
const lastType = last.type;
if (type === "cursorMove" && lastType === "cursorMove") {
result[lastIdx] = {
type: "cursorMove",
x: last.x + patch.x,
y: last.y + patch.y
};
continue;
}
if (type === "cursorTo" && lastType === "cursorTo") {
result[lastIdx] = patch;
continue;
}
if (type === "styleStr" && lastType === "styleStr") {
result[lastIdx] = { type: "styleStr", str: last.str + patch.str };
continue;
}
if (type === "hyperlink" && lastType === "hyperlink" && patch.uri === last.uri) {
continue;
}
if (type === "cursorShow" && lastType === "cursorHide" || type === "cursorHide" && lastType === "cursorShow") {
result.pop();
len--;
continue;
}
}
result.push(patch);
len++;
}
return result;
}
// node_modules/bidi-js/dist/bidi.js
var require_bidi = __commonJS((exports, module) => {
(function(global3, factory2) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory2() : typeof define === "function" && define.amd ? define(factory2) : (global3 = typeof globalThis !== "undefined" ? globalThis : global3 || self, global3.bidi_js = factory2());
})(exports, function() {
function bidiFactory() {
var bidi = function(exports2) {
var DATA = {
R: "13k,1a,2,3,3,2+1j,ch+16,a+1,5+2,2+n,5,a,4,6+16,4+3,h+1b,4mo,179q,2+9,2+11,2i9+7y,2+68,4,3+4,5+13,4+3,2+4k,3+29,8+cf,1t+7z,w+17,3+3m,1t+3z,16o1+5r,8+30,8+mc,29+1r,29+4v,75+73",
EN: "1c+9,3d+1,6,187+9,513,4+5,7+9,sf+j,175h+9,qw+q,161f+1d,4xt+a,25i+9",
ES: "17,2,6dp+1,f+1,av,16vr,mx+1,4o,2",
ET: "z+2,3h+3,b+1,ym,3e+1,2o,p4+1,8,6u,7c,g6,1wc,1n9+4,30+1b,2n,6d,qhx+1,h0m,a+1,49+2,63+1,4+1,6bb+3,12jj",
AN: "16o+5,2j+9,2+1,35,ed,1ff2+9,87+u",
CS: "18,2+1,b,2u,12k,55v,l,17v0,2,3,53,2+1,b",
B: "a,3,f+2,2v,690",
S: "9,2,k",
WS: "c,k,4f4,1vk+a,u,1j,335",
ON: "x+1,4+4,h+5,r+5,r+3,z,5+3,2+1,2+1,5,2+2,3+4,o,w,ci+1,8+d,3+d,6+8,2+g,39+1,9,6+1,2,33,b8,3+1,3c+1,7+1,5r,b,7h+3,sa+5,2,3i+6,jg+3,ur+9,2v,ij+1,9g+9,7+a,8m,4+1,49+x,14u,2+2,c+2,e+2,e+2,e+1,i+n,e+e,2+p,u+2,e+2,36+1,2+3,2+1,b,2+2,6+5,2,2,2,h+1,5+4,6+3,3+f,16+2,5+3l,3+81,1y+p,2+40,q+a,m+13,2r+ch,2+9e,75+hf,3+v,2+2w,6e+5,f+6,75+2a,1a+p,2+2g,d+5x,r+b,6+3,4+o,g,6+1,6+2,2k+1,4,2j,5h+z,1m+1,1e+f,t+2,1f+e,d+3,4o+3,2s+1,w,535+1r,h3l+1i,93+2,2s,b+1,3l+x,2v,4g+3,21+3,kz+1,g5v+1,5a,j+9,n+v,2,3,2+8,2+1,3+2,2,3,46+1,4+4,h+5,r+5,r+a,3h+2,4+6,b+4,78,1r+24,4+c,4,1hb,ey+6,103+j,16j+c,1ux+7,5+g,fsh,jdq+1t,4,57+2e,p1,1m,1m,1m,1m,4kt+1,7j+17,5+2r,d+e,3+e,2+e,2+10,m+4,w,1n+5,1q,4z+5,4b+rb,9+c,4+c,4+37,d+2g,8+b,l+b,5+1j,9+9,7+13,9+t,3+1,27+3c,2+29,2+3q,d+d,3+4,4+2,6+6,a+o,8+6,a+2,e+6,16+42,2+1i",
BN: "0+8,6+d,2s+5,2+p,e,4m9,1kt+2,2b+5,5+5,17q9+v,7k,6p+8,6+1,119d+3,440+7,96s+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+75,6p+2rz,1ben+1,1ekf+1,1ekf+1",
NSM: "lc+33,7o+6,7c+18,2,2+1,2+1,2,21+a,1d+k,h,2u+6,3+5,3+1,2+3,10,v+q,2k+a,1n+8,a,p+3,2+8,2+2,2+4,18+2,3c+e,2+v,1k,2,5+7,5,4+6,b+1,u,1n,5+3,9,l+1,r,3+1,1m,5+1,5+1,3+2,4,v+1,4,c+1,1m,5+4,2+1,5,l+1,n+5,2,1n,3,2+3,9,8+1,c+1,v,1q,d,1f,4,1m+2,6+2,2+3,8+1,c+1,u,1n,g+1,l+1,t+1,1m+1,5+3,9,l+1,u,21,8+2,2,2j,3+6,d+7,2r,3+8,c+5,23+1,s,2,2,1k+d,2+4,2+1,6+a,2+z,a,2v+3,2+5,2+1,3+1,q+1,5+2,h+3,e,3+1,7,g,jk+2,qb+2,u+2,u+1,v+1,1t+1,2+6,9,3+a,a,1a+2,3c+1,z,3b+2,5+1,a,7+2,64+1,3,1n,2+6,2,2,3+7,7+9,3,1d+g,1s+3,1d,2+4,2,6,15+8,d+1,x+3,3+1,2+2,1l,2+1,4,2+2,1n+7,3+1,49+2,2+c,2+6,5,7,4+1,5j+1l,2+4,k1+w,2db+2,3y,2p+v,ff+3,30+1,n9x+3,2+9,x+1,29+1,7l,4,5,q+1,6,48+1,r+h,e,13+7,q+a,1b+2,1d,3+3,3+1,14,1w+5,3+1,3+1,d,9,1c,1g,2+2,3+1,6+1,2,17+1,9,6n,3,5,fn5,ki+f,h+f,r2,6b,46+4,1af+2,2+1,6+3,15+2,5,4m+1,fy+3,as+1,4a+a,4x,1j+e,1l+2,1e+3,3+1,1y+2,11+4,2+7,1r,d+1,1h+8,b+3,3,2o+2,3,2+1,7,4h,4+7,m+1,1m+1,4,12+6,4+4,5g+7,3+2,2,o,2d+5,2,5+1,2+1,6n+3,7+1,2+1,s+1,2e+7,3,2+1,2z,2,3+5,2,2u+2,3+3,2+4,78+8,2+1,75+1,2,5,41+3,3+1,5,x+5,3+1,15+5,3+3,9,a+5,3+2,1b+c,2+1,bb+6,2+5,2d+l,3+6,2+1,2+1,3f+5,4,2+1,2+6,2,21+1,4,2,9o+1,f0c+4,1o+6,t5,1s+3,2a,f5l+1,43t+2,i+7,3+6,v+3,45+2,1j0+1i,5+1d,9,f,n+4,2+e,11t+6,2+g,3+6,2+1,2+4,7a+6,c6+3,15t+6,32+6,gzhy+6n",
AL: "16w,3,2,e+1b,z+2,2+2s,g+1,8+1,b+m,2+t,s+2i,c+e,4h+f,1d+1e,1bwe+dp,3+3z,x+c,2+1,35+3y,2rm+z,5+7,b+5,dt+l,c+u,17nl+27,1t+27,4x+6n,3+d",
LRO: "6ct",
RLO: "6cu",
LRE: "6cq",
RLE: "6cr",
PDF: "6cs",
LRI: "6ee",
RLI: "6ef",
FSI: "6eg",
PDI: "6eh"
};
var TYPES = {};
var TYPES_TO_NAMES = {};
TYPES.L = 1;
TYPES_TO_NAMES[1] = "L";
Object.keys(DATA).forEach(function(type, i2) {
TYPES[type] = 1 << i2 + 1;
TYPES_TO_NAMES[TYPES[type]] = type;
});
Object.freeze(TYPES);
var ISOLATE_INIT_TYPES = TYPES.LRI | TYPES.RLI | TYPES.FSI;
var STRONG_TYPES = TYPES.L | TYPES.R | TYPES.AL;
var NEUTRAL_ISOLATE_TYPES = TYPES.B | TYPES.S | TYPES.WS | TYPES.ON | TYPES.FSI | TYPES.LRI | TYPES.RLI | TYPES.PDI;
var BN_LIKE_TYPES = TYPES.BN | TYPES.RLE | TYPES.LRE | TYPES.RLO | TYPES.LRO | TYPES.PDF;
var TRAILING_TYPES = TYPES.S | TYPES.WS | TYPES.B | ISOLATE_INIT_TYPES | TYPES.PDI | BN_LIKE_TYPES;
var map3 = null;
function parseData() {
if (!map3) {
map3 = new Map;
var loop = function(type2) {
if (DATA.hasOwnProperty(type2)) {
var lastCode = 0;
DATA[type2].split(",").forEach(function(range) {
var ref = range.split("+");
var skip = ref[0];
var step = ref[1];
skip = parseInt(skip, 36);
step = step ? parseInt(step, 36) : 0;
map3.set(lastCode += skip, TYPES[type2]);
for (var i2 = 0;i2 < step; i2++) {
map3.set(++lastCode, TYPES[type2]);
}
});
}
};
for (var type in DATA)
loop(type);
}
}
function getBidiCharType(char) {
parseData();
return map3.get(char.codePointAt(0)) || TYPES.L;
}
function getBidiCharTypeName(char) {
return TYPES_TO_NAMES[getBidiCharType(char)];
}
var data$1 = {
pairs: "14>1,1e>2,u>2,2wt>1,1>1,1ge>1,1wp>1,1j>1,f>1,hm>1,1>1,u>1,u6>1,1>1,+5,28>1,w>1,1>1,+3,b8>1,1>1,+3,1>3,-1>-1,3>1,1>1,+2,1s>1,1>1,x>1,th>1,1>1,+2,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,4q>1,1e>2,u>2,2>1,+1",
canonical: "6f1>-6dx,6dy>-6dx,6ec>-6ed,6ee>-6ed,6ww>2jj,-2ji>2jj,14r4>-1e7l,1e7m>-1e7l,1e7m>-1e5c,1e5d>-1e5b,1e5c>-14qx,14qy>-14qx,14vn>-1ecg,1ech>-1ecg,1edu>-1ecg,1eci>-1ecg,1eda>-1ecg,1eci>-1ecg,1eci>-168q,168r>-168q,168s>-14ye,14yf>-14ye"
};
function parseCharacterMap(encodedString, includeReverse) {
var radix = 36;
var lastCode = 0;
var map4 = new Map;
var reverseMap = includeReverse && new Map;
var prevPair;
encodedString.split(",").forEach(function visit2(entry) {
if (entry.indexOf("+") !== -1) {
for (var i2 = +entry;i2--; ) {
visit2(prevPair);
}
} else {
prevPair = entry;
var ref = entry.split(">");
var a2 = ref[0];
var b = ref[1];
a2 = String.fromCodePoint(lastCode += parseInt(a2, radix));
b = String.fromCodePoint(lastCode += parseInt(b, radix));
map4.set(a2, b);
includeReverse && reverseMap.set(b, a2);
}
});
return { map: map4, reverseMap };
}
var openToClose, closeToOpen, canonical;
function parse$1() {
if (!openToClose) {
var ref = parseCharacterMap(data$1.pairs, true);
var map4 = ref.map;
var reverseMap = ref.reverseMap;
openToClose = map4;
closeToOpen = reverseMap;
canonical = parseCharacterMap(data$1.canonical, false).map;
}
}
function openingToClosingBracket(char) {
parse$1();
return openToClose.get(char) || null;
}
function closingToOpeningBracket(char) {
parse$1();
return closeToOpen.get(char) || null;
}
function getCanonicalBracket(char) {
parse$1();
return canonical.get(char) || null;
}
var TYPE_L = TYPES.L;
var TYPE_R = TYPES.R;
var TYPE_EN = TYPES.EN;
var TYPE_ES = TYPES.ES;
var TYPE_ET = TYPES.ET;
var TYPE_AN = TYPES.AN;
var TYPE_CS = TYPES.CS;
var TYPE_B = TYPES.B;
var TYPE_S = TYPES.S;
var TYPE_ON = TYPES.ON;
var TYPE_BN = TYPES.BN;
var TYPE_NSM = TYPES.NSM;
var TYPE_AL = TYPES.AL;
var TYPE_LRO = TYPES.LRO;
var TYPE_RLO = TYPES.RLO;
var TYPE_LRE = TYPES.LRE;
var TYPE_RLE = TYPES.RLE;
var TYPE_PDF = TYPES.PDF;
var TYPE_LRI = TYPES.LRI;
var TYPE_RLI = TYPES.RLI;
var TYPE_FSI = TYPES.FSI;
var TYPE_PDI = TYPES.PDI;
function getEmbeddingLevels(string4, baseDirection) {
var MAX_DEPTH = 125;
var charTypes = new Uint32Array(string4.length);
for (var i2 = 0;i2 < string4.length; i2++) {
charTypes[i2] = getBidiCharType(string4[i2]);
}
var charTypeCounts = new Map;
function changeCharType(i3, type2) {
var oldType = charTypes[i3];
charTypes[i3] = type2;
charTypeCounts.set(oldType, charTypeCounts.get(oldType) - 1);
if (oldType & NEUTRAL_ISOLATE_TYPES) {
charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) - 1);
}
charTypeCounts.set(type2, (charTypeCounts.get(type2) || 0) + 1);
if (type2 & NEUTRAL_ISOLATE_TYPES) {
charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1);
}
}
var embedLevels = new Uint8Array(string4.length);
var isolationPairs = new Map;
var paragraphs = [];
var paragraph = null;
for (var i$1 = 0;i$1 < string4.length; i$1++) {
if (!paragraph) {
paragraphs.push(paragraph = {
start: i$1,
end: string4.length - 1,
level: baseDirection === "rtl" ? 1 : baseDirection === "ltr" ? 0 : determineAutoEmbedLevel(i$1, false)
});
}
if (charTypes[i$1] & TYPE_B) {
paragraph.end = i$1;
paragraph = null;
}
}
var FORMATTING_TYPES = TYPE_RLE | TYPE_LRE | TYPE_RLO | TYPE_LRO | ISOLATE_INIT_TYPES | TYPE_PDI | TYPE_PDF | TYPE_B;
var nextEven = function(n2) {
return n2 + (n2 & 1 ? 1 : 2);
};
var nextOdd = function(n2) {
return n2 + (n2 & 1 ? 2 : 1);
};
for (var paraIdx = 0;paraIdx < paragraphs.length; paraIdx++) {
paragraph = paragraphs[paraIdx];
var statusStack = [{
_level: paragraph.level,
_override: 0,
_isolate: 0
}];
var stackTop = undefined;
var overflowIsolateCount = 0;
var overflowEmbeddingCount = 0;
var validIsolateCount = 0;
charTypeCounts.clear();
for (var i$2 = paragraph.start;i$2 <= paragraph.end; i$2++) {
var charType = charTypes[i$2];
stackTop = statusStack[statusStack.length - 1];
charTypeCounts.set(charType, (charTypeCounts.get(charType) || 0) + 1);
if (charType & NEUTRAL_ISOLATE_TYPES) {
charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1);
}
if (charType & FORMATTING_TYPES) {
if (charType & (TYPE_RLE | TYPE_LRE)) {
embedLevels[i$2] = stackTop._level;
var level = (charType === TYPE_RLE ? nextOdd : nextEven)(stackTop._level);
if (level <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) {
statusStack.push({
_level: level,
_override: 0,
_isolate: 0
});
} else if (!overflowIsolateCount) {
overflowEmbeddingCount++;
}
} else if (charType & (TYPE_RLO | TYPE_LRO)) {
embedLevels[i$2] = stackTop._level;
var level$1 = (charType === TYPE_RLO ? nextOdd : nextEven)(stackTop._level);
if (level$1 <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) {
statusStack.push({
_level: level$1,
_override: charType & TYPE_RLO ? TYPE_R : TYPE_L,
_isolate: 0
});
} else if (!overflowIsolateCount) {
overflowEmbeddingCount++;
}
} else if (charType & ISOLATE_INIT_TYPES) {
if (charType & TYPE_FSI) {
charType = determineAutoEmbedLevel(i$2 + 1, true) === 1 ? TYPE_RLI : TYPE_LRI;
}
embedLevels[i$2] = stackTop._level;
if (stackTop._override) {
changeCharType(i$2, stackTop._override);
}
var level$2 = (charType === TYPE_RLI ? nextOdd : nextEven)(stackTop._level);
if (level$2 <= MAX_DEPTH && overflowIsolateCount === 0 && overflowEmbeddingCount === 0) {
validIsolateCount++;
statusStack.push({
_level: level$2,
_override: 0,
_isolate: 1,
_isolInitIndex: i$2
});
} else {
overflowIsolateCount++;
}
} else if (charType & TYPE_PDI) {
if (overflowIsolateCount > 0) {
overflowIsolateCount--;
} else if (validIsolateCount > 0) {
overflowEmbeddingCount = 0;
while (!statusStack[statusStack.length - 1]._isolate) {
statusStack.pop();
}
var isolInitIndex = statusStack[statusStack.length - 1]._isolInitIndex;
if (isolInitIndex != null) {
isolationPairs.set(isolInitIndex, i$2);
isolationPairs.set(i$2, isolInitIndex);
}
statusStack.pop();
validIsolateCount--;
}
stackTop = statusStack[statusStack.length - 1];
embedLevels[i$2] = stackTop._level;
if (stackTop._override) {
changeCharType(i$2, stackTop._override);
}
} else if (charType & TYPE_PDF) {
if (overflowIsolateCount === 0) {
if (overflowEmbeddingCount > 0) {
overflowEmbeddingCount--;
} else if (!stackTop._isolate && statusStack.length > 1) {
statusStack.pop();
stackTop = statusStack[statusStack.length - 1];
}
}
embedLevels[i$2] = stackTop._level;
} else if (charType & TYPE_B) {
embedLevels[i$2] = paragraph.level;
}
} else {
embedLevels[i$2] = stackTop._level;
if (stackTop._override && charType !== TYPE_BN) {
changeCharType(i$2, stackTop._override);
}
}
}
var levelRuns = [];
var currentRun = null;
for (var i$3 = paragraph.start;i$3 <= paragraph.end; i$3++) {
var charType$1 = charTypes[i$3];
if (!(charType$1 & BN_LIKE_TYPES)) {
var lvl = embedLevels[i$3];
var isIsolInit = charType$1 & ISOLATE_INIT_TYPES;
var isPDI = charType$1 === TYPE_PDI;
if (currentRun && lvl === currentRun._level) {
currentRun._end = i$3;
currentRun._endsWithIsolInit = isIsolInit;
} else {
levelRuns.push(currentRun = {
_start: i$3,
_end: i$3,
_level: lvl,
_startsWithPDI: isPDI,
_endsWithIsolInit: isIsolInit
});
}
}
}
var isolatingRunSeqs = [];
for (var runIdx = 0;runIdx < levelRuns.length; runIdx++) {
var run = levelRuns[runIdx];
if (!run._startsWithPDI || run._startsWithPDI && !isolationPairs.has(run._start)) {
var seqRuns = [currentRun = run];
for (var pdiIndex = undefined;currentRun && currentRun._endsWithIsolInit && (pdiIndex = isolationPairs.get(currentRun._end)) != null; ) {
for (var i$4 = runIdx + 1;i$4 < levelRuns.length; i$4++) {
if (levelRuns[i$4]._start === pdiIndex) {
seqRuns.push(currentRun = levelRuns[i$4]);
break;
}
}
}
var seqIndices = [];
for (var i$5 = 0;i$5 < seqRuns.length; i$5++) {
var run$1 = seqRuns[i$5];
for (var j = run$1._start;j <= run$1._end; j++) {
seqIndices.push(j);
}
}
var firstLevel = embedLevels[seqIndices[0]];
var prevLevel = paragraph.level;
for (var i$6 = seqIndices[0] - 1;i$6 >= 0; i$6--) {
if (!(charTypes[i$6] & BN_LIKE_TYPES)) {
prevLevel = embedLevels[i$6];
break;
}
}
var lastIndex = seqIndices[seqIndices.length - 1];
var lastLevel = embedLevels[lastIndex];
var nextLevel = paragraph.level;
if (!(charTypes[lastIndex] & ISOLATE_INIT_TYPES)) {
for (var i$7 = lastIndex + 1;i$7 <= paragraph.end; i$7++) {
if (!(charTypes[i$7] & BN_LIKE_TYPES)) {
nextLevel = embedLevels[i$7];
break;
}
}
}
isolatingRunSeqs.push({
_seqIndices: seqIndices,
_sosType: Math.max(prevLevel, firstLevel) % 2 ? TYPE_R : TYPE_L,
_eosType: Math.max(nextLevel, lastLevel) % 2 ? TYPE_R : TYPE_L
});
}
}
for (var seqIdx = 0;seqIdx < isolatingRunSeqs.length; seqIdx++) {
var ref = isolatingRunSeqs[seqIdx];
var seqIndices$1 = ref._seqIndices;
var sosType = ref._sosType;
var eosType = ref._eosType;
var embedDirection = embedLevels[seqIndices$1[0]] & 1 ? TYPE_R : TYPE_L;
if (charTypeCounts.get(TYPE_NSM)) {
for (var si = 0;si < seqIndices$1.length; si++) {
var i$8 = seqIndices$1[si];
if (charTypes[i$8] & TYPE_NSM) {
var prevType = sosType;
for (var sj = si - 1;sj >= 0; sj--) {
if (!(charTypes[seqIndices$1[sj]] & BN_LIKE_TYPES)) {
prevType = charTypes[seqIndices$1[sj]];
break;
}
}
changeCharType(i$8, prevType & (ISOLATE_INIT_TYPES | TYPE_PDI) ? TYPE_ON : prevType);
}
}
}
if (charTypeCounts.get(TYPE_EN)) {
for (var si$1 = 0;si$1 < seqIndices$1.length; si$1++) {
var i$9 = seqIndices$1[si$1];
if (charTypes[i$9] & TYPE_EN) {
for (var sj$1 = si$1 - 1;sj$1 >= -1; sj$1--) {
var prevCharType = sj$1 === -1 ? sosType : charTypes[seqIndices$1[sj$1]];
if (prevCharType & STRONG_TYPES) {
if (prevCharType === TYPE_AL) {
changeCharType(i$9, TYPE_AN);
}
break;
}
}
}
}
}
if (charTypeCounts.get(TYPE_AL)) {
for (var si$2 = 0;si$2 < seqIndices$1.length; si$2++) {
var i$10 = seqIndices$1[si$2];
if (charTypes[i$10] & TYPE_AL) {
changeCharType(i$10, TYPE_R);
}
}
}
if (charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) {
for (var si$3 = 1;si$3 < seqIndices$1.length - 1; si$3++) {
var i$11 = seqIndices$1[si$3];
if (charTypes[i$11] & (TYPE_ES | TYPE_CS)) {
var prevType$1 = 0, nextType = 0;
for (var sj$2 = si$3 - 1;sj$2 >= 0; sj$2--) {
prevType$1 = charTypes[seqIndices$1[sj$2]];
if (!(prevType$1 & BN_LIKE_TYPES)) {
break;
}
}
for (var sj$3 = si$3 + 1;sj$3 < seqIndices$1.length; sj$3++) {
nextType = charTypes[seqIndices$1[sj$3]];
if (!(nextType & BN_LIKE_TYPES)) {
break;
}
}
if (prevType$1 === nextType && (charTypes[i$11] === TYPE_ES ? prevType$1 === TYPE_EN : prevType$1 & (TYPE_EN | TYPE_AN))) {
changeCharType(i$11, prevType$1);
}
}
}
}
if (charTypeCounts.get(TYPE_EN)) {
for (var si$4 = 0;si$4 < seqIndices$1.length; si$4++) {
var i$12 = seqIndices$1[si$4];
if (charTypes[i$12] & TYPE_EN) {
for (var sj$4 = si$4 - 1;sj$4 >= 0 && charTypes[seqIndices$1[sj$4]] & (TYPE_ET | BN_LIKE_TYPES); sj$4--) {
changeCharType(seqIndices$1[sj$4], TYPE_EN);
}
for (si$4++;si$4 < seqIndices$1.length && charTypes[seqIndices$1[si$4]] & (TYPE_ET | BN_LIKE_TYPES | TYPE_EN); si$4++) {
if (charTypes[seqIndices$1[si$4]] !== TYPE_EN) {
changeCharType(seqIndices$1[si$4], TYPE_EN);
}
}
}
}
}
if (charTypeCounts.get(TYPE_ET) || charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) {
for (var si$5 = 0;si$5 < seqIndices$1.length; si$5++) {
var i$13 = seqIndices$1[si$5];
if (charTypes[i$13] & (TYPE_ET | TYPE_ES | TYPE_CS)) {
changeCharType(i$13, TYPE_ON);
for (var sj$5 = si$5 - 1;sj$5 >= 0 && charTypes[seqIndices$1[sj$5]] & BN_LIKE_TYPES; sj$5--) {
changeCharType(seqIndices$1[sj$5], TYPE_ON);
}
for (var sj$6 = si$5 + 1;sj$6 < seqIndices$1.length && charTypes[seqIndices$1[sj$6]] & BN_LIKE_TYPES; sj$6++) {
changeCharType(seqIndices$1[sj$6], TYPE_ON);
}
}
}
}
if (charTypeCounts.get(TYPE_EN)) {
for (var si$6 = 0, prevStrongType = sosType;si$6 < seqIndices$1.length; si$6++) {
var i$14 = seqIndices$1[si$6];
var type = charTypes[i$14];
if (type & TYPE_EN) {
if (prevStrongType === TYPE_L) {
changeCharType(i$14, TYPE_L);
}
} else if (type & STRONG_TYPES) {
prevStrongType = type;
}
}
}
if (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES)) {
var R_TYPES_FOR_N_STEPS = TYPE_R | TYPE_EN | TYPE_AN;
var STRONG_TYPES_FOR_N_STEPS = R_TYPES_FOR_N_STEPS | TYPE_L;
var bracketPairs = [];
{
var openerStack = [];
for (var si$7 = 0;si$7 < seqIndices$1.length; si$7++) {
if (charTypes[seqIndices$1[si$7]] & NEUTRAL_ISOLATE_TYPES) {
var char = string4[seqIndices$1[si$7]];
var oppositeBracket = undefined;
if (openingToClosingBracket(char) !== null) {
if (openerStack.length < 63) {
openerStack.push({ char, seqIndex: si$7 });
} else {
break;
}
} else if ((oppositeBracket = closingToOpeningBracket(char)) !== null) {
for (var stackIdx = openerStack.length - 1;stackIdx >= 0; stackIdx--) {
var stackChar = openerStack[stackIdx].char;
if (stackChar === oppositeBracket || stackChar === closingToOpeningBracket(getCanonicalBracket(char)) || openingToClosingBracket(getCanonicalBracket(stackChar)) === char) {
bracketPairs.push([openerStack[stackIdx].seqIndex, si$7]);
openerStack.length = stackIdx;
break;
}
}
}
}
}
bracketPairs.sort(function(a2, b) {
return a2[0] - b[0];
});
}
for (var pairIdx = 0;pairIdx < bracketPairs.length; pairIdx++) {
var ref$1 = bracketPairs[pairIdx];
var openSeqIdx = ref$1[0];
var closeSeqIdx = ref$1[1];
var foundStrongType = false;
var useStrongType = 0;
for (var si$8 = openSeqIdx + 1;si$8 < closeSeqIdx; si$8++) {
var i$15 = seqIndices$1[si$8];
if (charTypes[i$15] & STRONG_TYPES_FOR_N_STEPS) {
foundStrongType = true;
var lr = charTypes[i$15] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
if (lr === embedDirection) {
useStrongType = lr;
break;
}
}
}
if (foundStrongType && !useStrongType) {
useStrongType = sosType;
for (var si$9 = openSeqIdx - 1;si$9 >= 0; si$9--) {
var i$16 = seqIndices$1[si$9];
if (charTypes[i$16] & STRONG_TYPES_FOR_N_STEPS) {
var lr$1 = charTypes[i$16] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
if (lr$1 !== embedDirection) {
useStrongType = lr$1;
} else {
useStrongType = embedDirection;
}
break;
}
}
}
if (useStrongType) {
charTypes[seqIndices$1[openSeqIdx]] = charTypes[seqIndices$1[closeSeqIdx]] = useStrongType;
if (useStrongType !== embedDirection) {
for (var si$10 = openSeqIdx + 1;si$10 < seqIndices$1.length; si$10++) {
if (!(charTypes[seqIndices$1[si$10]] & BN_LIKE_TYPES)) {
if (getBidiCharType(string4[seqIndices$1[si$10]]) & TYPE_NSM) {
charTypes[seqIndices$1[si$10]] = useStrongType;
}
break;
}
}
}
if (useStrongType !== embedDirection) {
for (var si$11 = closeSeqIdx + 1;si$11 < seqIndices$1.length; si$11++) {
if (!(charTypes[seqIndices$1[si$11]] & BN_LIKE_TYPES)) {
if (getBidiCharType(string4[seqIndices$1[si$11]]) & TYPE_NSM) {
charTypes[seqIndices$1[si$11]] = useStrongType;
}
break;
}
}
}
}
}
for (var si$12 = 0;si$12 < seqIndices$1.length; si$12++) {
if (charTypes[seqIndices$1[si$12]] & NEUTRAL_ISOLATE_TYPES) {
var niRunStart = si$12, niRunEnd = si$12;
var prevType$2 = sosType;
for (var si2 = si$12 - 1;si2 >= 0; si2--) {
if (charTypes[seqIndices$1[si2]] & BN_LIKE_TYPES) {
niRunStart = si2;
} else {
prevType$2 = charTypes[seqIndices$1[si2]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
break;
}
}
var nextType$1 = eosType;
for (var si2$1 = si$12 + 1;si2$1 < seqIndices$1.length; si2$1++) {
if (charTypes[seqIndices$1[si2$1]] & (NEUTRAL_ISOLATE_TYPES | BN_LIKE_TYPES)) {
niRunEnd = si2$1;
} else {
nextType$1 = charTypes[seqIndices$1[si2$1]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
break;
}
}
for (var sj$7 = niRunStart;sj$7 <= niRunEnd; sj$7++) {
charTypes[seqIndices$1[sj$7]] = prevType$2 === nextType$1 ? prevType$2 : embedDirection;
}
si$12 = niRunEnd;
}
}
}
}
for (var i$17 = paragraph.start;i$17 <= paragraph.end; i$17++) {
var level$3 = embedLevels[i$17];
var type$1 = charTypes[i$17];
if (level$3 & 1) {
if (type$1 & (TYPE_L | TYPE_EN | TYPE_AN)) {
embedLevels[i$17]++;
}
} else {
if (type$1 & TYPE_R) {
embedLevels[i$17]++;
} else if (type$1 & (TYPE_AN | TYPE_EN)) {
embedLevels[i$17] += 2;
}
}
if (type$1 & BN_LIKE_TYPES) {
embedLevels[i$17] = i$17 === 0 ? paragraph.level : embedLevels[i$17 - 1];
}
if (i$17 === paragraph.end || getBidiCharType(string4[i$17]) & (TYPE_S | TYPE_B)) {
for (var j$1 = i$17;j$1 >= 0 && getBidiCharType(string4[j$1]) & TRAILING_TYPES; j$1--) {
embedLevels[j$1] = paragraph.level;
}
}
}
}
return {
levels: embedLevels,
paragraphs
};
function determineAutoEmbedLevel(start, isFSI) {
for (var i3 = start;i3 < string4.length; i3++) {
var charType2 = charTypes[i3];
if (charType2 & (TYPE_R | TYPE_AL)) {
return 1;
}
if (charType2 & (TYPE_B | TYPE_L) || isFSI && charType2 === TYPE_PDI) {
return 0;
}
if (charType2 & ISOLATE_INIT_TYPES) {
var pdi = indexOfMatchingPDI(i3);
i3 = pdi === -1 ? string4.length : pdi;
}
}
return 0;
}
function indexOfMatchingPDI(isolateStart) {
var isolationLevel = 1;
for (var i3 = isolateStart + 1;i3 < string4.length; i3++) {
var charType2 = charTypes[i3];
if (charType2 & TYPE_B) {
break;
}
if (charType2 & TYPE_PDI) {
if (--isolationLevel === 0) {
return i3;
}
} else if (charType2 & ISOLATE_INIT_TYPES) {
isolationLevel++;
}
}
return -1;
}
}
var data = "14>1,j>2,t>2,u>2,1a>g,2v3>1,1>1,1ge>1,1wd>1,b>1,1j>1,f>1,ai>3,-2>3,+1,8>1k0,-1jq>1y7,-1y6>1hf,-1he>1h6,-1h5>1ha,-1h8>1qi,-1pu>1,6>3u,-3s>7,6>1,1>1,f>1,1>1,+2,3>1,1>1,+13,4>1,1>1,6>1eo,-1ee>1,3>1mg,-1me>1mk,-1mj>1mi,-1mg>1mi,-1md>1,1>1,+2,1>10k,-103>1,1>1,4>1,5>1,1>1,+10,3>1,1>8,-7>8,+1,-6>7,+1,a>1,1>1,u>1,u6>1,1>1,+5,26>1,1>1,2>1,2>2,8>1,7>1,4>1,1>1,+5,b8>1,1>1,+3,1>3,-2>1,2>1,1>1,+2,c>1,3>1,1>1,+2,h>1,3>1,a>1,1>1,2>1,3>1,1>1,d>1,f>1,3>1,1a>1,1>1,6>1,7>1,13>1,k>1,1>1,+19,4>1,1>1,+2,2>1,1>1,+18,m>1,a>1,1>1,lk>1,1>1,4>1,2>1,f>1,3>1,1>1,+3,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,6>1,4j>1,j>2,t>2,u>2,2>1,+1";
var mirrorMap;
function parse7() {
if (!mirrorMap) {
var ref = parseCharacterMap(data, true);
var map4 = ref.map;
var reverseMap = ref.reverseMap;
reverseMap.forEach(function(value, key) {
map4.set(key, value);
});
mirrorMap = map4;
}
}
function getMirroredCharacter(char) {
parse7();
return mirrorMap.get(char) || null;
}
function getMirroredCharactersMap(string4, embeddingLevels, start, end) {
var strLen = string4.length;
start = Math.max(0, start == null ? 0 : +start);
end = Math.min(strLen - 1, end == null ? strLen - 1 : +end);
var map4 = new Map;
for (var i2 = start;i2 <= end; i2++) {
if (embeddingLevels[i2] & 1) {
var mirror = getMirroredCharacter(string4[i2]);
if (mirror !== null) {
map4.set(i2, mirror);
}
}
}
return map4;
}
function getReorderSegments(string4, embeddingLevelsResult, start, end) {
var strLen = string4.length;
start = Math.max(0, start == null ? 0 : +start);
end = Math.min(strLen - 1, end == null ? strLen - 1 : +end);
var segments = [];
embeddingLevelsResult.paragraphs.forEach(function(paragraph) {
var lineStart = Math.max(start, paragraph.start);
var lineEnd = Math.min(end, paragraph.end);
if (lineStart < lineEnd) {
var lineLevels = embeddingLevelsResult.levels.slice(lineStart, lineEnd + 1);
for (var i2 = lineEnd;i2 >= lineStart && getBidiCharType(string4[i2]) & TRAILING_TYPES; i2--) {
lineLevels[i2] = paragraph.level;
}
var maxLevel = paragraph.level;
var minOddLevel = Infinity;
for (var i$1 = 0;i$1 < lineLevels.length; i$1++) {
var level = lineLevels[i$1];
if (level > maxLevel) {
maxLevel = level;
}
if (level < minOddLevel) {
minOddLevel = level | 1;
}
}
for (var lvl = maxLevel;lvl >= minOddLevel; lvl--) {
for (var i$2 = 0;i$2 < lineLevels.length; i$2++) {
if (lineLevels[i$2] >= lvl) {
var segStart = i$2;
while (i$2 + 1 < lineLevels.length && lineLevels[i$2 + 1] >= lvl) {
i$2++;
}
if (i$2 > segStart) {
segments.push([segStart + lineStart, i$2 + lineStart]);
}
}
}
}
}
});
return segments;
}
function getReorderedString(string4, embedLevelsResult, start, end) {
var indices = getReorderedIndices(string4, embedLevelsResult, start, end);
var chars = [].concat(string4);
indices.forEach(function(charIndex, i2) {
chars[i2] = (embedLevelsResult.levels[charIndex] & 1 ? getMirroredCharacter(string4[charIndex]) : null) || string4[charIndex];
});
return chars.join("");
}
function getReorderedIndices(string4, embedLevelsResult, start, end) {
var segments = getReorderSegments(string4, embedLevelsResult, start, end);
var indices = [];
for (var i2 = 0;i2 < string4.length; i2++) {
indices[i2] = i2;
}
segments.forEach(function(ref) {
var start2 = ref[0];
var end2 = ref[1];
var slice = indices.slice(start2, end2 + 1);
for (var i3 = slice.length;i3--; ) {
indices[end2 - i3] = slice[i3];
}
});
return indices;
}
exports2.closingToOpeningBracket = closingToOpeningBracket;
exports2.getBidiCharType = getBidiCharType;
exports2.getBidiCharTypeName = getBidiCharTypeName;
exports2.getCanonicalBracket = getCanonicalBracket;
exports2.getEmbeddingLevels = getEmbeddingLevels;
exports2.getMirroredCharacter = getMirroredCharacter;
exports2.getMirroredCharactersMap = getMirroredCharactersMap;
exports2.getReorderSegments = getReorderSegments;
exports2.getReorderedIndices = getReorderedIndices;
exports2.getReorderedString = getReorderedString;
exports2.openingToClosingBracket = openingToClosingBracket;
Object.defineProperty(exports2, "__esModule", { value: true });
return exports2;
}({});
return bidi;
}
return bidiFactory;
});
});
// src/ink/bidi.ts
function needsBidi() {
if (needsSoftwareBidi === undefined) {
needsSoftwareBidi = process.platform === "win32" || typeof process.env["WT_SESSION"] === "string" || process.env["TERM_PROGRAM"] === "vscode";
}
return needsSoftwareBidi;
}
function getBidi() {
if (!bidiInstance) {
bidiInstance = import_bidi_js.default();
}
return bidiInstance;
}
function reorderBidi(characters) {
if (!needsBidi() || characters.length === 0) {
return characters;
}
const plainText = characters.map((c6) => c6.value).join("");
if (!hasRTLCharacters(plainText)) {
return characters;
}
const bidi = getBidi();
const { levels } = bidi.getEmbeddingLevels(plainText, "auto");
const charLevels = [];
let offset = 0;
for (let i2 = 0;i2 < characters.length; i2++) {
charLevels.push(levels[offset]);
offset += characters[i2].value.length;
}
const reordered = [...characters];
const maxLevel = Math.max(...charLevels);
for (let level = maxLevel;level >= 1; level--) {
let i2 = 0;
while (i2 < reordered.length) {
if (charLevels[i2] >= level) {
let j = i2 + 1;
while (j < reordered.length && charLevels[j] >= level) {
j++;
}
reverseRange(reordered, i2, j - 1);
reverseRangeNumbers(charLevels, i2, j - 1);
i2 = j;
} else {
i2++;
}
}
}
return reordered;
}
function reverseRange(arr, start, end) {
while (start < end) {
const temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
function reverseRangeNumbers(arr, start, end) {
while (start < end) {
const temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
function hasRTLCharacters(text) {
return /[\u0590-\u05FF\uFB1D-\uFB4F\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF\u0780-\u07BF\u0700-\u074F]/u.test(text);
}
var import_bidi_js, bidiInstance, needsSoftwareBidi;
var init_bidi = __esm(() => {
import_bidi_js = __toESM(require_bidi(), 1);
});
// src/ink/widest-line.ts
function widestLine(string4) {
let maxWidth = 0;
let start = 0;
while (start <= string4.length) {
const end = string4.indexOf(`
`, start);
const line = end === -1 ? string4.substring(start) : string4.substring(start, end);
maxWidth = Math.max(maxWidth, lineWidth(line));
if (end === -1)
break;
start = end + 1;
}
return maxWidth;
}
var init_widest_line = __esm(() => {
init_line_width_cache();
});
// src/ink/output.ts
function intersectClip(parent, child) {
if (!parent)
return child;
return {
x1: maxDefined(parent.x1, child.x1),
x2: minDefined(parent.x2, child.x2),
y1: maxDefined(parent.y1, child.y1),
y2: minDefined(parent.y2, child.y2)
};
}
function maxDefined(a2, b) {
if (a2 === undefined)
return b;
if (b === undefined)
return a2;
return Math.max(a2, b);
}
function minDefined(a2, b) {
if (a2 === undefined)
return b;
if (b === undefined)
return a2;
return Math.min(a2, b);
}
class Output {
width;
height;
stylePool;
screen;
operations = [];
charCache = new Map;
constructor(options) {
const { width, height, stylePool, screen } = options;
this.width = width;
this.height = height;
this.stylePool = stylePool;
this.screen = screen;
resetScreen(screen, width, height);
}
reset(width, height, screen) {
this.width = width;
this.height = height;
this.screen = screen;
this.operations.length = 0;
resetScreen(screen, width, height);
if (this.charCache.size > 16384)
this.charCache.clear();
}
blit(src, x2, y2, width, height) {
this.operations.push({ type: "blit", src, x: x2, y: y2, width, height });
}
shift(top, bottom, n2) {
this.operations.push({ type: "shift", top, bottom, n: n2 });
}
clear(region, fromAbsolute) {
this.operations.push({ type: "clear", region, fromAbsolute });
}
noSelect(region) {
this.operations.push({ type: "noSelect", region });
}
write(x2, y2, text, softWrap) {
if (!text) {
return;
}
this.operations.push({
type: "write",
x: x2,
y: y2,
text,
softWrap
});
}
clip(clip) {
this.operations.push({
type: "clip",
clip
});
}
unclip() {
this.operations.push({
type: "unclip"
});
}
get() {
const screen = this.screen;
const screenWidth = this.width;
const screenHeight = this.height;
let blitCells = 0;
let writeCells = 0;
const absoluteClears = [];
for (const operation of this.operations) {
if (operation.type !== "clear")
continue;
const { x: x2, y: y2, width, height } = operation.region;
const startX = Math.max(0, x2);
const startY = Math.max(0, y2);
const maxX = Math.min(x2 + width, screenWidth);
const maxY = Math.min(y2 + height, screenHeight);
if (startX >= maxX || startY >= maxY)
continue;
const rect = {
x: startX,
y: startY,
width: maxX - startX,
height: maxY - startY
};
screen.damage = screen.damage ? unionRect(screen.damage, rect) : rect;
if (operation.fromAbsolute)
absoluteClears.push(rect);
}
const clips = [];
for (const operation of this.operations) {
switch (operation.type) {
case "clear":
continue;
case "clip":
clips.push(intersectClip(clips.at(-1), operation.clip));
continue;
case "unclip":
clips.pop();
continue;
case "blit": {
const {
src,
x: regionX,
y: regionY,
width: regionWidth,
height: regionHeight
} = operation;
const clip = clips.at(-1);
const startX = Math.max(regionX, clip?.x1 ?? 0);
const startY = Math.max(regionY, clip?.y1 ?? 0);
const maxY = Math.min(regionY + regionHeight, screenHeight, src.height, clip?.y2 ?? Infinity);
const maxX = Math.min(regionX + regionWidth, screenWidth, src.width, clip?.x2 ?? Infinity);
if (startX >= maxX || startY >= maxY)
continue;
if (absoluteClears.length === 0) {
blitRegion(screen, src, startX, startY, maxX, maxY);
blitCells += (maxY - startY) * (maxX - startX);
continue;
}
let rowStart = startY;
for (let row = startY;row <= maxY; row++) {
const excluded = row < maxY && absoluteClears.some((r) => row >= r.y && row < r.y + r.height && startX >= r.x && maxX <= r.x + r.width);
if (excluded || row === maxY) {
if (row > rowStart) {
blitRegion(screen, src, startX, rowStart, maxX, row);
blitCells += (row - rowStart) * (maxX - startX);
}
rowStart = row + 1;
}
}
continue;
}
case "shift": {
shiftRows(screen, operation.top, operation.bottom, operation.n);
continue;
}
case "write": {
const { text, softWrap } = operation;
let { x: x2, y: y2 } = operation;
let lines = text.split(`
`);
let swFrom = 0;
let prevContentEnd = 0;
const clip = clips.at(-1);
if (clip) {
const clipHorizontally = typeof clip?.x1 === "number" && typeof clip?.x2 === "number";
const clipVertically = typeof clip?.y1 === "number" && typeof clip?.y2 === "number";
if (clipHorizontally) {
const width = widestLine(text);
if (x2 + width <= clip.x1 || x2 >= clip.x2) {
continue;
}
}
if (clipVertically) {
const height = lines.length;
if (y2 + height <= clip.y1 || y2 >= clip.y2) {
continue;
}
}
if (clipHorizontally) {
lines = lines.map((line) => {
const from = x2 < clip.x1 ? clip.x1 - x2 : 0;
const width = stringWidth(line);
const to = x2 + width > clip.x2 ? clip.x2 - x2 : width;
let sliced = sliceAnsi(line, from, to);
if (stringWidth(sliced) > to - from) {
sliced = sliceAnsi(line, from, to - 1);
}
return sliced;
});
if (x2 < clip.x1) {
x2 = clip.x1;
}
}
if (clipVertically) {
const from = y2 < clip.y1 ? clip.y1 - y2 : 0;
const height = lines.length;
const to = y2 + height > clip.y2 ? clip.y2 - y2 : height;
if (softWrap && from > 0 && softWrap[from] === true) {
prevContentEnd = x2 + stringWidth(lines[from - 1]);
}
lines = lines.slice(from, to);
swFrom = from;
if (y2 < clip.y1) {
y2 = clip.y1;
}
}
}
const swBits = screen.softWrap;
let offsetY = 0;
for (const line of lines) {
const lineY = y2 + offsetY;
if (lineY >= screenHeight) {
break;
}
const contentEnd = writeLineToScreen(screen, line, x2, lineY, screenWidth, this.stylePool, this.charCache);
writeCells += contentEnd - x2;
if (softWrap) {
const isSW = softWrap[swFrom + offsetY] === true;
swBits[lineY] = isSW ? prevContentEnd : 0;
prevContentEnd = contentEnd;
}
offsetY++;
}
continue;
}
}
}
for (const operation of this.operations) {
if (operation.type === "noSelect") {
const { x: x2, y: y2, width, height } = operation.region;
markNoSelectRegion(screen, x2, y2, width, height);
}
}
const totalCells = blitCells + writeCells;
if (totalCells > 1000 && writeCells > blitCells) {
logForDebugging(`High write ratio: blit=${blitCells}, write=${writeCells} (${(writeCells / totalCells * 100).toFixed(1)}% writes), screen=${screenHeight}x${screenWidth}`);
}
return screen;
}
}
function stylesEqual2(a2, b) {
if (a2 === b)
return true;
const len = a2.length;
if (len !== b.length)
return false;
if (len === 0)
return true;
for (let i2 = 0;i2 < len; i2++) {
if (a2[i2].code !== b[i2].code)
return false;
}
return true;
}
function styledCharsWithGraphemeClustering(chars, stylePool) {
const charCount = chars.length;
if (charCount === 0)
return [];
const result = [];
const bufferChars = [];
let bufferStyles = chars[0].styles;
for (let i2 = 0;i2 < charCount; i2++) {
const char = chars[i2];
const styles5 = char.styles;
if (bufferChars.length > 0 && !stylesEqual2(styles5, bufferStyles)) {
flushBuffer(bufferChars.join(""), bufferStyles, stylePool, result);
bufferChars.length = 0;
}
bufferChars.push(char.value);
bufferStyles = styles5;
}
if (bufferChars.length > 0) {
flushBuffer(bufferChars.join(""), bufferStyles, stylePool, result);
}
return result;
}
function flushBuffer(buffer, styles5, stylePool, out) {
const hyperlink = extractHyperlinkFromStyles(styles5) ?? undefined;
const hasOsc8Styles = hyperlink !== undefined || styles5.some((s) => s.code.length >= OSC8_PREFIX.length && s.code.startsWith(OSC8_PREFIX));
const filteredStyles = hasOsc8Styles ? filterOutHyperlinkStyles(styles5) : styles5;
const styleId = stylePool.intern(filteredStyles);
for (const { segment: grapheme } of getGraphemeSegmenter().segment(buffer)) {
out.push({
value: grapheme,
width: stringWidth(grapheme),
styleId,
hyperlink
});
}
}
function writeLineToScreen(screen, line, x2, y2, screenWidth, stylePool, charCache) {
let characters = charCache.get(line);
if (!characters) {
characters = reorderBidi(styledCharsWithGraphemeClustering(styledCharsFromTokens(tokenize3(line)), stylePool));
charCache.set(line, characters);
}
let offsetX = x2;
for (let charIdx = 0;charIdx < characters.length; charIdx++) {
const character = characters[charIdx];
const codePoint = character.value.codePointAt(0);
if (codePoint !== undefined && codePoint <= 31) {
if (codePoint === 9) {
const tabWidth = 8;
const spacesToNextStop = tabWidth - offsetX % tabWidth;
for (let i2 = 0;i2 < spacesToNextStop && offsetX < screenWidth; i2++) {
setCellAt(screen, offsetX, y2, {
char: " ",
styleId: stylePool.none,
width: 0 /* Narrow */,
hyperlink: undefined
});
offsetX++;
}
} else if (codePoint === 27) {
const nextChar = characters[charIdx + 1]?.value;
const nextCode = nextChar?.codePointAt(0);
if (nextChar === "(" || nextChar === ")" || nextChar === "*" || nextChar === "+") {
charIdx += 2;
} else if (nextChar === "[") {
charIdx++;
while (charIdx < characters.length - 1) {
charIdx++;
const c6 = characters[charIdx]?.value.codePointAt(0);
if (c6 !== undefined && c6 >= 64 && c6 <= 126) {
break;
}
}
} else if (nextChar === "]" || nextChar === "P" || nextChar === "_" || nextChar === "^" || nextChar === "X") {
charIdx++;
while (charIdx < characters.length - 1) {
charIdx++;
const c6 = characters[charIdx]?.value;
if (c6 === "\x07") {
break;
}
if (c6 === "\x1B") {
const nextC = characters[charIdx + 1]?.value;
if (nextC === "\\") {
charIdx++;
break;
}
}
}
} else if (nextCode !== undefined && nextCode >= 48 && nextCode <= 126) {
charIdx++;
}
}
continue;
}
const charWidth = character.width;
if (charWidth === 0) {
continue;
}
const isWideCharacter = charWidth >= 2;
if (isWideCharacter && offsetX + 2 > screenWidth) {
setCellAt(screen, offsetX, y2, {
char: " ",
styleId: stylePool.none,
width: 3 /* SpacerHead */,
hyperlink: undefined
});
offsetX++;
continue;
}
setCellAt(screen, offsetX, y2, {
char: character.value,
styleId: character.styleId,
width: isWideCharacter ? 1 /* Wide */ : 0 /* Narrow */,
hyperlink: character.hyperlink
});
offsetX += isWideCharacter ? 2 : 1;
}
return offsetX;
}
var init_output2 = __esm(() => {
init_build();
init_debug();
init_intl();
init_sliceAnsi();
init_bidi();
init_geometry();
init_screen();
init_stringWidth();
init_widest_line();
});
// node_modules/indent-string/index.js
function indentString(string4, count3 = 1, options = {}) {
const {
indent = " ",
includeEmptyLines = false
} = options;
if (typeof string4 !== "string") {
throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string4}\``);
}
if (typeof count3 !== "number") {
throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count3}\``);
}
if (count3 < 0) {
throw new RangeError(`Expected \`count\` to be at least 0, got \`${count3}\``);
}
if (typeof indent !== "string") {
throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
}
if (count3 === 0) {
return string4;
}
const regex2 = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
return string4.replace(regex2, indent.repeat(count3));
}
// src/ink/get-max-width.ts
var getMaxWidth = (yogaNode) => {
return yogaNode.getComputedWidth() - yogaNode.getComputedPadding(LayoutEdge.Left) - yogaNode.getComputedPadding(LayoutEdge.Right) - yogaNode.getComputedBorder(LayoutEdge.Left) - yogaNode.getComputedBorder(LayoutEdge.Right);
}, get_max_width_default;
var init_get_max_width = __esm(() => {
init_node4();
get_max_width_default = getMaxWidth;
});
// node_modules/cli-boxes/boxes.json
var require_boxes = __commonJS((exports, module) => {
module.exports = {
single: {
topLeft: "┌",
top: "─",
topRight: "┐",
right: "│",
bottomRight: "┘",
bottom: "─",
bottomLeft: "└",
left: "│"
},
double: {
topLeft: "╔",
top: "═",
topRight: "╗",
right: "║",
bottomRight: "╝",
bottom: "═",
bottomLeft: "╚",
left: "║"
},
round: {
topLeft: "╭",
top: "─",
topRight: "╮",
right: "│",
bottomRight: "╯",
bottom: "─",
bottomLeft: "╰",
left: "│"
},
bold: {
topLeft: "┏",
top: "━",
topRight: "┓",
right: "┃",
bottomRight: "┛",
bottom: "━",
bottomLeft: "┗",
left: "┃"
},
singleDouble: {
topLeft: "╓",
top: "─",
topRight: "╖",
right: "║",
bottomRight: "╜",
bottom: "─",
bottomLeft: "╙",
left: "║"
},
doubleSingle: {
topLeft: "╒",
top: "═",
topRight: "╕",
right: "│",
bottomRight: "╛",
bottom: "═",
bottomLeft: "╘",
left: "│"
},
classic: {
topLeft: "+",
top: "-",
topRight: "+",
right: "|",
bottomRight: "+",
bottom: "-",
bottomLeft: "+",
left: "|"
},
arrow: {
topLeft: "↘",
top: "↓",
topRight: "↙",
right: "←",
bottomRight: "↖",
bottom: "↑",
bottomLeft: "↗",
left: "→"
}
};
});
// node_modules/cli-boxes/index.js
var require_cli_boxes = __commonJS((exports, module) => {
var cliBoxes = require_boxes();
module.exports = cliBoxes;
module.exports.default = cliBoxes;
});
// src/ink/render-border.ts
function embedTextInBorder(borderLine, text, align, offset = 0, borderChar) {
const textLength = stringWidth(text);
const borderLength = borderLine.length;
if (textLength >= borderLength - 2) {
return ["", text.substring(0, borderLength), ""];
}
let position;
if (align === "center") {
position = Math.floor((borderLength - textLength) / 2);
} else if (align === "start") {
position = offset + 1;
} else {
position = borderLength - textLength - offset - 1;
}
position = Math.max(1, Math.min(position, borderLength - textLength - 1));
const before = borderLine.substring(0, 1) + borderChar.repeat(position - 1);
const after = borderChar.repeat(borderLength - position - textLength - 1) + borderLine.substring(borderLength - 1);
return [before, text, after];
}
function styleBorderLine(line, color, dim2) {
let styled = applyColor(line, color);
if (dim2) {
styled = source_default.dim(styled);
}
return styled;
}
var import_cli_boxes, CUSTOM_BORDER_STYLES, renderBorder = (x2, y2, node, output) => {
if (node.style.borderStyle) {
const width = Math.floor(node.yogaNode.getComputedWidth());
const height = Math.floor(node.yogaNode.getComputedHeight());
const box = typeof node.style.borderStyle === "string" ? CUSTOM_BORDER_STYLES[node.style.borderStyle] ?? import_cli_boxes.default[node.style.borderStyle] : node.style.borderStyle;
const topBorderColor = node.style.borderTopColor ?? node.style.borderColor;
const bottomBorderColor = node.style.borderBottomColor ?? node.style.borderColor;
const leftBorderColor = node.style.borderLeftColor ?? node.style.borderColor;
const rightBorderColor = node.style.borderRightColor ?? node.style.borderColor;
const dimTopBorderColor = node.style.borderTopDimColor ?? node.style.borderDimColor;
const dimBottomBorderColor = node.style.borderBottomDimColor ?? node.style.borderDimColor;
const dimLeftBorderColor = node.style.borderLeftDimColor ?? node.style.borderDimColor;
const dimRightBorderColor = node.style.borderRightDimColor ?? node.style.borderDimColor;
const showTopBorder = node.style.borderTop !== false;
const showBottomBorder = node.style.borderBottom !== false;
const showLeftBorder = node.style.borderLeft !== false;
const showRightBorder = node.style.borderRight !== false;
const contentWidth = Math.max(0, width - (showLeftBorder ? 1 : 0) - (showRightBorder ? 1 : 0));
const topBorderLine = showTopBorder ? (showLeftBorder ? box.topLeft : "") + box.top.repeat(contentWidth) + (showRightBorder ? box.topRight : "") : "";
let topBorder;
if (showTopBorder && node.style.borderText?.position === "top") {
const [before, text, after] = embedTextInBorder(topBorderLine, node.style.borderText.content, node.style.borderText.align, node.style.borderText.offset, box.top);
topBorder = styleBorderLine(before, topBorderColor, dimTopBorderColor) + text + styleBorderLine(after, topBorderColor, dimTopBorderColor);
} else if (showTopBorder) {
topBorder = styleBorderLine(topBorderLine, topBorderColor, dimTopBorderColor);
}
let verticalBorderHeight = height;
if (showTopBorder) {
verticalBorderHeight -= 1;
}
if (showBottomBorder) {
verticalBorderHeight -= 1;
}
verticalBorderHeight = Math.max(0, verticalBorderHeight);
let leftBorder = (applyColor(box.left, leftBorderColor) + `
`).repeat(verticalBorderHeight);
if (dimLeftBorderColor) {
leftBorder = source_default.dim(leftBorder);
}
let rightBorder = (applyColor(box.right, rightBorderColor) + `
`).repeat(verticalBorderHeight);
if (dimRightBorderColor) {
rightBorder = source_default.dim(rightBorder);
}
const bottomBorderLine = showBottomBorder ? (showLeftBorder ? box.bottomLeft : "") + box.bottom.repeat(contentWidth) + (showRightBorder ? box.bottomRight : "") : "";
let bottomBorder;
if (showBottomBorder && node.style.borderText?.position === "bottom") {
const [before, text, after] = embedTextInBorder(bottomBorderLine, node.style.borderText.content, node.style.borderText.align, node.style.borderText.offset, box.bottom);
bottomBorder = styleBorderLine(before, bottomBorderColor, dimBottomBorderColor) + text + styleBorderLine(after, bottomBorderColor, dimBottomBorderColor);
} else if (showBottomBorder) {
bottomBorder = styleBorderLine(bottomBorderLine, bottomBorderColor, dimBottomBorderColor);
}
const offsetY = showTopBorder ? 1 : 0;
if (topBorder) {
output.write(x2, y2, topBorder);
}
if (showLeftBorder) {
output.write(x2, y2 + offsetY, leftBorder);
}
if (showRightBorder) {
output.write(x2 + width - 1, y2 + offsetY, rightBorder);
}
if (bottomBorder) {
output.write(x2, y2 + height - 1, bottomBorder);
}
}
}, render_border_default;
var init_render_border = __esm(() => {
init_source();
init_colorize();
init_stringWidth();
import_cli_boxes = __toESM(require_cli_boxes(), 1);
CUSTOM_BORDER_STYLES = {
dashed: {
top: "╌",
left: "╎",
right: "╎",
bottom: "╌",
topLeft: " ",
topRight: " ",
bottomLeft: " ",
bottomRight: " "
}
};
render_border_default = renderBorder;
});
// src/ink/render-node-to-output.ts
function isXtermJsHost() {
return process.env.TERM_PROGRAM === "vscode" || isXtermJs();
}
function resetLayoutShifted() {
layoutShifted = false;
}
function didLayoutShift() {
return layoutShifted;
}
function resetScrollHint() {
scrollHint = null;
absoluteRectsPrev = absoluteRectsCur;
absoluteRectsCur = [];
}
function getScrollHint() {
return scrollHint;
}
function resetScrollDrainNode() {
scrollDrainNode = null;
}
function getScrollDrainNode() {
return scrollDrainNode;
}
function consumeFollowScroll() {
const f = followScroll;
followScroll = null;
return f;
}
function drainAdaptive(node, pending, innerHeight) {
const sign = pending > 0 ? 1 : -1;
let abs = Math.abs(pending);
let applied = 0;
if (abs > SCROLL_MAX_PENDING) {
applied += sign * (abs - SCROLL_MAX_PENDING);
abs = SCROLL_MAX_PENDING;
}
const step = abs <= SCROLL_INSTANT_THRESHOLD ? abs : abs < SCROLL_HIGH_PENDING ? SCROLL_STEP_MED : SCROLL_STEP_HIGH;
applied += sign * step;
const rem = abs - step;
const cap = Math.max(1, innerHeight - 1);
const totalAbs = Math.abs(applied);
if (totalAbs > cap) {
const excess = totalAbs - cap;
node.pendingScrollDelta = sign * (rem + excess);
return sign * cap;
}
node.pendingScrollDelta = rem > 0 ? sign * rem : undefined;
return applied;
}
function drainProportional(node, pending, innerHeight) {
const abs = Math.abs(pending);
const cap = Math.max(1, innerHeight - 1);
const step = Math.min(cap, Math.max(SCROLL_MIN_PER_FRAME, abs * 3 >> 2));
if (abs <= step) {
node.pendingScrollDelta = undefined;
return pending;
}
const applied = pending > 0 ? step : -step;
node.pendingScrollDelta = pending - applied;
return applied;
}
function wrapWithOsc8Link(text, url3) {
return `${OSC3}8;;${url3}${BEL3}${text}${OSC3}8;;${BEL3}`;
}
function buildCharToSegmentMap(segments) {
const map3 = [];
for (let i2 = 0;i2 < segments.length; i2++) {
const len = segments[i2].text.length;
for (let j = 0;j < len; j++) {
map3.push(i2);
}
}
return map3;
}
function applyStylesToWrappedText(wrappedPlain, segments, charToSegment, originalPlain, trimEnabled = false) {
const lines = wrappedPlain.split(`
`);
const resultLines = [];
let charIndex = 0;
for (let lineIdx = 0;lineIdx < lines.length; lineIdx++) {
const line = lines[lineIdx];
if (trimEnabled && line.length > 0) {
const lineStartsWithWhitespace = /\s/.test(line[0]);
const originalHasWhitespace = charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex]);
if (originalHasWhitespace && !lineStartsWithWhitespace) {
while (charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex])) {
charIndex++;
}
}
}
let styledLine = "";
let runStart = 0;
let runSegmentIndex = charToSegment[charIndex] ?? 0;
for (let i2 = 0;i2 < line.length; i2++) {
const currentSegmentIndex = charToSegment[charIndex] ?? runSegmentIndex;
if (currentSegmentIndex !== runSegmentIndex) {
const runText2 = line.slice(runStart, i2);
const segment2 = segments[runSegmentIndex];
if (segment2) {
let styled = applyTextStyles(runText2, segment2.styles);
if (segment2.hyperlink) {
styled = wrapWithOsc8Link(styled, segment2.hyperlink);
}
styledLine += styled;
} else {
styledLine += runText2;
}
runStart = i2;
runSegmentIndex = currentSegmentIndex;
}
charIndex++;
}
const runText = line.slice(runStart);
const segment = segments[runSegmentIndex];
if (segment) {
let styled = applyTextStyles(runText, segment.styles);
if (segment.hyperlink) {
styled = wrapWithOsc8Link(styled, segment.hyperlink);
}
styledLine += styled;
} else {
styledLine += runText;
}
resultLines.push(styledLine);
if (charIndex < originalPlain.length && originalPlain[charIndex] === `
`) {
charIndex++;
}
if (trimEnabled && lineIdx < lines.length - 1) {
const nextLine = lines[lineIdx + 1];
const nextLineFirstChar = nextLine.length > 0 ? nextLine[0] : null;
while (charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex])) {
if (nextLineFirstChar !== null && originalPlain[charIndex] === nextLineFirstChar) {
break;
}
charIndex++;
}
}
}
return resultLines.join(`
`);
}
function wrapWithSoftWrap(plainText, maxWidth, textWrap) {
if (textWrap !== "wrap" && textWrap !== "wrap-trim") {
return {
wrapped: wrapText2(plainText, maxWidth, textWrap),
softWrap: undefined
};
}
const origLines = plainText.split(`
`);
const outLines = [];
const softWrap = [];
for (const orig of origLines) {
const pieces = wrapText2(orig, maxWidth, textWrap).split(`
`);
for (let i2 = 0;i2 < pieces.length; i2++) {
outLines.push(pieces[i2]);
softWrap.push(i2 > 0);
}
}
return { wrapped: outLines.join(`
`), softWrap };
}
function applyPaddingToText(node, text, softWrap) {
const yogaNode = node.childNodes[0]?.yogaNode;
if (yogaNode) {
const offsetX = yogaNode.getComputedLeft();
const offsetY = yogaNode.getComputedTop();
text = `
`.repeat(offsetY) + indentString(text, offsetX);
if (softWrap && offsetY > 0) {
softWrap.unshift(...Array(offsetY).fill(false));
}
}
return text;
}
function renderNodeToOutput(node, output, {
offsetX = 0,
offsetY = 0,
prevScreen,
skipSelfBlit = false,
inheritedBackgroundColor
}) {
const { yogaNode } = node;
if (yogaNode) {
if (yogaNode.getDisplay() === LayoutDisplay.None) {
if (node.dirty) {
const cached3 = nodeCache.get(node);
if (cached3) {
output.clear({
x: Math.floor(cached3.x),
y: Math.floor(cached3.y),
width: Math.floor(cached3.width),
height: Math.floor(cached3.height)
});
dropSubtreeCache(node);
layoutShifted = true;
}
}
return;
}
const x2 = offsetX + yogaNode.getComputedLeft();
const yogaTop = yogaNode.getComputedTop();
let y2 = offsetY + yogaTop;
const width = yogaNode.getComputedWidth();
const height = yogaNode.getComputedHeight();
if (y2 < 0 && node.style.position === "absolute") {
y2 = 0;
}
const cached2 = nodeCache.get(node);
if (!node.dirty && !skipSelfBlit && node.pendingScrollDelta === undefined && cached2 && cached2.x === x2 && cached2.y === y2 && cached2.width === width && cached2.height === height && prevScreen) {
const fx = Math.floor(x2);
const fy = Math.floor(y2);
const fw = Math.floor(width);
const fh = Math.floor(height);
output.blit(prevScreen, fx, fy, fw, fh);
if (node.style.position === "absolute") {
absoluteRectsCur.push(cached2);
}
blitEscapingAbsoluteDescendants(node, output, prevScreen, fx, fy, fw, fh);
return;
}
const positionChanged = cached2 !== undefined && (cached2.x !== x2 || cached2.y !== y2 || cached2.width !== width || cached2.height !== height);
if (positionChanged) {
layoutShifted = true;
}
if (cached2 && (node.dirty || positionChanged)) {
output.clear({
x: Math.floor(cached2.x),
y: Math.floor(cached2.y),
width: Math.floor(cached2.width),
height: Math.floor(cached2.height)
}, node.style.position === "absolute");
}
const clears = pendingClears.get(node);
const hasRemovedChild = clears !== undefined;
if (hasRemovedChild) {
layoutShifted = true;
for (const rect2 of clears) {
output.clear({
x: Math.floor(rect2.x),
y: Math.floor(rect2.y),
width: Math.floor(rect2.width),
height: Math.floor(rect2.height)
});
}
pendingClears.delete(node);
}
if (height === 0 && siblingSharesY(node, yogaNode)) {
nodeCache.set(node, { x: x2, y: y2, width, height, top: yogaTop });
node.dirty = false;
return;
}
if (node.nodeName === "ink-raw-ansi") {
const text = node.attributes["rawText"];
if (text) {
output.write(x2, y2, text);
}
} else if (node.nodeName === "ink-text") {
const segments = squashTextNodesToSegments(node, inheritedBackgroundColor ? { backgroundColor: inheritedBackgroundColor } : undefined);
const plainText = segments.map((s) => s.text).join("");
if (plainText.length > 0) {
const maxWidth = Math.min(get_max_width_default(yogaNode), output.width - x2);
const textWrap = node.style.textWrap ?? "wrap";
const needsWrapping = widestLine(plainText) > maxWidth;
let text;
let softWrap;
if (needsWrapping && segments.length === 1) {
const segment = segments[0];
const w = wrapWithSoftWrap(plainText, maxWidth, textWrap);
softWrap = w.softWrap;
text = w.wrapped.split(`
`).map((line) => {
let styled = applyTextStyles(line, segment.styles);
if (segment.hyperlink) {
styled = wrapWithOsc8Link(styled, segment.hyperlink);
}
return styled;
}).join(`
`);
} else if (needsWrapping) {
const w = wrapWithSoftWrap(plainText, maxWidth, textWrap);
softWrap = w.softWrap;
const charToSegment = buildCharToSegmentMap(segments);
text = applyStylesToWrappedText(w.wrapped, segments, charToSegment, plainText, textWrap === "wrap-trim");
} else {
text = segments.map((segment) => {
let styledText = applyTextStyles(segment.text, segment.styles);
if (segment.hyperlink) {
styledText = wrapWithOsc8Link(styledText, segment.hyperlink);
}
return styledText;
}).join("");
}
text = applyPaddingToText(node, text, softWrap);
output.write(x2, y2, text, softWrap);
}
} else if (node.nodeName === "ink-box") {
const boxBackgroundColor = node.style.backgroundColor ?? inheritedBackgroundColor;
if (node.style.noSelect) {
const boxX = Math.floor(x2);
const fromEdge = node.style.noSelect === "from-left-edge";
output.noSelect({
x: fromEdge ? 0 : boxX,
y: Math.floor(y2),
width: fromEdge ? boxX + Math.floor(width) : Math.floor(width),
height: Math.floor(height)
});
}
const overflowX = node.style.overflowX ?? node.style.overflow;
const overflowY = node.style.overflowY ?? node.style.overflow;
const clipHorizontally = overflowX === "hidden" || overflowX === "scroll";
const clipVertically = overflowY === "hidden" || overflowY === "scroll";
const isScrollY = overflowY === "scroll";
const needsClip = clipHorizontally || clipVertically;
let y1;
let y22;
if (needsClip) {
const x1 = clipHorizontally ? x2 + yogaNode.getComputedBorder(LayoutEdge.Left) : undefined;
const x22 = clipHorizontally ? x2 + yogaNode.getComputedWidth() - yogaNode.getComputedBorder(LayoutEdge.Right) : undefined;
y1 = clipVertically ? y2 + yogaNode.getComputedBorder(LayoutEdge.Top) : undefined;
y22 = clipVertically ? y2 + yogaNode.getComputedHeight() - yogaNode.getComputedBorder(LayoutEdge.Bottom) : undefined;
output.clip({ x1, x2: x22, y1, y2: y22 });
}
if (isScrollY) {
const padTop = yogaNode.getComputedPadding(LayoutEdge.Top);
const innerHeight = Math.max(0, (y22 ?? y2 + height) - (y1 ?? y2) - padTop - yogaNode.getComputedPadding(LayoutEdge.Bottom));
const content = node.childNodes.find((c6) => c6.yogaNode);
const contentYoga = content?.yogaNode;
const scrollHeight = contentYoga?.getComputedHeight() ?? 0;
const prevScrollHeight = node.scrollHeight ?? scrollHeight;
const prevInnerHeight = node.scrollViewportHeight ?? innerHeight;
node.scrollHeight = scrollHeight;
node.scrollViewportHeight = innerHeight;
node.scrollViewportTop = (y1 ?? y2) + padTop;
const maxScroll = Math.max(0, scrollHeight - innerHeight);
if (node.scrollAnchor) {
const anchorTop = node.scrollAnchor.el.yogaNode?.getComputedTop();
if (anchorTop != null) {
node.scrollTop = anchorTop + node.scrollAnchor.offset;
node.pendingScrollDelta = undefined;
}
node.scrollAnchor = undefined;
}
const scrollTopBeforeFollow = node.scrollTop ?? 0;
const sticky = node.stickyScroll ?? Boolean(node.attributes["stickyScroll"]);
const prevMaxScroll = Math.max(0, prevScrollHeight - prevInnerHeight);
const grew = scrollHeight >= prevScrollHeight;
const atBottom = sticky || grew && scrollTopBeforeFollow >= prevMaxScroll;
if (atBottom && (node.pendingScrollDelta ?? 0) >= 0) {
node.scrollTop = maxScroll;
node.pendingScrollDelta = undefined;
if (node.stickyScroll === false && scrollTopBeforeFollow >= prevMaxScroll) {
node.stickyScroll = true;
}
}
const followDelta = (node.scrollTop ?? 0) - scrollTopBeforeFollow;
if (followDelta > 0) {
const vpTop = node.scrollViewportTop ?? 0;
followScroll = {
delta: followDelta,
viewportTop: vpTop,
viewportBottom: vpTop + innerHeight - 1
};
}
let cur = node.scrollTop ?? 0;
const pending = node.pendingScrollDelta;
const cMin = node.scrollClampMin;
const cMax = node.scrollClampMax;
const haveClamp = cMin !== undefined && cMax !== undefined;
if (pending !== undefined && pending !== 0) {
const pastClamp = haveClamp && (pending < 0 && cur < cMin || pending > 0 && cur > cMax);
const eff = pastClamp ? Math.min(4, innerHeight >> 3) : innerHeight;
cur += isXtermJsHost() ? drainAdaptive(node, pending, eff) : drainProportional(node, pending, eff);
} else if (pending === 0) {
node.pendingScrollDelta = undefined;
}
let scrollTop = Math.max(0, Math.min(cur, maxScroll));
const clamped = haveClamp ? Math.max(cMin, Math.min(scrollTop, cMax)) : scrollTop;
node.scrollTop = scrollTop;
if (scrollTop !== cur)
node.pendingScrollDelta = undefined;
if (node.pendingScrollDelta !== undefined)
scrollDrainNode = node;
scrollTop = clamped;
if (content && contentYoga) {
const contentX = x2 + contentYoga.getComputedLeft();
const contentY = y2 + contentYoga.getComputedTop() - scrollTop;
const contentCached = nodeCache.get(content);
let hint = null;
if (contentCached && contentCached.y !== contentY) {
const delta = contentCached.y - contentY;
const regionTop = Math.floor(y2 + contentYoga.getComputedTop());
const regionBottom = regionTop + innerHeight - 1;
if (cached2?.y === y2 && cached2.height === height && innerHeight > 0 && Math.abs(delta) < innerHeight) {
hint = { top: regionTop, bottom: regionBottom, delta };
scrollHint = hint;
} else {
layoutShifted = true;
}
}
const scrollHeight2 = contentYoga.getComputedHeight();
const prevHeight = contentCached?.height ?? scrollHeight2;
const heightDelta = scrollHeight2 - prevHeight;
const safeForFastPath = !hint || heightDelta === 0 || hint.delta > 0 && heightDelta === hint.delta;
if (!safeForFastPath)
scrollHint = null;
if (hint && prevScreen && safeForFastPath) {
const { top, bottom, delta } = hint;
const w = Math.floor(width);
output.blit(prevScreen, Math.floor(x2), top, w, bottom - top + 1);
output.shift(top, bottom, delta);
const edgeTop = delta > 0 ? bottom - delta + 1 : top;
const edgeBottom = delta > 0 ? bottom : top - delta - 1;
output.clear({
x: Math.floor(x2),
y: edgeTop,
width: w,
height: edgeBottom - edgeTop + 1
});
output.clip({
x1: undefined,
x2: undefined,
y1: edgeTop,
y2: edgeBottom + 1
});
const dirtyChildren = content.dirty ? new Set(content.childNodes.filter((c6) => c6.dirty)) : null;
renderScrolledChildren(content, output, contentX, contentY, hasRemovedChild, undefined, edgeTop - contentY, edgeBottom + 1 - contentY, boxBackgroundColor, true);
output.unclip();
if (dirtyChildren) {
const edgeTopLocal = edgeTop - contentY;
const edgeBottomLocal = edgeBottom + 1 - contentY;
const spaces2 = " ".repeat(w);
let cumHeightShift = 0;
for (const childNode of content.childNodes) {
const childElem = childNode;
const isDirty = dirtyChildren.has(childNode);
if (!isDirty && cumHeightShift === 0) {
if (nodeCache.has(childElem))
continue;
}
const cy = childElem.yogaNode;
if (!cy)
continue;
const childTop = cy.getComputedTop();
const childH = cy.getComputedHeight();
const childBottom = childTop + childH;
if (isDirty) {
const prev = nodeCache.get(childElem);
cumHeightShift += childH - (prev ? prev.height : 0);
}
if (childBottom <= scrollTop || childTop >= scrollTop + innerHeight)
continue;
if (childTop >= edgeTopLocal && childBottom <= edgeBottomLocal)
continue;
const screenY = Math.floor(contentY + childTop);
if (!isDirty) {
const childCached = nodeCache.get(childElem);
if (childCached && Math.floor(childCached.y) - delta === screenY) {
continue;
}
}
const screenBottom = Math.min(Math.floor(contentY + childBottom), Math.floor((y1 ?? y2) + padTop + innerHeight));
if (screenY < screenBottom) {
const fill = Array(screenBottom - screenY).fill(spaces2).join(`
`);
output.write(Math.floor(x2), screenY, fill);
output.clip({
x1: undefined,
x2: undefined,
y1: screenY,
y2: screenBottom
});
renderNodeToOutput(childElem, output, {
offsetX: contentX,
offsetY: contentY,
prevScreen: undefined,
inheritedBackgroundColor: boxBackgroundColor
});
output.unclip();
}
}
}
const spaces = absoluteRectsPrev.length ? " ".repeat(w) : "";
for (const r of absoluteRectsPrev) {
if (r.y >= bottom + 1 || r.y + r.height <= top)
continue;
const shiftedTop = Math.max(top, Math.floor(r.y) - delta);
const shiftedBottom = Math.min(bottom + 1, Math.floor(r.y + r.height) - delta);
if (shiftedTop >= edgeTop && shiftedBottom <= edgeBottom + 1)
continue;
if (shiftedTop >= shiftedBottom)
continue;
const fill = Array(shiftedBottom - shiftedTop).fill(spaces).join(`
`);
output.write(Math.floor(x2), shiftedTop, fill);
output.clip({
x1: undefined,
x2: undefined,
y1: shiftedTop,
y2: shiftedBottom
});
renderScrolledChildren(content, output, contentX, contentY, hasRemovedChild, undefined, shiftedTop - contentY, shiftedBottom - contentY, boxBackgroundColor, true);
output.unclip();
}
} else {
const scrolled = contentCached && contentCached.y !== contentY;
if (scrolled && y1 !== undefined && y22 !== undefined) {
output.clear({
x: Math.floor(x2),
y: Math.floor(y1),
width: Math.floor(width),
height: Math.floor(y22 - y1)
});
}
renderScrolledChildren(content, output, contentX, contentY, hasRemovedChild, scrolled || positionChanged ? undefined : prevScreen, scrollTop, scrollTop + innerHeight, boxBackgroundColor);
}
nodeCache.set(content, {
x: contentX,
y: contentY,
width: contentYoga.getComputedWidth(),
height: contentYoga.getComputedHeight()
});
content.dirty = false;
}
} else {
const ownBackgroundColor = node.style.backgroundColor;
if (ownBackgroundColor || node.style.opaque) {
const borderLeft = yogaNode.getComputedBorder(LayoutEdge.Left);
const borderRight = yogaNode.getComputedBorder(LayoutEdge.Right);
const borderTop = yogaNode.getComputedBorder(LayoutEdge.Top);
const borderBottom = yogaNode.getComputedBorder(LayoutEdge.Bottom);
const innerWidth = Math.floor(width) - borderLeft - borderRight;
const innerHeight = Math.floor(height) - borderTop - borderBottom;
if (innerWidth > 0 && innerHeight > 0) {
const spaces = " ".repeat(innerWidth);
const fillLine = ownBackgroundColor ? applyTextStyles(spaces, { backgroundColor: ownBackgroundColor }) : spaces;
const fill = Array(innerHeight).fill(fillLine).join(`
`);
output.write(x2 + borderLeft, y2 + borderTop, fill);
}
}
renderChildren(node, output, x2, y2, hasRemovedChild, ownBackgroundColor || node.style.opaque ? undefined : prevScreen, boxBackgroundColor);
}
if (needsClip) {
output.unclip();
}
render_border_default(x2, y2, node, output);
} else if (node.nodeName === "ink-root") {
renderChildren(node, output, x2, y2, hasRemovedChild, prevScreen, inheritedBackgroundColor);
}
const rect = { x: x2, y: y2, width, height, top: yogaTop };
nodeCache.set(node, rect);
if (node.style.position === "absolute") {
absoluteRectsCur.push(rect);
}
node.dirty = false;
}
}
function renderChildren(node, output, offsetX, offsetY, hasRemovedChild, prevScreen, inheritedBackgroundColor) {
let seenDirtyChild = false;
let seenDirtyClipped = false;
for (const childNode of node.childNodes) {
const childElem = childNode;
const wasDirty = childElem.dirty;
const isAbsolute5 = childElem.style.position === "absolute";
renderNodeToOutput(childElem, output, {
offsetX,
offsetY,
prevScreen: hasRemovedChild || seenDirtyChild ? undefined : prevScreen,
skipSelfBlit: seenDirtyClipped && isAbsolute5 && !childElem.style.opaque && childElem.style.backgroundColor === undefined,
inheritedBackgroundColor
});
if (wasDirty && !seenDirtyChild) {
if (!clipsBothAxes(childElem) || isAbsolute5) {
seenDirtyChild = true;
} else {
seenDirtyClipped = true;
}
}
}
}
function clipsBothAxes(node) {
const ox = node.style.overflowX ?? node.style.overflow;
const oy = node.style.overflowY ?? node.style.overflow;
return (ox === "hidden" || ox === "scroll") && (oy === "hidden" || oy === "scroll");
}
function siblingSharesY(node, yogaNode) {
const parent = node.parentNode;
if (!parent)
return false;
const myTop = yogaNode.getComputedTop();
const siblings = parent.childNodes;
const idx = siblings.indexOf(node);
for (let i2 = idx + 1;i2 < siblings.length; i2++) {
const sib = siblings[i2].yogaNode;
if (!sib)
continue;
return sib.getComputedTop() === myTop;
}
for (let i2 = idx - 1;i2 >= 0; i2--) {
const sib = siblings[i2].yogaNode;
if (!sib)
continue;
return sib.getComputedTop() === myTop;
}
return false;
}
function blitEscapingAbsoluteDescendants(node, output, prevScreen, px, py, pw, ph) {
const pr = px + pw;
const pb = py + ph;
for (const child of node.childNodes) {
if (child.nodeName === "#text")
continue;
const elem = child;
if (elem.style.position === "absolute") {
const cached2 = nodeCache.get(elem);
if (cached2) {
absoluteRectsCur.push(cached2);
const cx = Math.floor(cached2.x);
const cy = Math.floor(cached2.y);
const cw = Math.floor(cached2.width);
const ch = Math.floor(cached2.height);
if (cx < px || cy < py || cx + cw > pr || cy + ch > pb) {
output.blit(prevScreen, cx, cy, cw, ch);
}
}
}
blitEscapingAbsoluteDescendants(elem, output, prevScreen, px, py, pw, ph);
}
}
function renderScrolledChildren(node, output, offsetX, offsetY, hasRemovedChild, prevScreen, scrollTopY, scrollBottomY, inheritedBackgroundColor, preserveCulledCache = false) {
let seenDirtyChild = false;
let cumHeightShift = 0;
for (const childNode of node.childNodes) {
const childElem = childNode;
const cy = childElem.yogaNode;
if (cy) {
const cached2 = nodeCache.get(childElem);
let top;
let height;
if (cached2?.top !== undefined && !childElem.dirty && cumHeightShift === 0) {
top = cached2.top;
height = cached2.height;
} else {
top = cy.getComputedTop();
height = cy.getComputedHeight();
if (childElem.dirty) {
cumHeightShift += height - (cached2 ? cached2.height : 0);
}
if (cached2)
cached2.top = top;
}
const bottom = top + height;
if (bottom <= scrollTopY || top >= scrollBottomY) {
if (!preserveCulledCache)
dropSubtreeCache(childElem);
continue;
}
}
const wasDirty = childElem.dirty;
renderNodeToOutput(childElem, output, {
offsetX,
offsetY,
prevScreen: hasRemovedChild || seenDirtyChild ? undefined : prevScreen,
inheritedBackgroundColor
});
if (wasDirty) {
seenDirtyChild = true;
}
}
}
function dropSubtreeCache(node) {
nodeCache.delete(node);
for (const child of node.childNodes) {
if (child.nodeName !== "#text") {
dropSubtreeCache(child);
}
}
}
var layoutShifted = false, scrollHint = null, absoluteRectsPrev, absoluteRectsCur, scrollDrainNode = null, followScroll = null, SCROLL_MIN_PER_FRAME = 4, SCROLL_INSTANT_THRESHOLD = 5, SCROLL_HIGH_PENDING = 12, SCROLL_STEP_MED = 2, SCROLL_STEP_HIGH = 3, SCROLL_MAX_PENDING = 30, OSC3 = "\x1B]", BEL3 = "\x07", render_node_to_output_default;
var init_render_node_to_output = __esm(() => {
init_colorize();
init_get_max_width();
init_node4();
init_node_cache();
init_render_border();
init_squash_text_nodes();
init_terminal();
init_widest_line();
init_wrap_text();
absoluteRectsPrev = [];
absoluteRectsCur = [];
render_node_to_output_default = renderNodeToOutput;
});
// src/ink/render-to-screen.ts
function scanPositions(screen, query) {
const lq = query.toLowerCase();
if (!lq)
return [];
const qlen = lq.length;
const w = screen.width;
const h2 = screen.height;
const noSelect = screen.noSelect;
const positions = [];
const t0 = performance.now();
for (let row = 0;row < h2; row++) {
const rowOff = row * w;
let text = "";
const colOf = [];
const codeUnitToCell = [];
for (let col = 0;col < w; col++) {
const idx = rowOff + col;
const cell = cellAtIndex(screen, idx);
if (cell.width === 2 /* SpacerTail */ || cell.width === 3 /* SpacerHead */ || noSelect[idx] === 1) {
continue;
}
const lc = cell.char.toLowerCase();
const cellIdx = colOf.length;
for (let i2 = 0;i2 < lc.length; i2++) {
codeUnitToCell.push(cellIdx);
}
text += lc;
colOf.push(col);
}
let pos = text.indexOf(lq);
while (pos >= 0) {
const startCi = codeUnitToCell[pos];
const endCi = codeUnitToCell[pos + qlen - 1];
const col = colOf[startCi];
const endCol = colOf[endCi] + 1;
positions.push({ row, col, len: endCol - col });
pos = text.indexOf(lq, pos + qlen);
}
}
timing.scan += performance.now() - t0;
return positions;
}
function applyPositionedHighlight(screen, stylePool, positions, rowOffset, currentIdx) {
if (currentIdx < 0 || currentIdx >= positions.length)
return false;
const p = positions[currentIdx];
const row = p.row + rowOffset;
if (row < 0 || row >= screen.height)
return false;
const transform2 = (id) => stylePool.withCurrentMatch(id);
const rowOff = row * screen.width;
for (let col = p.col;col < p.col + p.len; col++) {
if (col < 0 || col >= screen.width)
continue;
const cell = cellAtIndex(screen, rowOff + col);
setCellStyleId(screen, col, row, transform2(cell.styleId));
}
return true;
}
var import_constants15, timing;
var init_render_to_screen = __esm(() => {
init_debug();
init_dom();
init_focus();
init_output2();
init_reconciler();
init_render_node_to_output();
init_screen();
import_constants15 = __toESM(require_constants7(), 1);
timing = { reconcile: 0, yoga: 0, paint: 0, scan: 0, calls: 0 };
});
// src/ink/renderer.ts
function createRenderer(node, stylePool) {
let output;
return (options) => {
const { frontFrame, backFrame, isTTY, terminalWidth, terminalRows } = options;
const prevScreen = frontFrame.screen;
const backScreen = backFrame.screen;
const charPool = backScreen.charPool;
const hyperlinkPool = backScreen.hyperlinkPool;
const computedHeight = node.yogaNode?.getComputedHeight();
const computedWidth = node.yogaNode?.getComputedWidth();
const hasInvalidHeight = computedHeight === undefined || !Number.isFinite(computedHeight) || computedHeight < 0;
const hasInvalidWidth = computedWidth === undefined || !Number.isFinite(computedWidth) || computedWidth < 0;
if (!node.yogaNode || hasInvalidHeight || hasInvalidWidth) {
if (node.yogaNode && (hasInvalidHeight || hasInvalidWidth)) {
logForDebugging(`Invalid yoga dimensions: width=${computedWidth}, height=${computedHeight}, ` + `childNodes=${node.childNodes.length}, terminalWidth=${terminalWidth}, terminalRows=${terminalRows}`);
}
return {
screen: createScreen(terminalWidth, 0, stylePool, charPool, hyperlinkPool),
viewport: { width: terminalWidth, height: terminalRows },
cursor: { x: 0, y: 0, visible: true }
};
}
const width = Math.floor(node.yogaNode.getComputedWidth());
const yogaHeight = Math.floor(node.yogaNode.getComputedHeight());
const height = options.altScreen ? terminalRows : yogaHeight;
if (options.altScreen && yogaHeight > terminalRows) {
logForDebugging(`alt-screen: yoga height ${yogaHeight} > terminalRows ${terminalRows} — ` + `something is rendering outside . Overflow clipped.`, { level: "warn" });
}
const screen = backScreen ?? createScreen(width, height, stylePool, charPool, hyperlinkPool);
if (output) {
output.reset(width, height, screen);
} else {
output = new Output({ width, height, stylePool, screen });
}
resetLayoutShifted();
resetScrollHint();
resetScrollDrainNode();
const absoluteRemoved = consumeAbsoluteRemovedFlag();
render_node_to_output_default(node, output, {
prevScreen: absoluteRemoved || options.prevFrameContaminated ? undefined : prevScreen
});
const renderedScreen = output.get();
const drainNode = getScrollDrainNode();
if (drainNode)
markDirty(drainNode);
return {
scrollHint: options.altScreen ? getScrollHint() : null,
scrollDrainPending: drainNode !== null,
screen: renderedScreen,
viewport: {
width: terminalWidth,
height: options.altScreen ? terminalRows + 1 : terminalRows
},
cursor: {
x: 0,
y: options.altScreen ? Math.max(0, Math.min(screen.height, terminalRows) - 1) : screen.height,
visible: !isTTY || screen.height === 0
}
};
};
}
var init_renderer = __esm(() => {
init_debug();
init_dom();
init_node_cache();
init_output2();
init_render_node_to_output();
init_screen();
});
// src/ink/searchHighlight.ts
function applySearchHighlight(screen, query, stylePool) {
if (!query)
return false;
const lq = query.toLowerCase();
const qlen = lq.length;
const w = screen.width;
const noSelect = screen.noSelect;
const height = screen.height;
let applied = false;
for (let row = 0;row < height; row++) {
const rowOff = row * w;
let text = "";
const colOf = [];
const codeUnitToCell = [];
for (let col = 0;col < w; col++) {
const idx = rowOff + col;
const cell = cellAtIndex(screen, idx);
if (cell.width === 2 /* SpacerTail */ || cell.width === 3 /* SpacerHead */ || noSelect[idx] === 1) {
continue;
}
const lc = cell.char.toLowerCase();
const cellIdx = colOf.length;
for (let i2 = 0;i2 < lc.length; i2++) {
codeUnitToCell.push(cellIdx);
}
text += lc;
colOf.push(col);
}
let pos = text.indexOf(lq);
while (pos >= 0) {
applied = true;
const startCi = codeUnitToCell[pos];
const endCi = codeUnitToCell[pos + qlen - 1];
for (let ci = startCi;ci <= endCi; ci++) {
const col = colOf[ci];
const cell = cellAtIndex(screen, rowOff + col);
setCellStyleId(screen, col, row, stylePool.withInverse(cell.styleId));
}
pos = text.indexOf(lq, pos + qlen);
}
}
return applied;
}
var init_searchHighlight = __esm(() => {
init_screen();
});
// src/ink/useTerminalNotification.ts
function useTerminalNotification() {
const writeRaw = import_react11.useContext(TerminalWriteContext);
if (!writeRaw) {
throw new Error("useTerminalNotification must be used within TerminalWriteProvider");
}
const notifyITerm2 = import_react11.useCallback(({ message, title }) => {
const displayString = title ? `${title}:
${message}` : message;
writeRaw(wrapForMultiplexer(osc(OSC2.ITERM2, `
${displayString}`)));
}, [writeRaw]);
const notifyKitty = import_react11.useCallback(({
message,
title,
id
}) => {
writeRaw(wrapForMultiplexer(osc(OSC2.KITTY, `i=${id}:d=0:p=title`, title)));
writeRaw(wrapForMultiplexer(osc(OSC2.KITTY, `i=${id}:p=body`, message)));
writeRaw(wrapForMultiplexer(osc(OSC2.KITTY, `i=${id}:d=1:a=focus`, "")));
}, [writeRaw]);
const notifyGhostty = import_react11.useCallback(({ message, title }) => {
writeRaw(wrapForMultiplexer(osc(OSC2.GHOSTTY, "notify", title, message)));
}, [writeRaw]);
const notifyBell = import_react11.useCallback(() => {
writeRaw(BEL);
}, [writeRaw]);
const progress = import_react11.useCallback((state, percentage) => {
if (!isProgressReportingAvailable()) {
return;
}
if (!state) {
writeRaw(wrapForMultiplexer(osc(OSC2.ITERM2, ITERM2.PROGRESS, PROGRESS.CLEAR, "")));
return;
}
const pct = Math.max(0, Math.min(100, Math.round(percentage ?? 0)));
switch (state) {
case "completed":
writeRaw(wrapForMultiplexer(osc(OSC2.ITERM2, ITERM2.PROGRESS, PROGRESS.CLEAR, "")));
break;
case "error":
writeRaw(wrapForMultiplexer(osc(OSC2.ITERM2, ITERM2.PROGRESS, PROGRESS.ERROR, pct)));
break;
case "indeterminate":
writeRaw(wrapForMultiplexer(osc(OSC2.ITERM2, ITERM2.PROGRESS, PROGRESS.INDETERMINATE, "")));
break;
case "running":
writeRaw(wrapForMultiplexer(osc(OSC2.ITERM2, ITERM2.PROGRESS, PROGRESS.SET, pct)));
break;
case null:
break;
}
}, [writeRaw]);
return import_react11.useMemo(() => ({ notifyITerm2, notifyKitty, notifyGhostty, notifyBell, progress }), [notifyITerm2, notifyKitty, notifyGhostty, notifyBell, progress]);
}
var import_react11, TerminalWriteContext, TerminalWriteProvider;
var init_useTerminalNotification = __esm(() => {
init_terminal();
init_ansi();
init_osc();
import_react11 = __toESM(require_react(), 1);
TerminalWriteContext = import_react11.createContext(null);
TerminalWriteProvider = TerminalWriteContext.Provider;
});
// src/ink/ink.tsx
import { closeSync as closeSync3, constants as fsConstants, openSync as openSync3, readSync as readSync2, writeSync } from "fs";
import { format as format3 } from "util";
function makeAltScreenParkPatch(terminalRows) {
return Object.freeze({
type: "stdout",
content: cursorPosition(terminalRows, 1)
});
}
class Ink {
options;
log;
terminal;
scheduleRender;
isUnmounted = false;
isPaused = false;
container;
rootNode;
focusManager;
renderer;
stylePool;
charPool;
hyperlinkPool;
exitPromise;
restoreConsole;
restoreStderr;
unsubscribeTTYHandlers;
terminalColumns;
terminalRows;
currentNode = null;
frontFrame;
backFrame;
lastPoolResetTime = performance.now();
drainTimer = null;
lastYogaCounters = {
ms: 0,
visited: 0,
measured: 0,
cacheHits: 0,
live: 0
};
altScreenParkPatch;
selection = createSelectionState();
searchHighlightQuery = "";
searchPositions = null;
selectionListeners = new Set;
hoveredNodes = new Set;
altScreenActive = false;
altScreenMouseTracking = false;
prevFrameContaminated = false;
needsEraseBeforePaint = false;
cursorDeclaration = null;
displayCursor = null;
constructor(options) {
this.options = options;
autoBind(this);
if (this.options.patchConsole) {
this.restoreConsole = this.patchConsole();
this.restoreStderr = this.patchStderr();
}
this.terminal = {
stdout: options.stdout,
stderr: options.stderr
};
this.terminalColumns = options.stdout.columns || 80;
this.terminalRows = options.stdout.rows || 24;
this.altScreenParkPatch = makeAltScreenParkPatch(this.terminalRows);
this.stylePool = new StylePool;
this.charPool = new CharPool;
this.hyperlinkPool = new HyperlinkPool;
this.frontFrame = emptyFrame(this.terminalRows, this.terminalColumns, this.stylePool, this.charPool, this.hyperlinkPool);
this.backFrame = emptyFrame(this.terminalRows, this.terminalColumns, this.stylePool, this.charPool, this.hyperlinkPool);
this.log = new LogUpdate({
isTTY: options.stdout.isTTY || false,
stylePool: this.stylePool
});
const deferredRender = () => queueMicrotask(this.onRender);
this.scheduleRender = throttle_default2(deferredRender, FRAME_INTERVAL_MS, {
leading: true,
trailing: true
});
this.isUnmounted = false;
this.unsubscribeExit = onExit(this.unmount, {
alwaysLast: false
});
if (options.stdout.isTTY) {
options.stdout.on("resize", this.handleResize);
process.on("SIGCONT", this.handleResume);
this.unsubscribeTTYHandlers = () => {
options.stdout.off("resize", this.handleResize);
process.off("SIGCONT", this.handleResume);
};
}
this.rootNode = createNode("ink-root");
this.focusManager = new FocusManager((target, event) => dispatcher.dispatchDiscrete(target, event));
this.rootNode.focusManager = this.focusManager;
this.renderer = createRenderer(this.rootNode, this.stylePool);
this.rootNode.onRender = this.scheduleRender;
this.rootNode.onImmediateRender = this.onRender;
this.rootNode.onComputeLayout = () => {
if (this.isUnmounted) {
return;
}
if (this.rootNode.yogaNode) {
const t0 = performance.now();
this.rootNode.yogaNode.setWidth(this.terminalColumns);
this.rootNode.yogaNode.calculateLayout(this.terminalColumns);
const ms = performance.now() - t0;
recordYogaMs(ms);
const c6 = getYogaCounters();
this.lastYogaCounters = {
ms,
...c6
};
}
};
this.container = reconciler_default.createContainer(this.rootNode, import_constants16.ConcurrentRoot, null, false, null, "id", noop_default, noop_default, noop_default, noop_default);
if (false) {}
}
handleResume = () => {
if (!this.options.stdout.isTTY) {
return;
}
if (this.altScreenActive) {
this.reenterAltScreen();
return;
}
this.frontFrame = emptyFrame(this.frontFrame.viewport.height, this.frontFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
this.backFrame = emptyFrame(this.backFrame.viewport.height, this.backFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
this.log.reset();
this.displayCursor = null;
};
handleResize = () => {
const cols = this.options.stdout.columns || 80;
const rows = this.options.stdout.rows || 24;
if (cols === this.terminalColumns && rows === this.terminalRows)
return;
this.terminalColumns = cols;
this.terminalRows = rows;
this.altScreenParkPatch = makeAltScreenParkPatch(this.terminalRows);
if (this.altScreenActive && !this.isPaused && this.options.stdout.isTTY) {
if (this.altScreenMouseTracking) {
this.options.stdout.write(ENABLE_MOUSE_TRACKING);
}
this.resetFramesForAltScreen();
this.needsEraseBeforePaint = true;
}
if (this.currentNode !== null) {
this.render(this.currentNode);
}
};
resolveExitPromise = () => {};
rejectExitPromise = () => {};
unsubscribeExit = () => {};
enterAlternateScreen() {
this.pause();
this.suspendStdin();
this.options.stdout.write(DISABLE_KITTY_KEYBOARD + DISABLE_MODIFY_OTHER_KEYS + (this.altScreenMouseTracking ? DISABLE_MOUSE_TRACKING : "") + (this.altScreenActive ? "" : "\x1B[?1049h") + "\x1B[?1004l" + "\x1B[0m" + "\x1B[?25h" + "\x1B[2J" + "\x1B[H");
}
exitAlternateScreen() {
this.options.stdout.write((this.altScreenActive ? ENTER_ALT_SCREEN : "") + "\x1B[2J" + "\x1B[H" + (this.altScreenMouseTracking ? ENABLE_MOUSE_TRACKING : "") + (this.altScreenActive ? "" : "\x1B[?1049l") + "\x1B[?25l");
this.resumeStdin();
if (this.altScreenActive) {
this.resetFramesForAltScreen();
} else {
this.repaint();
}
this.resume();
this.options.stdout.write("\x1B[?1004h" + (supportsExtendedKeys() ? DISABLE_KITTY_KEYBOARD + ENABLE_KITTY_KEYBOARD + ENABLE_MODIFY_OTHER_KEYS : ""));
}
onRender() {
if (this.isUnmounted || this.isPaused) {
return;
}
if (this.drainTimer !== null) {
clearTimeout(this.drainTimer);
this.drainTimer = null;
}
flushInteractionTime();
const renderStart = performance.now();
const terminalWidth = this.options.stdout.columns || 80;
const terminalRows = this.options.stdout.rows || 24;
const frame = this.renderer({
frontFrame: this.frontFrame,
backFrame: this.backFrame,
isTTY: this.options.stdout.isTTY,
terminalWidth,
terminalRows,
altScreen: this.altScreenActive,
prevFrameContaminated: this.prevFrameContaminated
});
const rendererMs = performance.now() - renderStart;
const follow = consumeFollowScroll();
if (follow && this.selection.anchor && this.selection.anchor.row >= follow.viewportTop && this.selection.anchor.row <= follow.viewportBottom) {
const {
delta,
viewportTop,
viewportBottom
} = follow;
if (this.selection.isDragging) {
if (hasSelection(this.selection)) {
captureScrolledRows(this.selection, this.frontFrame.screen, viewportTop, viewportTop + delta - 1, "above");
}
shiftAnchor(this.selection, -delta, viewportTop, viewportBottom);
} else if (!this.selection.focus || this.selection.focus.row >= viewportTop && this.selection.focus.row <= viewportBottom) {
if (hasSelection(this.selection)) {
captureScrolledRows(this.selection, this.frontFrame.screen, viewportTop, viewportTop + delta - 1, "above");
}
const cleared = shiftSelectionForFollow(this.selection, -delta, viewportTop, viewportBottom);
if (cleared)
for (const cb of this.selectionListeners)
cb();
}
}
let selActive = false;
let hlActive = false;
if (this.altScreenActive) {
selActive = hasSelection(this.selection);
if (selActive) {
applySelectionOverlay(frame.screen, this.selection, this.stylePool);
}
hlActive = applySearchHighlight(frame.screen, this.searchHighlightQuery, this.stylePool);
if (this.searchPositions) {
const sp = this.searchPositions;
const posApplied = applyPositionedHighlight(frame.screen, this.stylePool, sp.positions, sp.rowOffset, sp.currentIdx);
hlActive = hlActive || posApplied;
}
}
if (didLayoutShift() || selActive || hlActive || this.prevFrameContaminated) {
frame.screen.damage = {
x: 0,
y: 0,
width: frame.screen.width,
height: frame.screen.height
};
}
let prevFrame = this.frontFrame;
if (this.altScreenActive) {
prevFrame = {
...this.frontFrame,
cursor: ALT_SCREEN_ANCHOR_CURSOR
};
}
const tDiff = performance.now();
const diff2 = this.log.render(prevFrame, frame, this.altScreenActive, SYNC_OUTPUT_SUPPORTED);
const diffMs = performance.now() - tDiff;
this.backFrame = this.frontFrame;
this.frontFrame = frame;
if (renderStart - this.lastPoolResetTime > 5 * 60 * 1000) {
this.resetPools();
this.lastPoolResetTime = renderStart;
}
const flickers = [];
for (const patch of diff2) {
if (patch.type === "clearTerminal") {
flickers.push({
desiredHeight: frame.screen.height,
availableHeight: frame.viewport.height,
reason: patch.reason
});
if (isDebugRepaintsEnabled() && patch.debug) {
const chain = findOwnerChainAtRow(this.rootNode, patch.debug.triggerY);
logForDebugging(`[REPAINT] full reset · ${patch.reason} · row ${patch.debug.triggerY}
` + ` prev: "${patch.debug.prevLine}"
` + ` next: "${patch.debug.nextLine}"
` + ` culprit: ${chain.length ? chain.join(" < ") : "(no owner chain captured)"}`, {
level: "warn"
});
}
}
}
const tOptimize = performance.now();
const optimized = optimize(diff2);
const optimizeMs = performance.now() - tOptimize;
const hasDiff = optimized.length > 0;
if (this.altScreenActive && hasDiff) {
if (this.needsEraseBeforePaint) {
this.needsEraseBeforePaint = false;
optimized.unshift(ERASE_THEN_HOME_PATCH);
} else {
optimized.unshift(CURSOR_HOME_PATCH);
}
optimized.push(this.altScreenParkPatch);
}
const decl = this.cursorDeclaration;
const rect = decl !== null ? nodeCache.get(decl.node) : undefined;
const target = decl !== null && rect !== undefined ? {
x: rect.x + decl.relativeX,
y: rect.y + decl.relativeY
} : null;
const parked = this.displayCursor;
const targetMoved = target !== null && (parked === null || parked.x !== target.x || parked.y !== target.y);
if (hasDiff || targetMoved || target === null && parked !== null) {
if (parked !== null && !this.altScreenActive && hasDiff) {
const pdx = prevFrame.cursor.x - parked.x;
const pdy = prevFrame.cursor.y - parked.y;
if (pdx !== 0 || pdy !== 0) {
optimized.unshift({
type: "stdout",
content: cursorMove(pdx, pdy)
});
}
}
if (target !== null) {
if (this.altScreenActive) {
const row = Math.min(Math.max(target.y + 1, 1), terminalRows);
const col = Math.min(Math.max(target.x + 1, 1), terminalWidth);
optimized.push({
type: "stdout",
content: cursorPosition(row, col)
});
} else {
const from = !hasDiff && parked !== null ? parked : {
x: frame.cursor.x,
y: frame.cursor.y
};
const dx = target.x - from.x;
const dy = target.y - from.y;
if (dx !== 0 || dy !== 0) {
optimized.push({
type: "stdout",
content: cursorMove(dx, dy)
});
}
}
this.displayCursor = target;
} else {
if (parked !== null && !this.altScreenActive && !hasDiff) {
const rdx = frame.cursor.x - parked.x;
const rdy = frame.cursor.y - parked.y;
if (rdx !== 0 || rdy !== 0) {
optimized.push({
type: "stdout",
content: cursorMove(rdx, rdy)
});
}
}
this.displayCursor = null;
}
}
const tWrite = performance.now();
writeDiffToTerminal(this.terminal, optimized, this.altScreenActive && !SYNC_OUTPUT_SUPPORTED);
const writeMs = performance.now() - tWrite;
this.prevFrameContaminated = selActive || hlActive;
if (frame.scrollDrainPending) {
this.drainTimer = setTimeout(() => this.onRender(), FRAME_INTERVAL_MS >> 2);
}
const yogaMs = getLastYogaMs();
const commitMs = getLastCommitMs();
const yc = this.lastYogaCounters;
resetProfileCounters();
this.lastYogaCounters = {
ms: 0,
visited: 0,
measured: 0,
cacheHits: 0,
live: 0
};
this.options.onFrame?.({
durationMs: performance.now() - renderStart,
phases: {
renderer: rendererMs,
diff: diffMs,
optimize: optimizeMs,
write: writeMs,
patches: diff2.length,
yoga: yogaMs,
commit: commitMs,
yogaVisited: yc.visited,
yogaMeasured: yc.measured,
yogaCacheHits: yc.cacheHits,
yogaLive: yc.live
},
flickers
});
}
pause() {
reconciler_default.flushSyncFromReconciler();
this.onRender();
this.isPaused = true;
}
resume() {
this.isPaused = false;
this.onRender();
}
repaint() {
this.frontFrame = emptyFrame(this.frontFrame.viewport.height, this.frontFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
this.backFrame = emptyFrame(this.backFrame.viewport.height, this.backFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
this.log.reset();
this.displayCursor = null;
}
forceRedraw() {
if (!this.options.stdout.isTTY || this.isUnmounted || this.isPaused)
return;
this.options.stdout.write(ERASE_SCREEN + CURSOR_HOME);
if (this.altScreenActive) {
this.resetFramesForAltScreen();
} else {
this.repaint();
this.prevFrameContaminated = true;
}
this.onRender();
}
invalidatePrevFrame() {
this.prevFrameContaminated = true;
}
setAltScreenActive(active, mouseTracking = false) {
if (this.altScreenActive === active)
return;
this.altScreenActive = active;
this.altScreenMouseTracking = active && mouseTracking;
if (active) {
this.resetFramesForAltScreen();
} else {
this.repaint();
}
}
get isAltScreenActive() {
return this.altScreenActive;
}
reassertTerminalModes = (includeAltScreen = false) => {
if (!this.options.stdout.isTTY)
return;
if (this.isPaused)
return;
if (supportsExtendedKeys()) {
this.options.stdout.write(DISABLE_KITTY_KEYBOARD + ENABLE_KITTY_KEYBOARD + ENABLE_MODIFY_OTHER_KEYS);
}
if (!this.altScreenActive)
return;
if (this.altScreenMouseTracking) {
this.options.stdout.write(ENABLE_MOUSE_TRACKING);
}
if (includeAltScreen) {
this.reenterAltScreen();
}
};
detachForShutdown() {
this.isUnmounted = true;
this.scheduleRender.cancel?.();
const stdin = this.options.stdin;
this.drainStdin();
if (stdin.isTTY && stdin.isRaw && stdin.setRawMode) {
stdin.setRawMode(false);
}
}
drainStdin() {
drainStdin(this.options.stdin);
}
reenterAltScreen() {
this.options.stdout.write(ENTER_ALT_SCREEN + ERASE_SCREEN + CURSOR_HOME + (this.altScreenMouseTracking ? ENABLE_MOUSE_TRACKING : ""));
this.resetFramesForAltScreen();
}
resetFramesForAltScreen() {
const rows = this.terminalRows;
const cols = this.terminalColumns;
const blank = () => ({
screen: createScreen(cols, rows, this.stylePool, this.charPool, this.hyperlinkPool),
viewport: {
width: cols,
height: rows + 1
},
cursor: {
x: 0,
y: 0,
visible: true
}
});
this.frontFrame = blank();
this.backFrame = blank();
this.log.reset();
this.displayCursor = null;
this.prevFrameContaminated = true;
}
copySelectionNoClear() {
if (!hasSelection(this.selection))
return "";
const text = getSelectedText(this.selection, this.frontFrame.screen);
if (text) {
setClipboard(text).then((raw) => {
if (raw)
this.options.stdout.write(raw);
});
}
return text;
}
copySelection() {
if (!hasSelection(this.selection))
return "";
const text = this.copySelectionNoClear();
clearSelection(this.selection);
this.notifySelectionChange();
return text;
}
clearTextSelection() {
if (!hasSelection(this.selection))
return;
clearSelection(this.selection);
this.notifySelectionChange();
}
setSearchHighlight(query) {
if (this.searchHighlightQuery === query)
return;
this.searchHighlightQuery = query;
this.scheduleRender();
}
scanElementSubtree(el) {
if (!this.searchHighlightQuery || !el.yogaNode)
return [];
const width = Math.ceil(el.yogaNode.getComputedWidth());
const height = Math.ceil(el.yogaNode.getComputedHeight());
if (width <= 0 || height <= 0)
return [];
const elLeft = el.yogaNode.getComputedLeft();
const elTop = el.yogaNode.getComputedTop();
const screen = createScreen(width, height, this.stylePool, this.charPool, this.hyperlinkPool);
const output = new Output({
width,
height,
stylePool: this.stylePool,
screen
});
render_node_to_output_default(el, output, {
offsetX: -elLeft,
offsetY: -elTop,
prevScreen: undefined
});
const rendered = output.get();
markDirty(el);
const positions = scanPositions(rendered, this.searchHighlightQuery);
logForDebugging(`scanElementSubtree: q='${this.searchHighlightQuery}' ` + `el=${width}x${height}@(${elLeft},${elTop}) n=${positions.length} ` + `[${positions.slice(0, 10).map((p) => `${p.row}:${p.col}`).join(",")}` + `${positions.length > 10 ? ",…" : ""}]`);
return positions;
}
setSearchPositions(state) {
this.searchPositions = state;
this.scheduleRender();
}
setSelectionBgColor(color) {
const wrapped = colorize("\x00", color, "background");
const nul = wrapped.indexOf("\x00");
if (nul <= 0 || nul === wrapped.length - 1) {
this.stylePool.setSelectionBg(null);
return;
}
this.stylePool.setSelectionBg({
type: "ansi",
code: wrapped.slice(0, nul),
endCode: wrapped.slice(nul + 1)
});
}
captureScrolledRows(firstRow, lastRow, side) {
captureScrolledRows(this.selection, this.frontFrame.screen, firstRow, lastRow, side);
}
shiftSelectionForScroll(dRow, minRow, maxRow) {
const hadSel = hasSelection(this.selection);
shiftSelection(this.selection, dRow, minRow, maxRow, this.frontFrame.screen.width);
if (hadSel && !hasSelection(this.selection)) {
this.notifySelectionChange();
}
}
moveSelectionFocus(move) {
if (!this.altScreenActive)
return;
const {
focus
} = this.selection;
if (!focus)
return;
const {
width,
height
} = this.frontFrame.screen;
const maxCol = width - 1;
const maxRow = height - 1;
let {
col,
row
} = focus;
switch (move) {
case "left":
if (col > 0)
col--;
else if (row > 0) {
col = maxCol;
row--;
}
break;
case "right":
if (col < maxCol)
col++;
else if (row < maxRow) {
col = 0;
row++;
}
break;
case "up":
if (row > 0)
row--;
break;
case "down":
if (row < maxRow)
row++;
break;
case "lineStart":
col = 0;
break;
case "lineEnd":
col = maxCol;
break;
}
if (col === focus.col && row === focus.row)
return;
moveFocus(this.selection, col, row);
this.notifySelectionChange();
}
hasTextSelection() {
return hasSelection(this.selection);
}
subscribeToSelectionChange(cb) {
this.selectionListeners.add(cb);
return () => this.selectionListeners.delete(cb);
}
notifySelectionChange() {
this.onRender();
for (const cb of this.selectionListeners)
cb();
}
dispatchClick(col, row) {
if (!this.altScreenActive)
return false;
const blank = isEmptyCellAt(this.frontFrame.screen, col, row);
return dispatchClick(this.rootNode, col, row, blank);
}
dispatchHover(col, row) {
if (!this.altScreenActive)
return;
dispatchHover(this.rootNode, col, row, this.hoveredNodes);
}
dispatchKeyboardEvent(parsedKey) {
const target = this.focusManager.activeElement ?? this.rootNode;
const event = new KeyboardEvent(parsedKey);
dispatcher.dispatchDiscrete(target, event);
if (!event.defaultPrevented && parsedKey.name === "tab" && !parsedKey.ctrl && !parsedKey.meta) {
if (parsedKey.shift) {
this.focusManager.focusPrevious(this.rootNode);
} else {
this.focusManager.focusNext(this.rootNode);
}
}
}
getHyperlinkAt(col, row) {
if (!this.altScreenActive)
return;
const screen = this.frontFrame.screen;
const cell = cellAt(screen, col, row);
let url3 = cell?.hyperlink;
if (!url3 && cell?.width === 2 /* SpacerTail */ && col > 0) {
url3 = cellAt(screen, col - 1, row)?.hyperlink;
}
return url3 ?? findPlainTextUrlAt(screen, col, row);
}
onHyperlinkClick;
openHyperlink(url3) {
this.onHyperlinkClick?.(url3);
}
handleMultiClick(col, row, count3) {
if (!this.altScreenActive)
return;
const screen = this.frontFrame.screen;
startSelection(this.selection, col, row);
if (count3 === 2)
selectWordAt(this.selection, screen, col, row);
else
selectLineAt(this.selection, screen, row);
if (!this.selection.focus)
this.selection.focus = this.selection.anchor;
this.notifySelectionChange();
}
handleSelectionDrag(col, row) {
if (!this.altScreenActive)
return;
const sel = this.selection;
if (sel.anchorSpan) {
extendSelection(sel, this.frontFrame.screen, col, row);
} else {
updateSelection(sel, col, row);
}
this.notifySelectionChange();
}
stdinListeners = [];
wasRawMode = false;
suspendStdin() {
const stdin = this.options.stdin;
if (!stdin.isTTY) {
return;
}
const readableListeners = stdin.listeners("readable");
logForDebugging(`[stdin] suspendStdin: removing ${readableListeners.length} readable listener(s), wasRawMode=${stdin.isRaw ?? false}`);
readableListeners.forEach((listener) => {
this.stdinListeners.push({
event: "readable",
listener
});
stdin.removeListener("readable", listener);
});
const stdinWithRaw = stdin;
if (stdinWithRaw.isRaw && stdinWithRaw.setRawMode) {
stdinWithRaw.setRawMode(false);
this.wasRawMode = true;
}
}
resumeStdin() {
const stdin = this.options.stdin;
if (!stdin.isTTY) {
return;
}
if (this.stdinListeners.length === 0 && !this.wasRawMode) {
logForDebugging("[stdin] resumeStdin: called with no stored listeners and wasRawMode=false (possible desync)", {
level: "warn"
});
}
logForDebugging(`[stdin] resumeStdin: re-attaching ${this.stdinListeners.length} listener(s), wasRawMode=${this.wasRawMode}`);
this.stdinListeners.forEach(({
event,
listener
}) => {
stdin.addListener(event, listener);
});
this.stdinListeners = [];
if (this.wasRawMode) {
const stdinWithRaw = stdin;
if (stdinWithRaw.setRawMode) {
stdinWithRaw.setRawMode(true);
}
this.wasRawMode = false;
}
}
writeRaw(data) {
this.options.stdout.write(data);
}
setCursorDeclaration = (decl, clearIfNode) => {
if (decl === null && clearIfNode !== undefined && this.cursorDeclaration?.node !== clearIfNode) {
return;
}
this.cursorDeclaration = decl;
};
render(node) {
this.currentNode = node;
const tree = /* @__PURE__ */ jsx_dev_runtime8.jsxDEV(App, {
stdin: this.options.stdin,
stdout: this.options.stdout,
stderr: this.options.stderr,
exitOnCtrlC: this.options.exitOnCtrlC,
onExit: this.unmount,
terminalColumns: this.terminalColumns,
terminalRows: this.terminalRows,
selection: this.selection,
onSelectionChange: this.notifySelectionChange,
onClickAt: this.dispatchClick,
onHoverAt: this.dispatchHover,
getHyperlinkAt: this.getHyperlinkAt,
onOpenHyperlink: this.openHyperlink,
onMultiClick: this.handleMultiClick,
onSelectionDrag: this.handleSelectionDrag,
onStdinResume: this.reassertTerminalModes,
onCursorDeclaration: this.setCursorDeclaration,
dispatchKeyboardEvent: this.dispatchKeyboardEvent,
children: /* @__PURE__ */ jsx_dev_runtime8.jsxDEV(TerminalWriteProvider, {
value: this.writeRaw,
children: node
}, undefined, false, undefined, this)
}, undefined, false, undefined, this);
reconciler_default.updateContainerSync(tree, this.container, null, noop_default);
reconciler_default.flushSyncWork();
}
unmount(error44) {
if (this.isUnmounted) {
return;
}
this.onRender();
this.unsubscribeExit();
if (typeof this.restoreConsole === "function") {
this.restoreConsole();
}
this.restoreStderr?.();
this.unsubscribeTTYHandlers?.();
const diff2 = this.log.renderPreviousOutput_DEPRECATED(this.frontFrame);
writeDiffToTerminal(this.terminal, optimize(diff2));
if (this.options.stdout.isTTY) {
if (this.altScreenActive) {
writeSync(1, EXIT_ALT_SCREEN);
}
writeSync(1, DISABLE_MOUSE_TRACKING);
this.drainStdin();
writeSync(1, DISABLE_MODIFY_OTHER_KEYS);
writeSync(1, DISABLE_KITTY_KEYBOARD);
writeSync(1, DFE);
writeSync(1, DBP);
writeSync(1, SHOW_CURSOR);
writeSync(1, CLEAR_ITERM2_PROGRESS);
if (supportsTabStatus())
writeSync(1, wrapForMultiplexer(CLEAR_TAB_STATUS));
}
this.isUnmounted = true;
this.scheduleRender.cancel?.();
if (this.drainTimer !== null) {
clearTimeout(this.drainTimer);
this.drainTimer = null;
}
reconciler_default.updateContainerSync(null, this.container, null, noop_default);
reconciler_default.flushSyncWork();
instances_default.delete(this.options.stdout);
this.rootNode.yogaNode?.free();
this.rootNode.yogaNode = undefined;
if (error44 instanceof Error) {
this.rejectExitPromise(error44);
} else {
this.resolveExitPromise();
}
}
async waitUntilExit() {
this.exitPromise ||= new Promise((resolve9, reject) => {
this.resolveExitPromise = resolve9;
this.rejectExitPromise = reject;
});
return this.exitPromise;
}
resetLineCount() {
if (this.options.stdout.isTTY) {
this.backFrame = this.frontFrame;
this.frontFrame = emptyFrame(this.frontFrame.viewport.height, this.frontFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
this.log.reset();
this.displayCursor = null;
}
}
resetPools() {
this.charPool = new CharPool;
this.hyperlinkPool = new HyperlinkPool;
migrateScreenPools(this.frontFrame.screen, this.charPool, this.hyperlinkPool);
this.backFrame.screen.charPool = this.charPool;
this.backFrame.screen.hyperlinkPool = this.hyperlinkPool;
}
patchConsole() {
const con = console;
const originals = {};
const toDebug = (...args) => logForDebugging(`console.log: ${format3(...args)}`);
const toError2 = (...args) => logError2(new Error(`console.error: ${format3(...args)}`));
for (const m of CONSOLE_STDOUT_METHODS) {
originals[m] = con[m];
con[m] = toDebug;
}
for (const m of CONSOLE_STDERR_METHODS) {
originals[m] = con[m];
con[m] = toError2;
}
originals.assert = con.assert;
con.assert = (condition, ...args) => {
if (!condition)
toError2(...args);
};
return () => Object.assign(con, originals);
}
patchStderr() {
const stderr = process.stderr;
const originalWrite = stderr.write;
let reentered = false;
const intercept = (chunk, encodingOrCb, cb) => {
const callback = typeof encodingOrCb === "function" ? encodingOrCb : cb;
if (reentered) {
const encoding = typeof encodingOrCb === "string" ? encodingOrCb : undefined;
return originalWrite.call(stderr, chunk, encoding, callback);
}
reentered = true;
try {
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
logForDebugging(`[stderr] ${text}`, {
level: "warn"
});
if (this.altScreenActive && !this.isUnmounted && !this.isPaused) {
this.prevFrameContaminated = true;
this.scheduleRender();
}
} finally {
reentered = false;
callback?.();
}
return true;
};
stderr.write = intercept;
return () => {
if (stderr.write === intercept) {
stderr.write = originalWrite;
}
};
}
}
function drainStdin(stdin = process.stdin) {
if (!stdin.isTTY)
return;
try {
while (stdin.read() !== null) {}
} catch {}
if (process.platform === "win32")
return;
const tty4 = stdin;
const wasRaw = tty4.isRaw === true;
let fd = -1;
try {
if (!wasRaw)
tty4.setRawMode?.(true);
fd = openSync3("/dev/tty", fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
const buf = Buffer.alloc(1024);
for (let i2 = 0;i2 < 64; i2++) {
if (readSync2(fd, buf, 0, buf.length, null) <= 0)
break;
}
} catch {} finally {
if (fd >= 0) {
try {
closeSync3(fd);
} catch {}
}
if (!wasRaw) {
try {
tty4.setRawMode?.(false);
} catch {}
}
}
}
var import_constants16, jsx_dev_runtime8, ALT_SCREEN_ANCHOR_CURSOR, CURSOR_HOME_PATCH, ERASE_THEN_HOME_PATCH, CONSOLE_STDOUT_METHODS, CONSOLE_STDERR_METHODS;
var init_ink = __esm(() => {
init_noop();
init_throttle2();
init_mjs();
init_state();
init_yoga_layout();
init_debug();
init_log3();
init_colorize();
init_App();
init_dom();
init_keyboard_event();
init_focus();
init_frame();
init_hit_test();
init_instances();
init_log_update();
init_node_cache();
init_output2();
init_reconciler();
init_render_node_to_output();
init_render_to_screen();
init_renderer();
init_screen();
init_searchHighlight();
init_selection();
init_terminal();
init_csi();
init_dec();
init_osc();
init_useTerminalNotification();
import_constants16 = __toESM(require_constants7(), 1);
jsx_dev_runtime8 = __toESM(require_jsx_dev_runtime(), 1);
ALT_SCREEN_ANCHOR_CURSOR = Object.freeze({
x: 0,
y: 0,
visible: false
});
CURSOR_HOME_PATCH = Object.freeze({
type: "stdout",
content: CURSOR_HOME
});
ERASE_THEN_HOME_PATCH = Object.freeze({
type: "stdout",
content: ERASE_SCREEN + CURSOR_HOME
});
CONSOLE_STDOUT_METHODS = ["log", "info", "debug", "dir", "dirxml", "count", "countReset", "group", "groupCollapsed", "groupEnd", "table", "time", "timeEnd", "timeLog"];
CONSOLE_STDERR_METHODS = ["warn", "error", "trace"];
});
// src/ink/root.ts
import { Stream as Stream3 } from "stream";
async function createRoot({
stdout = process.stdout,
stdin = process.stdin,
stderr = process.stderr,
exitOnCtrlC = true,
patchConsole = true,
onFrame
} = {}) {
await Promise.resolve();
const instance = new Ink({
stdout,
stdin,
stderr,
exitOnCtrlC,
patchConsole,
onFrame
});
instances_default.set(stdout, instance);
return {
render: (node) => instance.render(node),
unmount: () => instance.unmount(),
waitUntilExit: () => instance.waitUntilExit()
};
}
var renderSync = (node, options) => {
const opts = getOptions(options);
const inkOptions = {
stdout: process.stdout,
stdin: process.stdin,
stderr: process.stderr,
exitOnCtrlC: true,
patchConsole: true,
...opts
};
const instance = getInstance(inkOptions.stdout, () => new Ink(inkOptions));
instance.render(node);
return {
rerender: instance.render,
unmount() {
instance.unmount();
},
waitUntilExit: instance.waitUntilExit,
cleanup: () => instances_default.delete(inkOptions.stdout)
};
}, wrappedRender = async (node, options) => {
await Promise.resolve();
const instance = renderSync(node, options);
logForDebugging(`[render] first ink render: ${Math.round(process.uptime() * 1000)}ms since process start`);
return instance;
}, root_default, getOptions = (stdout = {}) => {
if (stdout instanceof Stream3) {
return {
stdout,
stdin: process.stdin
};
}
return stdout;
}, getInstance = (stdout, createInstance2) => {
let instance = instances_default.get(stdout);
if (!instance) {
instance = createInstance2();
instances_default.set(stdout, instance);
}
return instance;
};
var init_root = __esm(() => {
init_debug();
init_ink();
init_instances();
root_default = wrappedRender;
});
// src/utils/theme.ts
function getTheme(themeName) {
switch (themeName) {
case "light":
return lightTheme;
case "light-ansi":
return lightAnsiTheme;
case "dark-ansi":
return darkAnsiTheme;
case "light-daltonized":
return lightDaltonizedTheme;
case "dark-daltonized":
return darkDaltonizedTheme;
default:
return darkTheme;
}
}
function themeColorToAnsi(themeColor) {
const rgbMatch = themeColor.match(/rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)/);
if (rgbMatch) {
const r = parseInt(rgbMatch[1], 10);
const g = parseInt(rgbMatch[2], 10);
const b = parseInt(rgbMatch[3], 10);
const colored = chalkForChart.rgb(r, g, b)("X");
return colored.slice(0, colored.indexOf("X"));
}
return "\x1B[35m";
}
var THEME_NAMES, THEME_SETTINGS, lightTheme, lightAnsiTheme, darkAnsiTheme, lightDaltonizedTheme, darkTheme, darkDaltonizedTheme, chalkForChart;
var init_theme = __esm(() => {
init_source();
init_env();
THEME_NAMES = [
"dark",
"light",
"light-daltonized",
"dark-daltonized",
"light-ansi",
"dark-ansi"
];
THEME_SETTINGS = ["auto", ...THEME_NAMES];
lightTheme = {
autoAccept: "rgb(135,0,255)",
bashBorder: "rgb(255,0,135)",
claude: "rgb(59,130,246)",
claudeShimmer: "rgb(96,165,250)",
claudeBlue_FOR_SYSTEM_SPINNER: "rgb(87,105,247)",
claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(117,135,255)",
permission: "rgb(87,105,247)",
permissionShimmer: "rgb(137,155,255)",
planMode: "rgb(0,102,102)",
ide: "rgb(71,130,200)",
promptBorder: "rgb(153,153,153)",
promptBorderShimmer: "rgb(183,183,183)",
text: "rgb(0,0,0)",
inverseText: "rgb(255,255,255)",
inactive: "rgb(102,102,102)",
inactiveShimmer: "rgb(142,142,142)",
subtle: "rgb(175,175,175)",
suggestion: "rgb(87,105,247)",
remember: "rgb(0,0,255)",
background: "rgb(0,153,153)",
success: "rgb(44,122,57)",
error: "rgb(171,43,63)",
warning: "rgb(150,108,30)",
merged: "rgb(135,0,255)",
warningShimmer: "rgb(200,158,80)",
diffAdded: "rgb(105,219,124)",
diffRemoved: "rgb(255,168,180)",
diffAddedDimmed: "rgb(199,225,203)",
diffRemovedDimmed: "rgb(253,210,216)",
diffAddedWord: "rgb(47,157,68)",
diffRemovedWord: "rgb(209,69,75)",
red_FOR_SUBAGENTS_ONLY: "rgb(220,38,38)",
blue_FOR_SUBAGENTS_ONLY: "rgb(37,99,235)",
green_FOR_SUBAGENTS_ONLY: "rgb(22,163,74)",
yellow_FOR_SUBAGENTS_ONLY: "rgb(202,138,4)",
purple_FOR_SUBAGENTS_ONLY: "rgb(147,51,234)",
orange_FOR_SUBAGENTS_ONLY: "rgb(234,88,12)",
pink_FOR_SUBAGENTS_ONLY: "rgb(219,39,119)",
cyan_FOR_SUBAGENTS_ONLY: "rgb(8,145,178)",
professionalBlue: "rgb(106,155,204)",
chromeYellow: "rgb(251,188,4)",
clawd_body: "rgb(59,130,246)",
clawd_background: "rgb(0,0,0)",
userMessageBackground: "rgb(240, 240, 240)",
userMessageBackgroundHover: "rgb(252, 252, 252)",
messageActionsBackground: "rgb(232, 236, 244)",
selectionBg: "rgb(180, 213, 255)",
bashMessageBackgroundColor: "rgb(250, 245, 250)",
memoryBackgroundColor: "rgb(230, 245, 250)",
rate_limit_fill: "rgb(87,105,247)",
rate_limit_empty: "rgb(39,47,111)",
fastMode: "rgb(37,99,235)",
fastModeShimmer: "rgb(96,165,250)",
briefLabelYou: "rgb(37,99,235)",
briefLabelClaude: "rgb(59,130,246)",
rainbow_red: "rgb(235,95,87)",
rainbow_orange: "rgb(245,139,87)",
rainbow_yellow: "rgb(250,195,95)",
rainbow_green: "rgb(145,200,130)",
rainbow_blue: "rgb(130,170,220)",
rainbow_indigo: "rgb(155,130,200)",
rainbow_violet: "rgb(200,130,180)",
rainbow_red_shimmer: "rgb(250,155,147)",
rainbow_orange_shimmer: "rgb(255,185,137)",
rainbow_yellow_shimmer: "rgb(255,225,155)",
rainbow_green_shimmer: "rgb(185,230,180)",
rainbow_blue_shimmer: "rgb(180,205,240)",
rainbow_indigo_shimmer: "rgb(195,180,230)",
rainbow_violet_shimmer: "rgb(230,180,210)"
};
lightAnsiTheme = {
autoAccept: "ansi:magenta",
bashBorder: "ansi:magenta",
claude: "ansi:blueBright",
claudeShimmer: "ansi:cyanBright",
claudeBlue_FOR_SYSTEM_SPINNER: "ansi:blue",
claudeBlueShimmer_FOR_SYSTEM_SPINNER: "ansi:blueBright",
permission: "ansi:blue",
permissionShimmer: "ansi:blueBright",
planMode: "ansi:cyan",
ide: "ansi:blueBright",
promptBorder: "ansi:white",
promptBorderShimmer: "ansi:whiteBright",
text: "ansi:black",
inverseText: "ansi:white",
inactive: "ansi:blackBright",
inactiveShimmer: "ansi:white",
subtle: "ansi:blackBright",
suggestion: "ansi:blue",
remember: "ansi:blue",
background: "ansi:cyan",
success: "ansi:green",
error: "ansi:red",
warning: "ansi:yellow",
merged: "ansi:magenta",
warningShimmer: "ansi:yellowBright",
diffAdded: "ansi:green",
diffRemoved: "ansi:red",
diffAddedDimmed: "ansi:green",
diffRemovedDimmed: "ansi:red",
diffAddedWord: "ansi:greenBright",
diffRemovedWord: "ansi:redBright",
red_FOR_SUBAGENTS_ONLY: "ansi:red",
blue_FOR_SUBAGENTS_ONLY: "ansi:blue",
green_FOR_SUBAGENTS_ONLY: "ansi:green",
yellow_FOR_SUBAGENTS_ONLY: "ansi:yellow",
purple_FOR_SUBAGENTS_ONLY: "ansi:magenta",
orange_FOR_SUBAGENTS_ONLY: "ansi:redBright",
pink_FOR_SUBAGENTS_ONLY: "ansi:magentaBright",
cyan_FOR_SUBAGENTS_ONLY: "ansi:cyan",
professionalBlue: "ansi:blueBright",
chromeYellow: "ansi:yellow",
clawd_body: "ansi:blueBright",
clawd_background: "ansi:black",
userMessageBackground: "ansi:white",
userMessageBackgroundHover: "ansi:whiteBright",
messageActionsBackground: "ansi:white",
selectionBg: "ansi:cyan",
bashMessageBackgroundColor: "ansi:whiteBright",
memoryBackgroundColor: "ansi:white",
rate_limit_fill: "ansi:yellow",
rate_limit_empty: "ansi:black",
fastMode: "ansi:blue",
fastModeShimmer: "ansi:blueBright",
briefLabelYou: "ansi:blue",
briefLabelClaude: "ansi:blueBright",
rainbow_red: "ansi:red",
rainbow_orange: "ansi:redBright",
rainbow_yellow: "ansi:yellow",
rainbow_green: "ansi:green",
rainbow_blue: "ansi:cyan",
rainbow_indigo: "ansi:blue",
rainbow_violet: "ansi:magenta",
rainbow_red_shimmer: "ansi:redBright",
rainbow_orange_shimmer: "ansi:yellow",
rainbow_yellow_shimmer: "ansi:yellowBright",
rainbow_green_shimmer: "ansi:greenBright",
rainbow_blue_shimmer: "ansi:cyanBright",
rainbow_indigo_shimmer: "ansi:blueBright",
rainbow_violet_shimmer: "ansi:magentaBright"
};
darkAnsiTheme = {
autoAccept: "ansi:magentaBright",
bashBorder: "ansi:magentaBright",
claude: "ansi:blueBright",
claudeShimmer: "ansi:cyanBright",
claudeBlue_FOR_SYSTEM_SPINNER: "ansi:blueBright",
claudeBlueShimmer_FOR_SYSTEM_SPINNER: "ansi:blueBright",
permission: "ansi:blueBright",
permissionShimmer: "ansi:blueBright",
planMode: "ansi:cyanBright",
ide: "ansi:blue",
promptBorder: "ansi:white",
promptBorderShimmer: "ansi:whiteBright",
text: "ansi:whiteBright",
inverseText: "ansi:black",
inactive: "ansi:white",
inactiveShimmer: "ansi:whiteBright",
subtle: "ansi:white",
suggestion: "ansi:blueBright",
remember: "ansi:blueBright",
background: "ansi:cyanBright",
success: "ansi:greenBright",
error: "ansi:redBright",
warning: "ansi:yellowBright",
merged: "ansi:magentaBright",
warningShimmer: "ansi:yellowBright",
diffAdded: "ansi:green",
diffRemoved: "ansi:red",
diffAddedDimmed: "ansi:green",
diffRemovedDimmed: "ansi:red",
diffAddedWord: "ansi:greenBright",
diffRemovedWord: "ansi:redBright",
red_FOR_SUBAGENTS_ONLY: "ansi:redBright",
blue_FOR_SUBAGENTS_ONLY: "ansi:blueBright",
green_FOR_SUBAGENTS_ONLY: "ansi:greenBright",
yellow_FOR_SUBAGENTS_ONLY: "ansi:yellowBright",
purple_FOR_SUBAGENTS_ONLY: "ansi:magentaBright",
orange_FOR_SUBAGENTS_ONLY: "ansi:redBright",
pink_FOR_SUBAGENTS_ONLY: "ansi:magentaBright",
cyan_FOR_SUBAGENTS_ONLY: "ansi:cyanBright",
professionalBlue: "rgb(106,155,204)",
chromeYellow: "ansi:yellowBright",
clawd_body: "ansi:blueBright",
clawd_background: "ansi:black",
userMessageBackground: "ansi:blackBright",
userMessageBackgroundHover: "ansi:white",
messageActionsBackground: "ansi:blackBright",
selectionBg: "ansi:blue",
bashMessageBackgroundColor: "ansi:black",
memoryBackgroundColor: "ansi:blackBright",
rate_limit_fill: "ansi:yellow",
rate_limit_empty: "ansi:white",
fastMode: "ansi:blueBright",
fastModeShimmer: "ansi:cyanBright",
briefLabelYou: "ansi:blueBright",
briefLabelClaude: "ansi:blueBright",
rainbow_red: "ansi:red",
rainbow_orange: "ansi:redBright",
rainbow_yellow: "ansi:yellow",
rainbow_green: "ansi:green",
rainbow_blue: "ansi:cyan",
rainbow_indigo: "ansi:blue",
rainbow_violet: "ansi:magenta",
rainbow_red_shimmer: "ansi:redBright",
rainbow_orange_shimmer: "ansi:yellow",
rainbow_yellow_shimmer: "ansi:yellowBright",
rainbow_green_shimmer: "ansi:greenBright",
rainbow_blue_shimmer: "ansi:cyanBright",
rainbow_indigo_shimmer: "ansi:blueBright",
rainbow_violet_shimmer: "ansi:magentaBright"
};
lightDaltonizedTheme = {
autoAccept: "rgb(135,0,255)",
bashBorder: "rgb(0,102,204)",
claude: "rgb(51,102,255)",
claudeShimmer: "rgb(101,152,255)",
claudeBlue_FOR_SYSTEM_SPINNER: "rgb(51,102,255)",
claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(101,152,255)",
permission: "rgb(51,102,255)",
permissionShimmer: "rgb(101,152,255)",
planMode: "rgb(51,102,102)",
ide: "rgb(71,130,200)",
promptBorder: "rgb(153,153,153)",
promptBorderShimmer: "rgb(183,183,183)",
text: "rgb(0,0,0)",
inverseText: "rgb(255,255,255)",
inactive: "rgb(102,102,102)",
inactiveShimmer: "rgb(142,142,142)",
subtle: "rgb(175,175,175)",
suggestion: "rgb(51,102,255)",
remember: "rgb(51,102,255)",
background: "rgb(0,153,153)",
success: "rgb(0,102,153)",
error: "rgb(204,0,0)",
warning: "rgb(255,153,0)",
merged: "rgb(135,0,255)",
warningShimmer: "rgb(255,183,50)",
diffAdded: "rgb(153,204,255)",
diffRemoved: "rgb(255,204,204)",
diffAddedDimmed: "rgb(209,231,253)",
diffRemovedDimmed: "rgb(255,233,233)",
diffAddedWord: "rgb(51,102,204)",
diffRemovedWord: "rgb(153,51,51)",
red_FOR_SUBAGENTS_ONLY: "rgb(204,0,0)",
blue_FOR_SUBAGENTS_ONLY: "rgb(0,102,204)",
green_FOR_SUBAGENTS_ONLY: "rgb(0,204,0)",
yellow_FOR_SUBAGENTS_ONLY: "rgb(255,204,0)",
purple_FOR_SUBAGENTS_ONLY: "rgb(128,0,128)",
orange_FOR_SUBAGENTS_ONLY: "rgb(255,128,0)",
pink_FOR_SUBAGENTS_ONLY: "rgb(255,102,178)",
cyan_FOR_SUBAGENTS_ONLY: "rgb(0,178,178)",
professionalBlue: "rgb(106,155,204)",
chromeYellow: "rgb(251,188,4)",
clawd_body: "rgb(51,102,255)",
clawd_background: "rgb(0,0,0)",
userMessageBackground: "rgb(220, 220, 220)",
userMessageBackgroundHover: "rgb(232, 232, 232)",
messageActionsBackground: "rgb(210, 216, 226)",
selectionBg: "rgb(180, 213, 255)",
bashMessageBackgroundColor: "rgb(250, 245, 250)",
memoryBackgroundColor: "rgb(230, 245, 250)",
rate_limit_fill: "rgb(51,102,255)",
rate_limit_empty: "rgb(23,46,114)",
fastMode: "rgb(0,102,204)",
fastModeShimmer: "rgb(101,152,255)",
briefLabelYou: "rgb(37,99,235)",
briefLabelClaude: "rgb(51,102,255)",
rainbow_red: "rgb(235,95,87)",
rainbow_orange: "rgb(245,139,87)",
rainbow_yellow: "rgb(250,195,95)",
rainbow_green: "rgb(145,200,130)",
rainbow_blue: "rgb(130,170,220)",
rainbow_indigo: "rgb(155,130,200)",
rainbow_violet: "rgb(200,130,180)",
rainbow_red_shimmer: "rgb(250,155,147)",
rainbow_orange_shimmer: "rgb(255,185,137)",
rainbow_yellow_shimmer: "rgb(255,225,155)",
rainbow_green_shimmer: "rgb(185,230,180)",
rainbow_blue_shimmer: "rgb(180,205,240)",
rainbow_indigo_shimmer: "rgb(195,180,230)",
rainbow_violet_shimmer: "rgb(230,180,210)"
};
darkTheme = {
autoAccept: "rgb(175,135,255)",
bashBorder: "rgb(253,93,177)",
claude: "rgb(96,165,250)",
claudeShimmer: "rgb(147,197,253)",
claudeBlue_FOR_SYSTEM_SPINNER: "rgb(147,165,255)",
claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(177,195,255)",
permission: "rgb(177,185,249)",
permissionShimmer: "rgb(207,215,255)",
planMode: "rgb(72,150,140)",
ide: "rgb(71,130,200)",
promptBorder: "rgb(136,136,136)",
promptBorderShimmer: "rgb(166,166,166)",
text: "rgb(255,255,255)",
inverseText: "rgb(0,0,0)",
inactive: "rgb(153,153,153)",
inactiveShimmer: "rgb(193,193,193)",
subtle: "rgb(80,80,80)",
suggestion: "rgb(177,185,249)",
remember: "rgb(177,185,249)",
background: "rgb(0,204,204)",
success: "rgb(78,186,101)",
error: "rgb(255,107,128)",
warning: "rgb(255,193,7)",
merged: "rgb(175,135,255)",
warningShimmer: "rgb(255,223,57)",
diffAdded: "rgb(34,92,43)",
diffRemoved: "rgb(122,41,54)",
diffAddedDimmed: "rgb(71,88,74)",
diffRemovedDimmed: "rgb(105,72,77)",
diffAddedWord: "rgb(56,166,96)",
diffRemovedWord: "rgb(179,89,107)",
red_FOR_SUBAGENTS_ONLY: "rgb(220,38,38)",
blue_FOR_SUBAGENTS_ONLY: "rgb(37,99,235)",
green_FOR_SUBAGENTS_ONLY: "rgb(22,163,74)",
yellow_FOR_SUBAGENTS_ONLY: "rgb(202,138,4)",
purple_FOR_SUBAGENTS_ONLY: "rgb(147,51,234)",
orange_FOR_SUBAGENTS_ONLY: "rgb(234,88,12)",
pink_FOR_SUBAGENTS_ONLY: "rgb(219,39,119)",
cyan_FOR_SUBAGENTS_ONLY: "rgb(8,145,178)",
professionalBlue: "rgb(106,155,204)",
chromeYellow: "rgb(251,188,4)",
clawd_body: "rgb(96,165,250)",
clawd_background: "rgb(0,0,0)",
userMessageBackground: "rgb(55, 55, 55)",
userMessageBackgroundHover: "rgb(70, 70, 70)",
messageActionsBackground: "rgb(44, 50, 62)",
selectionBg: "rgb(38, 79, 120)",
bashMessageBackgroundColor: "rgb(65, 60, 65)",
memoryBackgroundColor: "rgb(55, 65, 70)",
rate_limit_fill: "rgb(177,185,249)",
rate_limit_empty: "rgb(80,83,112)",
fastMode: "rgb(59,130,246)",
fastModeShimmer: "rgb(96,165,250)",
briefLabelYou: "rgb(122,180,232)",
briefLabelClaude: "rgb(96,165,250)",
rainbow_red: "rgb(235,95,87)",
rainbow_orange: "rgb(245,139,87)",
rainbow_yellow: "rgb(250,195,95)",
rainbow_green: "rgb(145,200,130)",
rainbow_blue: "rgb(130,170,220)",
rainbow_indigo: "rgb(155,130,200)",
rainbow_violet: "rgb(200,130,180)",
rainbow_red_shimmer: "rgb(250,155,147)",
rainbow_orange_shimmer: "rgb(255,185,137)",
rainbow_yellow_shimmer: "rgb(255,225,155)",
rainbow_green_shimmer: "rgb(185,230,180)",
rainbow_blue_shimmer: "rgb(180,205,240)",
rainbow_indigo_shimmer: "rgb(195,180,230)",
rainbow_violet_shimmer: "rgb(230,180,210)"
};
darkDaltonizedTheme = {
autoAccept: "rgb(175,135,255)",
bashBorder: "rgb(51,153,255)",
claude: "rgb(153,204,255)",
claudeShimmer: "rgb(183,224,255)",
claudeBlue_FOR_SYSTEM_SPINNER: "rgb(153,204,255)",
claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(183,224,255)",
permission: "rgb(153,204,255)",
permissionShimmer: "rgb(183,224,255)",
planMode: "rgb(102,153,153)",
ide: "rgb(71,130,200)",
promptBorder: "rgb(136,136,136)",
promptBorderShimmer: "rgb(166,166,166)",
text: "rgb(255,255,255)",
inverseText: "rgb(0,0,0)",
inactive: "rgb(153,153,153)",
inactiveShimmer: "rgb(193,193,193)",
subtle: "rgb(80,80,80)",
suggestion: "rgb(153,204,255)",
remember: "rgb(153,204,255)",
background: "rgb(0,204,204)",
success: "rgb(51,153,255)",
error: "rgb(255,102,102)",
warning: "rgb(255,204,0)",
merged: "rgb(175,135,255)",
warningShimmer: "rgb(255,234,50)",
diffAdded: "rgb(0,68,102)",
diffRemoved: "rgb(102,0,0)",
diffAddedDimmed: "rgb(62,81,91)",
diffRemovedDimmed: "rgb(62,44,44)",
diffAddedWord: "rgb(0,119,179)",
diffRemovedWord: "rgb(179,0,0)",
red_FOR_SUBAGENTS_ONLY: "rgb(255,102,102)",
blue_FOR_SUBAGENTS_ONLY: "rgb(102,178,255)",
green_FOR_SUBAGENTS_ONLY: "rgb(102,255,102)",
yellow_FOR_SUBAGENTS_ONLY: "rgb(255,255,102)",
purple_FOR_SUBAGENTS_ONLY: "rgb(178,102,255)",
orange_FOR_SUBAGENTS_ONLY: "rgb(255,178,102)",
pink_FOR_SUBAGENTS_ONLY: "rgb(255,153,204)",
cyan_FOR_SUBAGENTS_ONLY: "rgb(102,204,204)",
professionalBlue: "rgb(106,155,204)",
chromeYellow: "rgb(251,188,4)",
clawd_body: "rgb(153,204,255)",
clawd_background: "rgb(0,0,0)",
userMessageBackground: "rgb(55, 55, 55)",
userMessageBackgroundHover: "rgb(70, 70, 70)",
messageActionsBackground: "rgb(44, 50, 62)",
selectionBg: "rgb(38, 79, 120)",
bashMessageBackgroundColor: "rgb(65, 60, 65)",
memoryBackgroundColor: "rgb(55, 65, 70)",
rate_limit_fill: "rgb(153,204,255)",
rate_limit_empty: "rgb(69,92,115)",
fastMode: "rgb(102,178,255)",
fastModeShimmer: "rgb(183,224,255)",
briefLabelYou: "rgb(122,180,232)",
briefLabelClaude: "rgb(153,204,255)",
rainbow_red: "rgb(235,95,87)",
rainbow_orange: "rgb(245,139,87)",
rainbow_yellow: "rgb(250,195,95)",
rainbow_green: "rgb(145,200,130)",
rainbow_blue: "rgb(130,170,220)",
rainbow_indigo: "rgb(155,130,200)",
rainbow_violet: "rgb(200,130,180)",
rainbow_red_shimmer: "rgb(250,155,147)",
rainbow_orange_shimmer: "rgb(255,185,137)",
rainbow_yellow_shimmer: "rgb(255,225,155)",
rainbow_green_shimmer: "rgb(185,230,180)",
rainbow_blue_shimmer: "rgb(180,205,240)",
rainbow_indigo_shimmer: "rgb(195,180,230)",
rainbow_violet_shimmer: "rgb(230,180,210)"
};
chalkForChart = env3.terminal === "Apple_Terminal" ? new Chalk({ level: 2 }) : source_default;
});
// src/components/design-system/color.ts
function color(c6, theme, type = "foreground") {
return (text) => {
if (!c6) {
return text;
}
if (c6.startsWith("rgb(") || c6.startsWith("#") || c6.startsWith("ansi256(") || c6.startsWith("ansi:")) {
return colorize(text, c6, type);
}
return colorize(text, getTheme(theme)[c6], type);
};
}
var init_color = __esm(() => {
init_colorize();
init_theme();
});
// src/components/design-system/ThemedBox.tsx
function resolveColor(color2, theme) {
if (!color2)
return;
if (color2.startsWith("rgb(") || color2.startsWith("#") || color2.startsWith("ansi256(") || color2.startsWith("ansi:")) {
return color2;
}
return theme[color2];
}
function ThemedBox(t0) {
const $2 = c5(33);
let backgroundColor;
let borderBottomColor;
let borderColor;
let borderLeftColor;
let borderRightColor;
let borderTopColor;
let children;
let ref;
let rest;
if ($2[0] !== t0) {
({
borderColor,
borderTopColor,
borderBottomColor,
borderLeftColor,
borderRightColor,
backgroundColor,
children,
ref,
...rest
} = t0);
$2[0] = t0;
$2[1] = backgroundColor;
$2[2] = borderBottomColor;
$2[3] = borderColor;
$2[4] = borderLeftColor;
$2[5] = borderRightColor;
$2[6] = borderTopColor;
$2[7] = children;
$2[8] = ref;
$2[9] = rest;
} else {
backgroundColor = $2[1];
borderBottomColor = $2[2];
borderColor = $2[3];
borderLeftColor = $2[4];
borderRightColor = $2[5];
borderTopColor = $2[6];
children = $2[7];
ref = $2[8];
rest = $2[9];
}
const [themeName] = useTheme();
let resolvedBorderBottomColor;
let resolvedBorderColor;
let resolvedBorderLeftColor;
let resolvedBorderRightColor;
let resolvedBorderTopColor;
let t1;
if ($2[10] !== backgroundColor || $2[11] !== borderBottomColor || $2[12] !== borderColor || $2[13] !== borderLeftColor || $2[14] !== borderRightColor || $2[15] !== borderTopColor || $2[16] !== themeName) {
const theme = getTheme(themeName);
resolvedBorderColor = resolveColor(borderColor, theme);
resolvedBorderTopColor = resolveColor(borderTopColor, theme);
resolvedBorderBottomColor = resolveColor(borderBottomColor, theme);
resolvedBorderLeftColor = resolveColor(borderLeftColor, theme);
resolvedBorderRightColor = resolveColor(borderRightColor, theme);
t1 = resolveColor(backgroundColor, theme);
$2[10] = backgroundColor;
$2[11] = borderBottomColor;
$2[12] = borderColor;
$2[13] = borderLeftColor;
$2[14] = borderRightColor;
$2[15] = borderTopColor;
$2[16] = themeName;
$2[17] = resolvedBorderBottomColor;
$2[18] = resolvedBorderColor;
$2[19] = resolvedBorderLeftColor;
$2[20] = resolvedBorderRightColor;
$2[21] = resolvedBorderTopColor;
$2[22] = t1;
} else {
resolvedBorderBottomColor = $2[17];
resolvedBorderColor = $2[18];
resolvedBorderLeftColor = $2[19];
resolvedBorderRightColor = $2[20];
resolvedBorderTopColor = $2[21];
t1 = $2[22];
}
const resolvedBackgroundColor = t1;
let t2;
if ($2[23] !== children || $2[24] !== ref || $2[25] !== resolvedBackgroundColor || $2[26] !== resolvedBorderBottomColor || $2[27] !== resolvedBorderColor || $2[28] !== resolvedBorderLeftColor || $2[29] !== resolvedBorderRightColor || $2[30] !== resolvedBorderTopColor || $2[31] !== rest) {
t2 = /* @__PURE__ */ jsx_dev_runtime9.jsxDEV(Box_default, {
ref,
borderColor: resolvedBorderColor,
borderTopColor: resolvedBorderTopColor,
borderBottomColor: resolvedBorderBottomColor,
borderLeftColor: resolvedBorderLeftColor,
borderRightColor: resolvedBorderRightColor,
backgroundColor: resolvedBackgroundColor,
...rest,
children
}, undefined, false, undefined, this);
$2[23] = children;
$2[24] = ref;
$2[25] = resolvedBackgroundColor;
$2[26] = resolvedBorderBottomColor;
$2[27] = resolvedBorderColor;
$2[28] = resolvedBorderLeftColor;
$2[29] = resolvedBorderRightColor;
$2[30] = resolvedBorderTopColor;
$2[31] = rest;
$2[32] = t2;
} else {
t2 = $2[32];
}
return t2;
}
var jsx_dev_runtime9, ThemedBox_default;
var init_ThemedBox = __esm(() => {
init_Box();
init_theme();
init_ThemeProvider();
jsx_dev_runtime9 = __toESM(require_jsx_dev_runtime(), 1);
ThemedBox_default = ThemedBox;
});
// src/components/design-system/ThemedText.tsx
function resolveColor2(color2, theme) {
if (!color2)
return;
if (color2.startsWith("rgb(") || color2.startsWith("#") || color2.startsWith("ansi256(") || color2.startsWith("ansi:")) {
return color2;
}
return theme[color2];
}
function ThemedText(t0) {
const $2 = c5(10);
const {
color: color2,
backgroundColor,
dimColor: t1,
bold: t2,
italic: t3,
underline: t4,
strikethrough: t5,
inverse: t6,
wrap: t7,
children
} = t0;
const dimColor = t1 === undefined ? false : t1;
const bold2 = t2 === undefined ? false : t2;
const italic2 = t3 === undefined ? false : t3;
const underline2 = t4 === undefined ? false : t4;
const strikethrough2 = t5 === undefined ? false : t5;
const inverse2 = t6 === undefined ? false : t6;
const wrap = t7 === undefined ? "wrap" : t7;
const [themeName] = useTheme();
const theme = getTheme(themeName);
const hoverColor = import_react12.useContext(TextHoverColorContext);
const resolvedColor = !color2 && hoverColor ? resolveColor2(hoverColor, theme) : dimColor ? theme.inactive : resolveColor2(color2, theme);
const resolvedBackgroundColor = backgroundColor ? theme[backgroundColor] : undefined;
let t8;
if ($2[0] !== bold2 || $2[1] !== children || $2[2] !== inverse2 || $2[3] !== italic2 || $2[4] !== resolvedBackgroundColor || $2[5] !== resolvedColor || $2[6] !== strikethrough2 || $2[7] !== underline2 || $2[8] !== wrap) {
t8 = /* @__PURE__ */ jsx_dev_runtime10.jsxDEV(Text, {
color: resolvedColor,
backgroundColor: resolvedBackgroundColor,
bold: bold2,
italic: italic2,
underline: underline2,
strikethrough: strikethrough2,
inverse: inverse2,
wrap,
children
}, undefined, false, undefined, this);
$2[0] = bold2;
$2[1] = children;
$2[2] = inverse2;
$2[3] = italic2;
$2[4] = resolvedBackgroundColor;
$2[5] = resolvedColor;
$2[6] = strikethrough2;
$2[7] = underline2;
$2[8] = wrap;
$2[9] = t8;
} else {
t8 = $2[9];
}
return t8;
}
var import_react12, jsx_dev_runtime10, TextHoverColorContext;
var init_ThemedText = __esm(() => {
init_Text();
init_theme();
init_ThemeProvider();
import_react12 = __toESM(require_react(), 1);
jsx_dev_runtime10 = __toESM(require_jsx_dev_runtime(), 1);
TextHoverColorContext = import_react12.default.createContext(undefined);
});
// node_modules/supports-hyperlinks/index.js
var require_supports_hyperlinks = __commonJS((exports, module) => {
var supportsColor2 = require_supports_color();
var hasFlag2 = require_has_flag();
function parseVersion(versionString) {
if (/^\d{3,4}$/.test(versionString)) {
const m = /(\d{1,2})(\d{2})/.exec(versionString) || [];
return {
major: 0,
minor: parseInt(m[1], 10),
patch: parseInt(m[2], 10)
};
}
const versions2 = (versionString || "").split(".").map((n2) => parseInt(n2, 10));
return {
major: versions2[0],
minor: versions2[1],
patch: versions2[2]
};
}
function supportsHyperlink(stream4) {
const {
CI,
FORCE_HYPERLINK,
NETLIFY,
TEAMCITY_VERSION,
TERM_PROGRAM,
TERM_PROGRAM_VERSION,
VTE_VERSION,
TERM
} = process.env;
if (FORCE_HYPERLINK) {
return !(FORCE_HYPERLINK.length > 0 && parseInt(FORCE_HYPERLINK, 10) === 0);
}
if (hasFlag2("no-hyperlink") || hasFlag2("no-hyperlinks") || hasFlag2("hyperlink=false") || hasFlag2("hyperlink=never")) {
return false;
}
if (hasFlag2("hyperlink=true") || hasFlag2("hyperlink=always")) {
return true;
}
if (NETLIFY) {
return true;
}
if (!supportsColor2.supportsColor(stream4)) {
return false;
}
if (stream4 && !stream4.isTTY) {
return false;
}
if ("WT_SESSION" in process.env) {
return true;
}
if (process.platform === "win32") {
return false;
}
if (CI) {
return false;
}
if (TEAMCITY_VERSION) {
return false;
}
if (TERM_PROGRAM) {
const version2 = parseVersion(TERM_PROGRAM_VERSION || "");
switch (TERM_PROGRAM) {
case "iTerm.app":
if (version2.major === 3) {
return version2.minor >= 1;
}
return version2.major > 3;
case "WezTerm":
return version2.major >= 20200620;
case "vscode":
return version2.major > 1 || version2.major === 1 && version2.minor >= 72;
case "ghostty":
return true;
}
}
if (VTE_VERSION) {
if (VTE_VERSION === "0.50.0") {
return false;
}
const version2 = parseVersion(VTE_VERSION);
return version2.major > 0 || version2.minor >= 50;
}
switch (TERM) {
case "alacritty":
return true;
}
return false;
}
module.exports = {
supportsHyperlink,
stdout: supportsHyperlink(process.stdout),
stderr: supportsHyperlink(process.stderr)
};
});
// src/ink/supports-hyperlinks.ts
function supportsHyperlinks(options) {
const stdoutSupported = options?.stdoutSupported ?? import_supports_hyperlinks.default.stdout;
if (stdoutSupported) {
return true;
}
const env5 = options?.env ?? process.env;
const termProgram = env5["TERM_PROGRAM"];
if (termProgram && ADDITIONAL_HYPERLINK_TERMINALS.includes(termProgram)) {
return true;
}
const lcTerminal = env5["LC_TERMINAL"];
if (lcTerminal && ADDITIONAL_HYPERLINK_TERMINALS.includes(lcTerminal)) {
return true;
}
const term = env5["TERM"];
if (term?.includes("kitty")) {
return true;
}
return false;
}
var import_supports_hyperlinks, ADDITIONAL_HYPERLINK_TERMINALS;
var init_supports_hyperlinks = __esm(() => {
import_supports_hyperlinks = __toESM(require_supports_hyperlinks(), 1);
ADDITIONAL_HYPERLINK_TERMINALS = [
"ghostty",
"Hyper",
"kitty",
"alacritty",
"iTerm.app",
"iTerm2"
];
});
// src/ink/components/Link.tsx
function Link(t0) {
const $2 = c5(5);
const {
children,
url: url3,
fallback
} = t0;
const content = children ?? url3;
if (supportsHyperlinks()) {
let t12;
if ($2[0] !== content || $2[1] !== url3) {
t12 = /* @__PURE__ */ jsx_dev_runtime11.jsxDEV(Text, {
children: /* @__PURE__ */ jsx_dev_runtime11.jsxDEV("ink-link", {
href: url3,
children: content
}, undefined, false, undefined, this)
}, undefined, false, undefined, this);
$2[0] = content;
$2[1] = url3;
$2[2] = t12;
} else {
t12 = $2[2];
}
return t12;
}
const t1 = fallback ?? content;
let t2;
if ($2[3] !== t1) {
t2 = /* @__PURE__ */ jsx_dev_runtime11.jsxDEV(Text, {
children: t1
}, undefined, false, undefined, this);
$2[3] = t1;
$2[4] = t2;
} else {
t2 = $2[4];
}
return t2;
}
var jsx_dev_runtime11;
var init_Link = __esm(() => {
init_supports_hyperlinks();
init_Text();
jsx_dev_runtime11 = __toESM(require_jsx_dev_runtime(), 1);
});
// src/ink/termio/esc.ts
function parseEsc(chars) {
if (chars.length === 0)
return null;
const first = chars[0];
if (first === "c") {
return { type: "reset" };
}
if (first === "7") {
return { type: "cursor", action: { type: "save" } };
}
if (first === "8") {
return { type: "cursor", action: { type: "restore" } };
}
if (first === "D") {
return {
type: "cursor",
action: { type: "move", direction: "down", count: 1 }
};
}
if (first === "M") {
return {
type: "cursor",
action: { type: "move", direction: "up", count: 1 }
};
}
if (first === "E") {
return { type: "cursor", action: { type: "nextLine", count: 1 } };
}
if (first === "H") {
return null;
}
if ("()".includes(first) && chars.length >= 2) {
return null;
}
return { type: "unknown", sequence: `\x1B${chars}` };
}
// src/ink/termio/types.ts
function defaultStyle2() {
return {
bold: false,
dim: false,
italic: false,
underline: "none",
blink: false,
inverse: false,
hidden: false,
strikethrough: false,
overline: false,
fg: { type: "default" },
bg: { type: "default" },
underlineColor: { type: "default" }
};
}
// src/ink/termio/sgr.ts
function parseParams(str) {
if (str === "")
return [{ value: 0, subparams: [], colon: false }];
const result = [];
let current = { value: null, subparams: [], colon: false };
let num = "";
let inSub = false;
for (let i2 = 0;i2 <= str.length; i2++) {
const c6 = str[i2];
if (c6 === ";" || c6 === undefined) {
const n2 = num === "" ? null : parseInt(num, 10);
if (inSub) {
if (n2 !== null)
current.subparams.push(n2);
} else {
current.value = n2;
}
result.push(current);
current = { value: null, subparams: [], colon: false };
num = "";
inSub = false;
} else if (c6 === ":") {
const n2 = num === "" ? null : parseInt(num, 10);
if (!inSub) {
current.value = n2;
current.colon = true;
inSub = true;
} else {
if (n2 !== null)
current.subparams.push(n2);
}
num = "";
} else if (c6 >= "0" && c6 <= "9") {
num += c6;
}
}
return result;
}
function parseExtendedColor(params, idx) {
const p = params[idx];
if (!p)
return null;
if (p.colon && p.subparams.length >= 1) {
if (p.subparams[0] === 5 && p.subparams.length >= 2) {
return { index: p.subparams[1] };
}
if (p.subparams[0] === 2 && p.subparams.length >= 4) {
const off = p.subparams.length >= 5 ? 1 : 0;
return {
r: p.subparams[1 + off],
g: p.subparams[2 + off],
b: p.subparams[3 + off]
};
}
}
const next = params[idx + 1];
if (!next)
return null;
if (next.value === 5 && params[idx + 2]?.value !== null && params[idx + 2]?.value !== undefined) {
return { index: params[idx + 2].value };
}
if (next.value === 2) {
const r = params[idx + 2]?.value;
const g = params[idx + 3]?.value;
const b = params[idx + 4]?.value;
if (r !== null && r !== undefined && g !== null && g !== undefined && b !== null && b !== undefined) {
return { r, g, b };
}
}
return null;
}
function applySGR(paramStr, style) {
const params = parseParams(paramStr);
let s = { ...style };
let i2 = 0;
while (i2 < params.length) {
const p = params[i2];
const code = p.value ?? 0;
if (code === 0) {
s = defaultStyle2();
i2++;
continue;
}
if (code === 1) {
s.bold = true;
i2++;
continue;
}
if (code === 2) {
s.dim = true;
i2++;
continue;
}
if (code === 3) {
s.italic = true;
i2++;
continue;
}
if (code === 4) {
s.underline = p.colon ? UNDERLINE_STYLES[p.subparams[0]] ?? "single" : "single";
i2++;
continue;
}
if (code === 5 || code === 6) {
s.blink = true;
i2++;
continue;
}
if (code === 7) {
s.inverse = true;
i2++;
continue;
}
if (code === 8) {
s.hidden = true;
i2++;
continue;
}
if (code === 9) {
s.strikethrough = true;
i2++;
continue;
}
if (code === 21) {
s.underline = "double";
i2++;
continue;
}
if (code === 22) {
s.bold = false;
s.dim = false;
i2++;
continue;
}
if (code === 23) {
s.italic = false;
i2++;
continue;
}
if (code === 24) {
s.underline = "none";
i2++;
continue;
}
if (code === 25) {
s.blink = false;
i2++;
continue;
}
if (code === 27) {
s.inverse = false;
i2++;
continue;
}
if (code === 28) {
s.hidden = false;
i2++;
continue;
}
if (code === 29) {
s.strikethrough = false;
i2++;
continue;
}
if (code === 53) {
s.overline = true;
i2++;
continue;
}
if (code === 55) {
s.overline = false;
i2++;
continue;
}
if (code >= 30 && code <= 37) {
s.fg = { type: "named", name: NAMED_COLORS[code - 30] };
i2++;
continue;
}
if (code === 39) {
s.fg = { type: "default" };
i2++;
continue;
}
if (code >= 40 && code <= 47) {
s.bg = { type: "named", name: NAMED_COLORS[code - 40] };
i2++;
continue;
}
if (code === 49) {
s.bg = { type: "default" };
i2++;
continue;
}
if (code >= 90 && code <= 97) {
s.fg = { type: "named", name: NAMED_COLORS[code - 90 + 8] };
i2++;
continue;
}
if (code >= 100 && code <= 107) {
s.bg = { type: "named", name: NAMED_COLORS[code - 100 + 8] };
i2++;
continue;
}
if (code === 38) {
const c6 = parseExtendedColor(params, i2);
if (c6) {
s.fg = "index" in c6 ? { type: "indexed", index: c6.index } : { type: "rgb", ...c6 };
i2 += p.colon ? 1 : ("index" in c6) ? 3 : 5;
continue;
}
}
if (code === 48) {
const c6 = parseExtendedColor(params, i2);
if (c6) {
s.bg = "index" in c6 ? { type: "indexed", index: c6.index } : { type: "rgb", ...c6 };
i2 += p.colon ? 1 : ("index" in c6) ? 3 : 5;
continue;
}
}
if (code === 58) {
const c6 = parseExtendedColor(params, i2);
if (c6) {
s.underlineColor = "index" in c6 ? { type: "indexed", index: c6.index } : { type: "rgb", ...c6 };
i2 += p.colon ? 1 : ("index" in c6) ? 3 : 5;
continue;
}
}
if (code === 59) {
s.underlineColor = { type: "default" };
i2++;
continue;
}
i2++;
}
return s;
}
var NAMED_COLORS, UNDERLINE_STYLES;
var init_sgr = __esm(() => {
NAMED_COLORS = [
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
"brightBlack",
"brightRed",
"brightGreen",
"brightYellow",
"brightBlue",
"brightMagenta",
"brightCyan",
"brightWhite"
];
UNDERLINE_STYLES = [
"none",
"single",
"double",
"curly",
"dotted",
"dashed"
];
});
// src/ink/termio/parser.ts
function isEmoji(codePoint) {
return codePoint >= 9728 && codePoint <= 9983 || codePoint >= 9984 && codePoint <= 10175 || codePoint >= 127744 && codePoint <= 129535 || codePoint >= 129536 && codePoint <= 129791 || codePoint >= 127456 && codePoint <= 127487;
}
function isEastAsianWide(codePoint) {
return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 11904 && codePoint <= 40959 || codePoint >= 44032 && codePoint <= 55203 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65040 && codePoint <= 65055 || codePoint >= 65072 && codePoint <= 65135 || codePoint >= 65280 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510 || codePoint >= 131072 && codePoint <= 196605 || codePoint >= 196608 && codePoint <= 262141;
}
function hasMultipleCodepoints(str) {
let count3 = 0;
for (const _ of str) {
count3++;
if (count3 > 1)
return true;
}
return false;
}
function graphemeWidth(grapheme) {
if (hasMultipleCodepoints(grapheme))
return 2;
const codePoint = grapheme.codePointAt(0);
if (codePoint === undefined)
return 1;
if (isEmoji(codePoint) || isEastAsianWide(codePoint))
return 2;
return 1;
}
function* segmentGraphemes(str) {
for (const { segment } of getGraphemeSegmenter().segment(str)) {
yield { value: segment, width: graphemeWidth(segment) };
}
}
function parseCSIParams(paramStr) {
if (paramStr === "")
return [];
return paramStr.split(/[;:]/).map((s) => s === "" ? 0 : parseInt(s, 10));
}
function parseCSI(rawSequence) {
const inner = rawSequence.slice(2);
if (inner.length === 0)
return null;
const finalByte = inner.charCodeAt(inner.length - 1);
const beforeFinal = inner.slice(0, -1);
let privateMode = "";
let paramStr = beforeFinal;
let intermediate = "";
if (beforeFinal.length > 0 && "?>=".includes(beforeFinal[0])) {
privateMode = beforeFinal[0];
paramStr = beforeFinal.slice(1);
}
const intermediateMatch = paramStr.match(/([^0-9;:]+)$/);
if (intermediateMatch) {
intermediate = intermediateMatch[1];
paramStr = paramStr.slice(0, -intermediate.length);
}
const params = parseCSIParams(paramStr);
const p0 = params[0] ?? 1;
const p1 = params[1] ?? 1;
if (finalByte === CSI.SGR && privateMode === "") {
return { type: "sgr", params: paramStr };
}
if (finalByte === CSI.CUU) {
return {
type: "cursor",
action: { type: "move", direction: "up", count: p0 }
};
}
if (finalByte === CSI.CUD) {
return {
type: "cursor",
action: { type: "move", direction: "down", count: p0 }
};
}
if (finalByte === CSI.CUF) {
return {
type: "cursor",
action: { type: "move", direction: "forward", count: p0 }
};
}
if (finalByte === CSI.CUB) {
return {
type: "cursor",
action: { type: "move", direction: "back", count: p0 }
};
}
if (finalByte === CSI.CNL) {
return { type: "cursor", action: { type: "nextLine", count: p0 } };
}
if (finalByte === CSI.CPL) {
return { type: "cursor", action: { type: "prevLine", count: p0 } };
}
if (finalByte === CSI.CHA) {
return { type: "cursor", action: { type: "column", col: p0 } };
}
if (finalByte === CSI.CUP || finalByte === CSI.HVP) {
return { type: "cursor", action: { type: "position", row: p0, col: p1 } };
}
if (finalByte === CSI.VPA) {
return { type: "cursor", action: { type: "row", row: p0 } };
}
if (finalByte === CSI.ED) {
const region = ERASE_DISPLAY[params[0] ?? 0] ?? "toEnd";
return { type: "erase", action: { type: "display", region } };
}
if (finalByte === CSI.EL) {
const region = ERASE_LINE_REGION[params[0] ?? 0] ?? "toEnd";
return { type: "erase", action: { type: "line", region } };
}
if (finalByte === CSI.ECH) {
return { type: "erase", action: { type: "chars", count: p0 } };
}
if (finalByte === CSI.SU) {
return { type: "scroll", action: { type: "up", count: p0 } };
}
if (finalByte === CSI.SD) {
return { type: "scroll", action: { type: "down", count: p0 } };
}
if (finalByte === CSI.DECSTBM) {
return {
type: "scroll",
action: { type: "setRegion", top: p0, bottom: p1 }
};
}
if (finalByte === CSI.SCOSC) {
return { type: "cursor", action: { type: "save" } };
}
if (finalByte === CSI.SCORC) {
return { type: "cursor", action: { type: "restore" } };
}
if (finalByte === CSI.DECSCUSR && intermediate === " ") {
const styleInfo = CURSOR_STYLES[p0] ?? CURSOR_STYLES[0];
return { type: "cursor", action: { type: "style", ...styleInfo } };
}
if (privateMode === "?" && (finalByte === CSI.SM || finalByte === CSI.RM)) {
const enabled = finalByte === CSI.SM;
if (p0 === DEC.CURSOR_VISIBLE) {
return {
type: "cursor",
action: enabled ? { type: "show" } : { type: "hide" }
};
}
if (p0 === DEC.ALT_SCREEN_CLEAR || p0 === DEC.ALT_SCREEN) {
return { type: "mode", action: { type: "alternateScreen", enabled } };
}
if (p0 === DEC.BRACKETED_PASTE) {
return { type: "mode", action: { type: "bracketedPaste", enabled } };
}
if (p0 === DEC.MOUSE_NORMAL) {
return {
type: "mode",
action: { type: "mouseTracking", mode: enabled ? "normal" : "off" }
};
}
if (p0 === DEC.MOUSE_BUTTON) {
return {
type: "mode",
action: { type: "mouseTracking", mode: enabled ? "button" : "off" }
};
}
if (p0 === DEC.MOUSE_ANY) {
return {
type: "mode",
action: { type: "mouseTracking", mode: enabled ? "any" : "off" }
};
}
if (p0 === DEC.FOCUS_EVENTS) {
return { type: "mode", action: { type: "focusEvents", enabled } };
}
}
return { type: "unknown", sequence: rawSequence };
}
function identifySequence(seq) {
if (seq.length < 2)
return "unknown";
if (seq.charCodeAt(0) !== C0.ESC)
return "unknown";
const second = seq.charCodeAt(1);
if (second === 91)
return "csi";
if (second === 93)
return "osc";
if (second === 79)
return "ss3";
return "esc";
}
class Parser {
tokenizer = createTokenizer();
style = defaultStyle2();
inLink = false;
linkUrl;
reset() {
this.tokenizer.reset();
this.style = defaultStyle2();
this.inLink = false;
this.linkUrl = undefined;
}
feed(input) {
const tokens = this.tokenizer.feed(input);
const actions = [];
for (const token of tokens) {
const tokenActions = this.processToken(token);
actions.push(...tokenActions);
}
return actions;
}
processToken(token) {
switch (token.type) {
case "text":
return this.processText(token.value);
case "sequence":
return this.processSequence(token.value);
}
}
processText(text) {
const actions = [];
let current = "";
for (const char of text) {
if (char.charCodeAt(0) === C0.BEL) {
if (current) {
const graphemes = [...segmentGraphemes(current)];
if (graphemes.length > 0) {
actions.push({ type: "text", graphemes, style: { ...this.style } });
}
current = "";
}
actions.push({ type: "bell" });
} else {
current += char;
}
}
if (current) {
const graphemes = [...segmentGraphemes(current)];
if (graphemes.length > 0) {
actions.push({ type: "text", graphemes, style: { ...this.style } });
}
}
return actions;
}
processSequence(seq) {
const seqType = identifySequence(seq);
switch (seqType) {
case "csi": {
const action = parseCSI(seq);
if (!action)
return [];
if (action.type === "sgr") {
this.style = applySGR(action.params, this.style);
return [];
}
return [action];
}
case "osc": {
let content = seq.slice(2);
if (content.endsWith("\x07")) {
content = content.slice(0, -1);
} else if (content.endsWith("\x1B\\")) {
content = content.slice(0, -2);
}
const action = parseOSC(content);
if (action) {
if (action.type === "link") {
if (action.action.type === "start") {
this.inLink = true;
this.linkUrl = action.action.url;
} else {
this.inLink = false;
this.linkUrl = undefined;
}
}
return [action];
}
return [];
}
case "esc": {
const escContent = seq.slice(1);
const action = parseEsc(escContent);
return action ? [action] : [];
}
case "ss3":
return [{ type: "unknown", sequence: seq }];
default:
return [{ type: "unknown", sequence: seq }];
}
}
}
var init_parser4 = __esm(() => {
init_intl();
init_ansi();
init_csi();
init_dec();
init_osc();
init_sgr();
init_tokenize();
});
// src/ink/termio.ts
var init_termio = __esm(() => {
init_parser4();
});
// src/ink/Ansi.tsx
function parseToSpans(input) {
const parser = new Parser;
const actions = parser.feed(input);
const spans = [];
let currentHyperlink;
for (const action of actions) {
if (action.type === "link") {
if (action.action.type === "start") {
currentHyperlink = action.action.url;
} else {
currentHyperlink = undefined;
}
continue;
}
if (action.type === "text") {
const text = action.graphemes.map((g) => g.value).join("");
if (!text)
continue;
const props = textStyleToSpanProps(action.style);
if (currentHyperlink) {
props.hyperlink = currentHyperlink;
}
const lastSpan = spans[spans.length - 1];
if (lastSpan && propsEqual(lastSpan.props, props)) {
lastSpan.text += text;
} else {
spans.push({
text,
props
});
}
}
}
return spans;
}
function textStyleToSpanProps(style) {
const props = {};
if (style.bold)
props.bold = true;
if (style.dim)
props.dim = true;
if (style.italic)
props.italic = true;
if (style.underline !== "none")
props.underline = true;
if (style.strikethrough)
props.strikethrough = true;
if (style.inverse)
props.inverse = true;
const fgColor = colorToString(style.fg);
if (fgColor)
props.color = fgColor;
const bgColor = colorToString(style.bg);
if (bgColor)
props.backgroundColor = bgColor;
return props;
}
function colorToString(color2) {
switch (color2.type) {
case "named":
return NAMED_COLOR_MAP[color2.name];
case "indexed":
return `ansi256(${color2.index})`;
case "rgb":
return `rgb(${color2.r},${color2.g},${color2.b})`;
case "default":
return;
}
}
function propsEqual(a2, b) {
return a2.color === b.color && a2.backgroundColor === b.backgroundColor && a2.bold === b.bold && a2.dim === b.dim && a2.italic === b.italic && a2.underline === b.underline && a2.strikethrough === b.strikethrough && a2.inverse === b.inverse && a2.hyperlink === b.hyperlink;
}
function hasAnyProps(props) {
return props.color !== undefined || props.backgroundColor !== undefined || props.dim === true || props.bold === true || props.italic === true || props.underline === true || props.strikethrough === true || props.inverse === true || props.hyperlink !== undefined;
}
function hasAnyTextProps(props) {
return props.color !== undefined || props.backgroundColor !== undefined || props.dim === true || props.bold === true || props.italic === true || props.underline === true || props.strikethrough === true || props.inverse === true;
}
function StyledText(t0) {
const $2 = c5(14);
let bold2;
let children;
let dim2;
let rest;
if ($2[0] !== t0) {
({
bold: bold2,
dim: dim2,
children,
...rest
} = t0);
$2[0] = t0;
$2[1] = bold2;
$2[2] = children;
$2[3] = dim2;
$2[4] = rest;
} else {
bold2 = $2[1];
children = $2[2];
dim2 = $2[3];
rest = $2[4];
}
if (dim2) {
let t12;
if ($2[5] !== children || $2[6] !== rest) {
t12 = /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
...rest,
dim: true,
children
}, undefined, false, undefined, this);
$2[5] = children;
$2[6] = rest;
$2[7] = t12;
} else {
t12 = $2[7];
}
return t12;
}
if (bold2) {
let t12;
if ($2[8] !== children || $2[9] !== rest) {
t12 = /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
...rest,
bold: true,
children
}, undefined, false, undefined, this);
$2[8] = children;
$2[9] = rest;
$2[10] = t12;
} else {
t12 = $2[10];
}
return t12;
}
let t1;
if ($2[11] !== children || $2[12] !== rest) {
t1 = /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
...rest,
children
}, undefined, false, undefined, this);
$2[11] = children;
$2[12] = rest;
$2[13] = t1;
} else {
t1 = $2[13];
}
return t1;
}
var import_react13, jsx_dev_runtime12, Ansi, NAMED_COLOR_MAP;
var init_Ansi = __esm(() => {
init_Link();
init_Text();
init_termio();
import_react13 = __toESM(require_react(), 1);
jsx_dev_runtime12 = __toESM(require_jsx_dev_runtime(), 1);
Ansi = import_react13.default.memo(function Ansi2(t0) {
const $2 = c5(12);
const {
children,
dimColor
} = t0;
if (typeof children !== "string") {
let t12;
if ($2[0] !== children || $2[1] !== dimColor) {
t12 = dimColor ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
dim: true,
children: String(children)
}, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
children: String(children)
}, undefined, false, undefined, this);
$2[0] = children;
$2[1] = dimColor;
$2[2] = t12;
} else {
t12 = $2[2];
}
return t12;
}
if (children === "") {
return null;
}
let t1;
let t2;
if ($2[3] !== children || $2[4] !== dimColor) {
t2 = Symbol.for("react.early_return_sentinel");
bb0: {
const spans = parseToSpans(children);
if (spans.length === 0) {
t2 = null;
break bb0;
}
if (spans.length === 1 && !hasAnyProps(spans[0].props)) {
t2 = dimColor ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
dim: true,
children: spans[0].text
}, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
children: spans[0].text
}, undefined, false, undefined, this);
break bb0;
}
let t32;
if ($2[7] !== dimColor) {
t32 = (span, i2) => {
const hyperlink = span.props.hyperlink;
if (dimColor) {
span.props.dim = true;
}
const hasTextProps = hasAnyTextProps(span.props);
if (hyperlink) {
return hasTextProps ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Link, {
url: hyperlink,
children: /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(StyledText, {
color: span.props.color,
backgroundColor: span.props.backgroundColor,
dim: span.props.dim,
bold: span.props.bold,
italic: span.props.italic,
underline: span.props.underline,
strikethrough: span.props.strikethrough,
inverse: span.props.inverse,
children: span.text
}, undefined, false, undefined, this)
}, i2, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Link, {
url: hyperlink,
children: span.text
}, i2, false, undefined, this);
}
return hasTextProps ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(StyledText, {
color: span.props.color,
backgroundColor: span.props.backgroundColor,
dim: span.props.dim,
bold: span.props.bold,
italic: span.props.italic,
underline: span.props.underline,
strikethrough: span.props.strikethrough,
inverse: span.props.inverse,
children: span.text
}, i2, false, undefined, this) : span.text;
};
$2[7] = dimColor;
$2[8] = t32;
} else {
t32 = $2[8];
}
t1 = spans.map(t32);
}
$2[3] = children;
$2[4] = dimColor;
$2[5] = t1;
$2[6] = t2;
} else {
t1 = $2[5];
t2 = $2[6];
}
if (t2 !== Symbol.for("react.early_return_sentinel")) {
return t2;
}
const content = t1;
let t3;
if ($2[9] !== content || $2[10] !== dimColor) {
t3 = dimColor ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
dim: true,
children: content
}, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
children: content
}, undefined, false, undefined, this);
$2[9] = content;
$2[10] = dimColor;
$2[11] = t3;
} else {
t3 = $2[11];
}
return t3;
});
NAMED_COLOR_MAP = {
black: "ansi:black",
red: "ansi:red",
green: "ansi:green",
yellow: "ansi:yellow",
blue: "ansi:blue",
magenta: "ansi:magenta",
cyan: "ansi:cyan",
white: "ansi:white",
brightBlack: "ansi:blackBright",
brightRed: "ansi:redBright",
brightGreen: "ansi:greenBright",
brightYellow: "ansi:yellowBright",
brightBlue: "ansi:blueBright",
brightMagenta: "ansi:magentaBright",
brightCyan: "ansi:cyanBright",
brightWhite: "ansi:whiteBright"
};
});
// src/ink/components/Button.tsx
function Button(t0) {
const $2 = c5(30);
let autoFocus;
let children;
let onAction;
let ref;
let style;
let t1;
if ($2[0] !== t0) {
({
onAction,
tabIndex: t1,
autoFocus,
children,
ref,
...style
} = t0);
$2[0] = t0;
$2[1] = autoFocus;
$2[2] = children;
$2[3] = onAction;
$2[4] = ref;
$2[5] = style;
$2[6] = t1;
} else {
autoFocus = $2[1];
children = $2[2];
onAction = $2[3];
ref = $2[4];
style = $2[5];
t1 = $2[6];
}
const tabIndex = t1 === undefined ? 0 : t1;
const [isFocused, setIsFocused] = import_react14.useState(false);
const [isHovered, setIsHovered] = import_react14.useState(false);
const [isActive, setIsActive] = import_react14.useState(false);
const activeTimer = import_react14.useRef(null);
let t2;
let t3;
if ($2[7] === Symbol.for("react.memo_cache_sentinel")) {
t2 = () => () => {
if (activeTimer.current) {
clearTimeout(activeTimer.current);
}
};
t3 = [];
$2[7] = t2;
$2[8] = t3;
} else {
t2 = $2[7];
t3 = $2[8];
}
import_react14.useEffect(t2, t3);
let t4;
if ($2[9] !== onAction) {
t4 = (e) => {
if (e.key === "return" || e.key === " ") {
e.preventDefault();
setIsActive(true);
onAction();
if (activeTimer.current) {
clearTimeout(activeTimer.current);
}
activeTimer.current = setTimeout(_temp2, 100, setIsActive);
}
};
$2[9] = onAction;
$2[10] = t4;
} else {
t4 = $2[10];
}
const handleKeyDown = t4;
let t5;
if ($2[11] !== onAction) {
t5 = (_e) => {
onAction();
};
$2[11] = onAction;
$2[12] = t5;
} else {
t5 = $2[12];
}
const handleClick = t5;
let t6;
if ($2[13] === Symbol.for("react.memo_cache_sentinel")) {
t6 = (_e_0) => setIsFocused(true);
$2[13] = t6;
} else {
t6 = $2[13];
}
const handleFocus = t6;
let t7;
if ($2[14] === Symbol.for("react.memo_cache_sentinel")) {
t7 = (_e_1) => setIsFocused(false);
$2[14] = t7;
} else {
t7 = $2[14];
}
const handleBlur = t7;
let t8;
if ($2[15] === Symbol.for("react.memo_cache_sentinel")) {
t8 = () => setIsHovered(true);
$2[15] = t8;
} else {
t8 = $2[15];
}
const handleMouseEnter = t8;
let t9;
if ($2[16] === Symbol.for("react.memo_cache_sentinel")) {
t9 = () => setIsHovered(false);
$2[16] = t9;
} else {
t9 = $2[16];
}
const handleMouseLeave = t9;
let t10;
if ($2[17] !== children || $2[18] !== isActive || $2[19] !== isFocused || $2[20] !== isHovered) {
const state = {
focused: isFocused,
hovered: isHovered,
active: isActive
};
t10 = typeof children === "function" ? children(state) : children;
$2[17] = children;
$2[18] = isActive;
$2[19] = isFocused;
$2[20] = isHovered;
$2[21] = t10;
} else {
t10 = $2[21];
}
const content = t10;
let t11;
if ($2[22] !== autoFocus || $2[23] !== content || $2[24] !== handleClick || $2[25] !== handleKeyDown || $2[26] !== ref || $2[27] !== style || $2[28] !== tabIndex) {
t11 = /* @__PURE__ */ jsx_dev_runtime13.jsxDEV(Box_default, {
ref,
tabIndex,
autoFocus,
onKeyDown: handleKeyDown,
onClick: handleClick,
onFocus: handleFocus,
onBlur: handleBlur,
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave,
...style,
children: content
}, undefined, false, undefined, this);
$2[22] = autoFocus;
$2[23] = content;
$2[24] = handleClick;
$2[25] = handleKeyDown;
$2[26] = ref;
$2[27] = style;
$2[28] = tabIndex;
$2[29] = t11;
} else {
t11 = $2[29];
}
return t11;
}
function _temp2(setter) {
return setter(false);
}
var import_react14, jsx_dev_runtime13, Button_default;
var init_Button = __esm(() => {
init_Box();
import_react14 = __toESM(require_react(), 1);
jsx_dev_runtime13 = __toESM(require_jsx_dev_runtime(), 1);
Button_default = Button;
});
// src/ink/components/Newline.tsx
function Newline(t0) {
const $2 = c5(4);
const {
count: t1
} = t0;
const count3 = t1 === undefined ? 1 : t1;
let t2;
if ($2[0] !== count3) {
t2 = `
`.repeat(count3);
$2[0] = count3;
$2[1] = t2;
} else {
t2 = $2[1];
}
let t3;
if ($2[2] !== t2) {
t3 = /* @__PURE__ */ jsx_dev_runtime14.jsxDEV("ink-text", {
children: t2
}, undefined, false, undefined, this);
$2[2] = t2;
$2[3] = t3;
} else {
t3 = $2[3];
}
return t3;
}
var jsx_dev_runtime14;
var init_Newline = __esm(() => {
jsx_dev_runtime14 = __toESM(require_jsx_dev_runtime(), 1);
});
// src/ink/components/NoSelect.tsx
function NoSelect(t0) {
const $2 = c5(8);
let boxProps;
let children;
let fromLeftEdge;
if ($2[0] !== t0) {
({
children,
fromLeftEdge,
...boxProps
} = t0);
$2[0] = t0;
$2[1] = boxProps;
$2[2] = children;
$2[3] = fromLeftEdge;
} else {
boxProps = $2[1];
children = $2[2];
fromLeftEdge = $2[3];
}
const t1 = fromLeftEdge ? "from-left-edge" : true;
let t2;
if ($2[4] !== boxProps || $2[5] !== children || $2[6] !== t1) {
t2 = /* @__PURE__ */ jsx_dev_runtime15.jsxDEV(Box_default, {
...boxProps,
noSelect: t1,
children
}, undefined, false, undefined, this);
$2[4] = boxProps;
$2[5] = children;
$2[6] = t1;
$2[7] = t2;
} else {
t2 = $2[7];
}
return t2;
}
var jsx_dev_runtime15;
var init_NoSelect = __esm(() => {
init_Box();
jsx_dev_runtime15 = __toESM(require_jsx_dev_runtime(), 1);
});
// src/ink/components/RawAnsi.tsx
function RawAnsi(t0) {
const $2 = c5(6);
const {
lines,
width
} = t0;
if (lines.length === 0) {
return null;
}
let t1;
if ($2[0] !== lines) {
t1 = lines.join(`
`);
$2[0] = lines;
$2[1] = t1;
} else {
t1 = $2[1];
}
let t2;
if ($2[2] !== lines.length || $2[3] !== t1 || $2[4] !== width) {
t2 = /* @__PURE__ */ jsx_dev_runtime16.jsxDEV("ink-raw-ansi", {
rawText: t1,
rawWidth: width,
rawHeight: lines.length
}, undefined, false, undefined, this);
$2[2] = lines.length;
$2[3] = t1;
$2[4] = width;
$2[5] = t2;
} else {
t2 = $2[5];
}
return t2;
}
var jsx_dev_runtime16;
var init_RawAnsi = __esm(() => {
jsx_dev_runtime16 = __toESM(require_jsx_dev_runtime(), 1);
});
// src/ink/components/Spacer.tsx
function Spacer() {
const $2 = c5(1);
let t0;
if ($2[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = /* @__PURE__ */ jsx_dev_runtime17.jsxDEV(Box_default, {
flexGrow: 1
}, undefined, false, undefined, this);
$2[0] = t0;
} else {
t0 = $2[0];
}
return t0;
}
var jsx_dev_runtime17;
var init_Spacer = __esm(() => {
init_Box();
jsx_dev_runtime17 = __toESM(require_jsx_dev_runtime(), 1);
});
// src/ink/hooks/use-terminal-viewport.ts
function useTerminalViewport() {
const terminalSize = import_react15.useContext(TerminalSizeContext);
const elementRef = import_react15.useRef(null);
const entryRef = import_react15.useRef({ isVisible: true });
const setElement = import_react15.useCallback((el) => {
elementRef.current = el;
}, []);
import_react15.useLayoutEffect(() => {
const element = elementRef.current;
if (!element?.yogaNode || !terminalSize) {
return;
}
const height = element.yogaNode.getComputedHeight();
const rows = terminalSize.rows;
let absoluteTop = element.yogaNode.getComputedTop();
let parent = element.parentNode;
let root2 = element.yogaNode;
while (parent) {
if (parent.yogaNode) {
absoluteTop += parent.yogaNode.getComputedTop();
root2 = parent.yogaNode;
}
if (parent.scrollTop)
absoluteTop -= parent.scrollTop;
parent = parent.parentNode;
}
const screenHeight = root2.getComputedHeight();
const bottom = absoluteTop + height;
const cursorRestoreScroll = screenHeight > rows ? 1 : 0;
const viewportY = Math.max(0, screenHeight - rows) + cursorRestoreScroll;
const viewportBottom = viewportY + rows;
const visible = bottom > viewportY && absoluteTop < viewportBottom;
if (visible !== entryRef.current.isVisible) {
entryRef.current = { isVisible: visible };
}
});
return [setElement, entryRef.current];
}
var import_react15;
var init_use_terminal_viewport = __esm(() => {
init_TerminalSizeContext();
import_react15 = __toESM(require_react(), 1);
});
// src/ink/hooks/use-animation-frame.ts
function useAnimationFrame(intervalMs = 16) {
const clock = import_react16.useContext(ClockContext);
const [viewportRef, { isVisible }] = useTerminalViewport();
const [time3, setTime] = import_react16.useState(() => clock?.now() ?? 0);
const active = isVisible && intervalMs !== null;
import_react16.useEffect(() => {
if (!clock || !active)
return;
let lastUpdate = clock.now();
const onChange = () => {
const now2 = clock.now();
if (now2 - lastUpdate >= intervalMs) {
lastUpdate = now2;
setTime(now2);
}
};
return clock.subscribe(onChange, true);
}, [clock, intervalMs, active]);
return [viewportRef, time3];
}
var import_react16;
var init_use_animation_frame = __esm(() => {
init_ClockContext();
init_use_terminal_viewport();
import_react16 = __toESM(require_react(), 1);
});
// src/ink/hooks/use-app.ts
var import_react17, useApp = () => import_react17.useContext(AppContext_default), use_app_default;
var init_use_app = __esm(() => {
init_AppContext();
import_react17 = __toESM(require_react(), 1);
use_app_default = useApp;
});
// node_modules/lodash.debounce/index.js
var require_lodash = __commonJS((exports, module) => {
var FUNC_ERROR_TEXT4 = "Expected a function";
var NAN2 = 0 / 0;
var symbolTag5 = "[object Symbol]";
var reTrim = /^\s+|\s+$/g;
var reIsBadHex2 = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary2 = /^0b[01]+$/i;
var reIsOctal2 = /^0o[0-7]+$/i;
var freeParseInt2 = parseInt;
var freeGlobal2 = typeof global == "object" && global && global.Object === Object && global;
var freeSelf2 = typeof self == "object" && self && self.Object === Object && self;
var root2 = freeGlobal2 || freeSelf2 || Function("return this")();
var objectProto17 = Object.prototype;
var objectToString4 = objectProto17.toString;
var nativeMax3 = Math.max;
var nativeMin2 = Math.min;
var now2 = function() {
return root2.Date.now();
};
function debounce2(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
if (typeof func != "function") {
throw new TypeError(FUNC_ERROR_TEXT4);
}
wait = toNumber2(wait) || 0;
if (isObject5(options)) {
leading = !!options.leading;
maxing = "maxWait" in options;
maxWait = maxing ? nativeMax3(toNumber2(options.maxWait) || 0, wait) : maxWait;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
function invokeFunc(time3) {
var args = lastArgs, thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time3;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge2(time3) {
lastInvokeTime = time3;
timerId = setTimeout(timerExpired, wait);
return leading ? invokeFunc(time3) : result;
}
function remainingWait(time3) {
var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime, result2 = wait - timeSinceLastCall;
return maxing ? nativeMin2(result2, maxWait - timeSinceLastInvoke) : result2;
}
function shouldInvoke(time3) {
var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime;
return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time3 = now2();
if (shouldInvoke(time3)) {
return trailingEdge2(time3);
}
timerId = setTimeout(timerExpired, remainingWait(time3));
}
function trailingEdge2(time3) {
timerId = undefined;
if (trailing && lastArgs) {
return invokeFunc(time3);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge2(now2());
}
function debounced() {
var time3 = now2(), isInvoking = shouldInvoke(time3);
lastArgs = arguments;
lastThis = this;
lastCallTime = time3;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge2(lastCallTime);
}
if (maxing) {
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
function isObject5(value) {
var type = typeof value;
return !!value && (type == "object" || type == "function");
}
function isObjectLike2(value) {
return !!value && typeof value == "object";
}
function isSymbol2(value) {
return typeof value == "symbol" || isObjectLike2(value) && objectToString4.call(value) == symbolTag5;
}
function toNumber2(value) {
if (typeof value == "number") {
return value;
}
if (isSymbol2(value)) {
return NAN2;
}
if (isObject5(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject5(other) ? other + "" : other;
}
if (typeof value != "string") {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, "");
var isBinary = reIsBinary2.test(value);
return isBinary || reIsOctal2.test(value) ? freeParseInt2(value.slice(2), isBinary ? 2 : 8) : reIsBadHex2.test(value) ? NAN2 : +value;
}
module.exports = debounce2;
});
// node_modules/usehooks-ts/dist/index.js
function useInterval(callback, delay) {
const savedCallback = import_react18.useRef(callback);
useIsomorphicLayoutEffect(() => {
savedCallback.current = callback;
}, [callback]);
import_react18.useEffect(() => {
if (delay === null) {
return;
}
const id = setInterval(() => {
savedCallback.current();
}, delay);
return () => {
clearInterval(id);
};
}, [delay]);
}
function useEventCallback(fn) {
const ref = import_react18.useRef(() => {
throw new Error("Cannot call an event handler while rendering.");
});
useIsomorphicLayoutEffect(() => {
ref.current = fn;
}, [fn]);
return import_react18.useCallback((...args) => {
var _a2;
return (_a2 = ref.current) == null ? undefined : _a2.call(ref, ...args);
}, [ref]);
}
function useUnmount(func) {
const funcRef = import_react18.useRef(func);
funcRef.current = func;
import_react18.useEffect(() => () => {
funcRef.current();
}, []);
}
function useDebounceCallback(func, delay = 500, options) {
const debouncedFunc = import_react18.useRef();
useUnmount(() => {
if (debouncedFunc.current) {
debouncedFunc.current.cancel();
}
});
const debounced = import_react18.useMemo(() => {
const debouncedFuncInstance = import_lodash.default(func, delay, options);
const wrappedFunc = (...args) => {
return debouncedFuncInstance(...args);
};
wrappedFunc.cancel = () => {
debouncedFuncInstance.cancel();
};
wrappedFunc.isPending = () => {
return !!debouncedFunc.current;
};
wrappedFunc.flush = () => {
return debouncedFuncInstance.flush();
};
return wrappedFunc;
}, [func, delay, options]);
import_react18.useEffect(() => {
debouncedFunc.current = import_lodash.default(func, delay, options);
}, [func, delay, options]);
return debounced;
}
var import_react18, import_lodash, useIsomorphicLayoutEffect;
var init_dist = __esm(() => {
import_react18 = __toESM(require_react(), 1);
import_lodash = __toESM(require_lodash(), 1);
useIsomorphicLayoutEffect = typeof window !== "undefined" ? import_react18.useLayoutEffect : import_react18.useEffect;
});
// src/ink/hooks/use-input.ts
var import_react19, useInput = (inputHandler, options = {}) => {
const { setRawMode, internal_exitOnCtrlC, internal_eventEmitter } = use_stdin_default();
import_react19.useLayoutEffect(() => {
if (options.isActive === false) {
return;
}
setRawMode(true);
return () => {
setRawMode(false);
};
}, [options.isActive, setRawMode]);
const handleData = useEventCallback((event) => {
if (options.isActive === false) {
return;
}
const { input, key } = event;
if (!(input === "c" && key.ctrl) || !internal_exitOnCtrlC) {
inputHandler(input, key, event);
}
});
import_react19.useEffect(() => {
internal_eventEmitter?.on("input", handleData);
return () => {
internal_eventEmitter?.removeListener("input", handleData);
};
}, [internal_eventEmitter, handleData]);
}, use_input_default;
var init_use_input = __esm(() => {
init_dist();
init_use_stdin();
import_react19 = __toESM(require_react(), 1);
use_input_default = useInput;
});
// src/ink/hooks/use-interval.ts
function useAnimationTimer(intervalMs) {
const clock = import_react20.useContext(ClockContext);
const [time3, setTime] = import_react20.useState(() => clock?.now() ?? 0);
import_react20.useEffect(() => {
if (!clock)
return;
let lastUpdate = clock.now();
const onChange = () => {
const now2 = clock.now();
if (now2 - lastUpdate >= intervalMs) {
lastUpdate = now2;
setTime(now2);
}
};
return clock.subscribe(onChange, false);
}, [clock, intervalMs]);
return time3;
}
function useInterval2(callback, intervalMs) {
const callbackRef = import_react20.useRef(callback);
callbackRef.current = callback;
const clock = import_react20.useContext(ClockContext);
import_react20.useEffect(() => {
if (!clock || intervalMs === null)
return;
let lastUpdate = clock.now();
const onChange = () => {
const now2 = clock.now();
if (now2 - lastUpdate >= intervalMs) {
lastUpdate = now2;
callbackRef.current();
}
};
return clock.subscribe(onChange, false);
}, [clock, intervalMs]);
}
var import_react20;
var init_use_interval = __esm(() => {
init_ClockContext();
import_react20 = __toESM(require_react(), 1);
});
// src/ink/hooks/use-selection.ts
function useSelection() {
import_react21.useContext(StdinContext_default);
const ink = instances_default.get(process.stdout);
return import_react21.useMemo(() => {
if (!ink) {
return {
copySelection: () => "",
copySelectionNoClear: () => "",
clearSelection: () => {},
hasSelection: () => false,
getState: () => null,
subscribe: () => () => {},
shiftAnchor: () => {},
shiftSelection: () => {},
moveFocus: () => {},
captureScrolledRows: () => {},
setSelectionBgColor: () => {}
};
}
return {
copySelection: () => ink.copySelection(),
copySelectionNoClear: () => ink.copySelectionNoClear(),
clearSelection: () => ink.clearTextSelection(),
hasSelection: () => ink.hasTextSelection(),
getState: () => ink.selection,
subscribe: (cb) => ink.subscribeToSelectionChange(cb),
shiftAnchor: (dRow, minRow, maxRow) => shiftAnchor(ink.selection, dRow, minRow, maxRow),
shiftSelection: (dRow, minRow, maxRow) => ink.shiftSelectionForScroll(dRow, minRow, maxRow),
moveFocus: (move) => ink.moveSelectionFocus(move),
captureScrolledRows: (firstRow, lastRow, side) => ink.captureScrolledRows(firstRow, lastRow, side),
setSelectionBgColor: (color2) => ink.setSelectionBgColor(color2)
};
}, [ink]);
}
function useHasSelection() {
import_react21.useContext(StdinContext_default);
const ink = instances_default.get(process.stdout);
return import_react21.useSyncExternalStore(ink ? ink.subscribeToSelectionChange : NO_SUBSCRIBE, ink ? ink.hasTextSelection : ALWAYS_FALSE);
}
var import_react21, NO_SUBSCRIBE = () => () => {}, ALWAYS_FALSE = () => false;
var init_use_selection = __esm(() => {
init_StdinContext();
init_instances();
init_selection();
import_react21 = __toESM(require_react(), 1);
});
// src/ink/hooks/use-tab-status.ts
function useTabStatus(kind) {
const writeRaw = import_react22.useContext(TerminalWriteContext);
const prevKindRef = import_react22.useRef(null);
import_react22.useEffect(() => {
if (kind === null) {
if (prevKindRef.current !== null && writeRaw && supportsTabStatus()) {
writeRaw(wrapForMultiplexer(CLEAR_TAB_STATUS));
}
prevKindRef.current = null;
return;
}
prevKindRef.current = kind;
if (!writeRaw || !supportsTabStatus())
return;
writeRaw(wrapForMultiplexer(tabStatus(TAB_STATUS_PRESETS[kind])));
}, [kind, writeRaw]);
}
var import_react22, rgb = (r, g, b) => ({
type: "rgb",
r,
g,
b
}), TAB_STATUS_PRESETS;
var init_use_tab_status = __esm(() => {
init_osc();
init_useTerminalNotification();
import_react22 = __toESM(require_react(), 1);
TAB_STATUS_PRESETS = {
idle: {
indicator: rgb(0, 215, 95),
status: "Idle",
statusColor: rgb(136, 136, 136)
},
busy: {
indicator: rgb(255, 149, 0),
status: "Working…",
statusColor: rgb(255, 149, 0)
},
waiting: {
indicator: rgb(95, 135, 255),
status: "Waiting",
statusColor: rgb(95, 135, 255)
}
};
});
// src/ink/hooks/use-terminal-title.ts
function useTerminalTitle(title) {
const writeRaw = import_react23.useContext(TerminalWriteContext);
import_react23.useEffect(() => {
if (title === null || !writeRaw)
return;
const clean = stripAnsi(title);
if (process.platform === "win32") {
process.title = clean;
} else {
writeRaw(osc(OSC2.SET_TITLE_AND_ICON, clean));
}
}, [title, writeRaw]);
}
var import_react23;
var init_use_terminal_title = __esm(() => {
init_strip_ansi();
init_osc();
init_useTerminalNotification();
import_react23 = __toESM(require_react(), 1);
});
// src/ink/measure-element.ts
var measureElement = (node) => ({
width: node.yogaNode?.getComputedWidth() ?? 0,
height: node.yogaNode?.getComputedHeight() ?? 0
}), measure_element_default;
var init_measure_element = __esm(() => {
measure_element_default = measureElement;
});
// src/ink.ts
var exports_ink = {};
__export(exports_ink, {
wrapText: () => wrapText2,
useThemeSetting: () => useThemeSetting,
useTheme: () => useTheme,
useTerminalViewport: () => useTerminalViewport,
useTerminalTitle: () => useTerminalTitle,
useTerminalFocus: () => useTerminalFocus,
useTabStatus: () => useTabStatus,
useStdin: () => use_stdin_default,
useSelection: () => useSelection,
usePreviewTheme: () => usePreviewTheme,
useInterval: () => useInterval2,
useInput: () => use_input_default,
useApp: () => use_app_default,
useAnimationTimer: () => useAnimationTimer,
useAnimationFrame: () => useAnimationFrame,
supportsTabStatus: () => supportsTabStatus,
render: () => render,
measureElement: () => measure_element_default,
createRoot: () => createRoot2,
color: () => color,
ThemeProvider: () => ThemeProvider,
Text: () => ThemedText,
TerminalFocusEvent: () => TerminalFocusEvent,
Spacer: () => Spacer,
RawAnsi: () => RawAnsi,
NoSelect: () => NoSelect,
Newline: () => Newline,
Link: () => Link,
InputEvent: () => InputEvent,
FocusManager: () => FocusManager,
EventEmitter: () => EventEmitter3,
Event: () => Event2,
ClickEvent: () => ClickEvent,
Button: () => Button_default,
Box: () => ThemedBox_default,
BaseText: () => Text,
BaseBox: () => Box_default,
Ansi: () => Ansi
});
function withTheme(node) {
return import_react24.createElement(ThemeProvider, null, node);
}
async function render(node, options) {
return root_default(withTheme(node), options);
}
async function createRoot2(options) {
const root2 = await createRoot(options);
return {
...root2,
render: (node) => root2.render(withTheme(node))
};
}
var import_react24;
var init_ink2 = __esm(() => {
init_ThemeProvider();
init_root();
init_color();
init_ThemedBox();
init_ThemedText();
init_ThemeProvider();
init_Ansi();
init_Box();
init_Button();
init_Link();
init_Newline();
init_NoSelect();
init_RawAnsi();
init_Spacer();
init_Text();
init_click_event();
init_emitter();
init_input_event();
init_terminal_focus_event();
init_focus();
init_use_animation_frame();
init_use_app();
init_use_input();
init_use_interval();
init_use_selection();
init_use_stdin();
init_use_tab_status();
init_use_terminal_focus();
init_use_terminal_title();
init_use_terminal_viewport();
init_measure_element();
init_osc();
init_wrap_text();
import_react24 = __toESM(require_react(), 1);
});
// src/hooks/useTerminalSize.ts
function useTerminalSize() {
const size = import_react25.useContext(TerminalSizeContext);
if (!size) {
throw new Error("useTerminalSize must be used within an Ink App component");
}
return size;
}
var import_react25;
var init_useTerminalSize = __esm(() => {
init_TerminalSizeContext();
import_react25 = __toESM(require_react(), 1);
});
// src/components/design-system/Ratchet.tsx
function Ratchet(t0) {
const $2 = c5(10);
const {
children,
lock: t1
} = t0;
const lock2 = t1 === undefined ? "always" : t1;
const [viewportRef, t2] = useTerminalViewport();
const {
isVisible
} = t2;
const {
rows
} = useTerminalSize();
const innerRef = import_react26.useRef(null);
const maxHeight = import_react26.useRef(0);
const [minHeight, setMinHeight] = import_react26.useState(0);
let t3;
if ($2[0] !== viewportRef) {
t3 = (el) => {
viewportRef(el);
};
$2[0] = viewportRef;
$2[1] = t3;
} else {
t3 = $2[1];
}
const outerRef = t3;
const engaged = lock2 === "always" || !isVisible;
let t4;
if ($2[2] !== rows) {
t4 = () => {
if (!innerRef.current) {
return;
}
const {
height
} = measure_element_default(innerRef.current);
if (height > maxHeight.current) {
maxHeight.current = Math.min(height, rows);
setMinHeight(maxHeight.current);
}
};
$2[2] = rows;
$2[3] = t4;
} else {
t4 = $2[3];
}
import_react26.useLayoutEffect(t4);
const t5 = engaged ? minHeight : undefined;
let t6;
if ($2[4] !== children) {
t6 = /* @__PURE__ */ jsx_dev_runtime18.jsxDEV(ThemedBox_default, {
ref: innerRef,
flexDirection: "column",
children
}, undefined, false, undefined, this);
$2[4] = children;
$2[5] = t6;
} else {
t6 = $2[5];
}
let t7;
if ($2[6] !== outerRef || $2[7] !== t5 || $2[8] !== t6) {
t7 = /* @__PURE__ */ jsx_dev_runtime18.jsxDEV(ThemedBox_default, {
minHeight: t5,
ref: outerRef,
children: t6
}, undefined, false, undefined, this);
$2[6] = outerRef;
$2[7] = t5;
$2[8] = t6;
$2[9] = t7;
} else {
t7 = $2[9];
}
return t7;
}
var import_react26, jsx_dev_runtime18;
var init_Ratchet = __esm(() => {
init_useTerminalSize();
init_use_terminal_viewport();
init_ink2();
import_react26 = __toESM(require_react(), 1);
jsx_dev_runtime18 = __toESM(require_jsx_dev_runtime(), 1);
});
// src/components/MessageResponse.tsx
function MessageResponse(t0) {
const $2 = c5(8);
const {
children,
height
} = t0;
const isMessageResponse = import_react27.useContext(MessageResponseContext);
if (isMessageResponse) {
return children;
}
let t1;
if ($2[0] === Symbol.for("react.memo_cache_sentinel")) {
t1 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(NoSelect, {
fromLeftEdge: true,
flexShrink: 0,
children: /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(ThemedText, {
dimColor: true,
children: [
" ",
"⎿ "
]
}, undefined, true, undefined, this)
}, undefined, false, undefined, this);
$2[0] = t1;
} else {
t1 = $2[0];
}
let t2;
if ($2[1] !== children) {
t2 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(ThemedBox_default, {
flexShrink: 1,
flexGrow: 1,
children
}, undefined, false, undefined, this);
$2[1] = children;
$2[2] = t2;
} else {
t2 = $2[2];
}
let t3;
if ($2[3] !== height || $2[4] !== t2) {
t3 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(MessageResponseProvider, {
children: /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(ThemedBox_default, {
flexDirection: "row",
height,
overflowY: "hidden",
children: [
t1,
t2
]
}, undefined, true, undefined, this)
}, undefined, false, undefined, this);
$2[3] = height;
$2[4] = t2;
$2[5] = t3;
} else {
t3 = $2[5];
}
const content = t3;
if (height !== undefined) {
return content;
}
let t4;
if ($2[6] !== content) {
t4 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(Ratchet, {
lock: "offscreen",
children: content
}, undefined, false, undefined, this);
$2[6] = content;
$2[7] = t4;
} else {
t4 = $2[7];
}
return t4;
}
function MessageResponseProvider(t0) {
const $2 = c5(2);
const {
children
} = t0;
let t1;
if ($2[0] !== children) {
t1 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(MessageResponseContext.Provider, {
value: true,
children
}, undefined, false, undefined, this);
$2[0] = children;
$2[1] = t1;
} else {
t1 = $2[1];
}
return t1;
}
var React9, import_react27, jsx_dev_runtime19, MessageResponseContext;
var init_MessageResponse = __esm(() => {
init_ink2();
init_Ratchet();
React9 = __toESM(require_react(), 1);
import_react27 = __toESM(require_react(), 1);
jsx_dev_runtime19 = __toESM(require_jsx_dev_runtime(), 1);
MessageResponseContext = React9.createContext(false);
});
// src/commands/add-dir/validation.ts
import { stat as stat8 } from "fs/promises";
import { dirname as dirname12, resolve as resolve9 } from "path";
async function validateDirectoryForWorkspace(directoryPath, permissionContext) {
if (!directoryPath) {
return {
resultType: "emptyPath"
};
}
const absolutePath = resolve9(expandPath(directoryPath));
try {
const stats = await stat8(absolutePath);
if (!stats.isDirectory()) {
return {
resultType: "notADirectory",
directoryPath,
absolutePath
};
}
} catch (e) {
const code = getErrnoCode(e);
if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "EPERM") {
return {
resultType: "pathNotFound",
directoryPath,
absolutePath
};
}
throw e;
}
const currentWorkingDirs = allWorkingDirectories(permissionContext);
for (const workingDir of currentWorkingDirs) {
if (pathInWorkingPath(absolutePath, workingDir)) {
return {
resultType: "alreadyInWorkingDirectory",
directoryPath,
workingDir
};
}
}
return {
resultType: "success",
absolutePath
};
}
function addDirHelpMessage(result) {
switch (result.resultType) {
case "emptyPath":
return "Please provide a directory path.";
case "pathNotFound":
return `Path ${source_default.bold(result.absolutePath)} was not found.`;
case "notADirectory": {
const parentDir = dirname12(result.absolutePath);
return `${source_default.bold(result.directoryPath)} is not a directory. Did you mean to add the parent directory ${source_default.bold(parentDir)}?`;
}
case "alreadyInWorkingDirectory":
return `${source_default.bold(result.directoryPath)} is already accessible within the existing working directory ${source_default.bold(result.workingDir)}.`;
case "success":
return `Added ${source_default.bold(result.absolutePath)} as a working directory.`;
}
}
var init_validation3 = __esm(() => {
init_source();
init_errors();
init_path2();
init_filesystem();
});
// src/state/store.ts
function createStore(initialState, onChange) {
let state = initialState;
const listeners = new Set;
return {
getState: () => state,
setState: (updater) => {
const prev = state;
const next = updater(prev);
if (Object.is(next, prev))
return;
state = next;
onChange?.({ newState: next, oldState: prev });
for (const listener of listeners)
listener();
},
subscribe: (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
}
};
}
// src/context/voice.tsx
var import_react28, jsx_dev_runtime20, VoiceContext;
var init_voice = __esm(() => {
import_react28 = __toESM(require_react(), 1);
jsx_dev_runtime20 = __toESM(require_jsx_dev_runtime(), 1);
VoiceContext = import_react28.createContext(null);
});
// src/utils/mailbox.ts
class Mailbox {
queue = [];
waiters = [];
changed = createSignal();
_revision = 0;
get length() {
return this.queue.length;
}
get revision() {
return this._revision;
}
send(msg) {
this._revision++;
const idx = this.waiters.findIndex((w) => w.fn(msg));
if (idx !== -1) {
const waiter = this.waiters.splice(idx, 1)[0];
if (waiter) {
waiter.resolve(msg);
this.notify();
return;
}
}
this.queue.push(msg);
this.notify();
}
poll(fn = () => true) {
const idx = this.queue.findIndex(fn);
if (idx === -1)
return;
return this.queue.splice(idx, 1)[0];
}
receive(fn = () => true) {
const idx = this.queue.findIndex(fn);
if (idx !== -1) {
const msg = this.queue.splice(idx, 1)[0];
if (msg) {
this.notify();
return Promise.resolve(msg);
}
}
return new Promise((resolve10) => {
this.waiters.push({ fn, resolve: resolve10 });
});
}
subscribe = this.changed.subscribe;
notify() {
this.changed.emit();
}
}
var init_mailbox = () => {};
// src/context/mailbox.tsx
function MailboxProvider(t0) {
const $2 = c5(3);
const {
children
} = t0;
let t1;
if ($2[0] === Symbol.for("react.memo_cache_sentinel")) {
t1 = new Mailbox;
$2[0] = t1;
} else {
t1 = $2[0];
}
const mailbox = t1;
let t2;
if ($2[1] !== children) {
t2 = /* @__PURE__ */ jsx_dev_runtime21.jsxDEV(MailboxContext.Provider, {
value: mailbox,
children
}, undefined, false, undefined, this);
$2[1] = children;
$2[2] = t2;
} else {
t2 = $2[2];
}
return t2;
}
function useMailbox() {
const mailbox = import_react29.useContext(MailboxContext);
if (!mailbox) {
throw new Error("useMailbox must be used within a MailboxProvider");
}
return mailbox;
}
var import_react29, jsx_dev_runtime21, MailboxContext;
var init_mailbox2 = __esm(() => {
init_mailbox();
import_react29 = __toESM(require_react(), 1);
jsx_dev_runtime21 = __toESM(require_jsx_dev_runtime(), 1);
MailboxContext = import_react29.createContext(undefined);
});
// node_modules/readdirp/esm/index.js
import { stat as stat9, lstat, readdir as readdir4, realpath as realpath4 } from "node:fs/promises";
import { Readable as Readable5 } from "node:stream";
import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "node:path";
function readdirp(root2, options = {}) {
let type = options.entryType || options.type;
if (type === "both")
type = EntryTypes.FILE_DIR_TYPE;
if (type)
options.type = type;
if (!root2) {
throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
} else if (typeof root2 !== "string") {
throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
} else if (type && !ALL_TYPES.includes(type)) {
throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
}
options.root = root2;
return new ReaddirpStream(options);
}
var EntryTypes, defaultOptions, RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR", NORMAL_FLOW_ERRORS, ALL_TYPES, DIR_TYPES, FILE_TYPES2, isNormalFlowError = (error44) => NORMAL_FLOW_ERRORS.has(error44.code), wantBigintFsStats, emptyFn = (_entryInfo) => true, normalizeFilter = (filter2) => {
if (filter2 === undefined)
return emptyFn;
if (typeof filter2 === "function")
return filter2;
if (typeof filter2 === "string") {
const fl = filter2.trim();
return (entry) => entry.basename === fl;
}
if (Array.isArray(filter2)) {
const trItems = filter2.map((item) => item.trim());
return (entry) => trItems.some((f) => entry.basename === f);
}
return emptyFn;
}, ReaddirpStream;
var init_esm2 = __esm(() => {
EntryTypes = {
FILE_TYPE: "files",
DIR_TYPE: "directories",
FILE_DIR_TYPE: "files_directories",
EVERYTHING_TYPE: "all"
};
defaultOptions = {
root: ".",
fileFilter: (_entryInfo) => true,
directoryFilter: (_entryInfo) => true,
type: EntryTypes.FILE_TYPE,
lstat: false,
depth: 2147483648,
alwaysStat: false,
highWaterMark: 4096
};
Object.freeze(defaultOptions);
NORMAL_FLOW_ERRORS = new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
ALL_TYPES = [
EntryTypes.DIR_TYPE,
EntryTypes.EVERYTHING_TYPE,
EntryTypes.FILE_DIR_TYPE,
EntryTypes.FILE_TYPE
];
DIR_TYPES = new Set([
EntryTypes.DIR_TYPE,
EntryTypes.EVERYTHING_TYPE,
EntryTypes.FILE_DIR_TYPE
]);
FILE_TYPES2 = new Set([
EntryTypes.EVERYTHING_TYPE,
EntryTypes.FILE_DIR_TYPE,
EntryTypes.FILE_TYPE
]);
wantBigintFsStats = process.platform === "win32";
ReaddirpStream = class ReaddirpStream extends Readable5 {
constructor(options = {}) {
super({
objectMode: true,
autoDestroy: true,
highWaterMark: options.highWaterMark
});
const opts = { ...defaultOptions, ...options };
const { root: root2, type } = opts;
this._fileFilter = normalizeFilter(opts.fileFilter);
this._directoryFilter = normalizeFilter(opts.directoryFilter);
const statMethod = opts.lstat ? lstat : stat9;
if (wantBigintFsStats) {
this._stat = (path10) => statMethod(path10, { bigint: true });
} else {
this._stat = statMethod;
}
this._maxDepth = opts.depth ?? defaultOptions.depth;
this._wantsDir = type ? DIR_TYPES.has(type) : false;
this._wantsFile = type ? FILE_TYPES2.has(type) : false;
this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
this._root = presolve(root2);
this._isDirent = !opts.alwaysStat;
this._statsProp = this._isDirent ? "dirent" : "stats";
this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
this.parents = [this._exploreDir(root2, 1)];
this.reading = false;
this.parent = undefined;
}
async _read(batch) {
if (this.reading)
return;
this.reading = true;
try {
while (!this.destroyed && batch > 0) {
const par = this.parent;
const fil = par && par.files;
if (fil && fil.length > 0) {
const { path: path10, depth } = par;
const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path10));
const awaited = await Promise.all(slice);
for (const entry of awaited) {
if (!entry)
continue;
if (this.destroyed)
return;
const entryType = await this._getEntryType(entry);
if (entryType === "directory" && this._directoryFilter(entry)) {
if (depth <= this._maxDepth) {
this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
}
if (this._wantsDir) {
this.push(entry);
batch--;
}
} else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
if (this._wantsFile) {
this.push(entry);
batch--;
}
}
}
} else {
const parent = this.parents.pop();
if (!parent) {
this.push(null);
break;
}
this.parent = await parent;
if (this.destroyed)
return;
}
}
} catch (error44) {
this.destroy(error44);
} finally {
this.reading = false;
}
}
async _exploreDir(path10, depth) {
let files;
try {
files = await readdir4(path10, this._rdOptions);
} catch (error44) {
this._onError(error44);
}
return { files, depth, path: path10 };
}
async _formatEntry(dirent, path10) {
let entry;
const basename5 = this._isDirent ? dirent.name : dirent;
try {
const fullPath = presolve(pjoin(path10, basename5));
entry = { path: prelative(this._root, fullPath), fullPath, basename: basename5 };
entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
} catch (err) {
this._onError(err);
return;
}
return entry;
}
_onError(err) {
if (isNormalFlowError(err) && !this.destroyed) {
this.emit("warn", err);
} else {
this.destroy(err);
}
}
async _getEntryType(entry) {
if (!entry && this._statsProp in entry) {
return "";
}
const stats = entry[this._statsProp];
if (stats.isFile())
return "file";
if (stats.isDirectory())
return "directory";
if (stats && stats.isSymbolicLink()) {
const full = entry.fullPath;
try {
const entryRealPath = await realpath4(full);
const entryRealPathStats = await lstat(entryRealPath);
if (entryRealPathStats.isFile()) {
return "file";
}
if (entryRealPathStats.isDirectory()) {
const len = entryRealPath.length;
if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
recursiveError.code = RECURSIVE_ERROR_CODE;
return this._onError(recursiveError);
}
return "directory";
}
} catch (error44) {
this._onError(error44);
return "";
}
}
}
_includeAsFile(entry) {
const stats = entry && entry[this._statsProp];
return stats && this._wantsEverything && !stats.isDirectory();
}
};
});
// node_modules/chokidar/esm/handler.js
import { watchFile as watchFile3, unwatchFile as unwatchFile3, watch as fs_watch } from "fs";
import { open as open4, stat as stat10, lstat as lstat2, realpath as fsrealpath } from "fs/promises";
import * as sysPath from "path";
import { type as osType } from "os";
function createFsWatchInstance(path10, options, listener, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener(path10);
emitRaw(rawEvent, evPath, { watchedPath: path10 });
if (evPath && path10 !== evPath) {
fsWatchBroadcast(sysPath.resolve(path10, evPath), KEY_LISTENERS, sysPath.join(path10, evPath));
}
};
try {
return fs_watch(path10, {
persistent: options.persistent
}, handleEvent);
} catch (error44) {
errHandler(error44);
return;
}
}
class NodeFsHandler {
constructor(fsW) {
this.fsw = fsW;
this._boundHandleError = (error44) => fsW._handleError(error44);
}
_watchWithNodeFs(path10, listener) {
const opts = this.fsw.options;
const directory = sysPath.dirname(path10);
const basename6 = sysPath.basename(path10);
const parent = this.fsw._getWatchedDir(directory);
parent.add(basename6);
const absolutePath = sysPath.resolve(path10);
const options = {
persistent: opts.persistent
};
if (!listener)
listener = EMPTY_FN;
let closer;
if (opts.usePolling) {
const enableBin = opts.interval !== opts.binaryInterval;
options.interval = enableBin && isBinaryPath(basename6) ? opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path10, absolutePath, options, {
listener,
rawEmitter: this.fsw._emitRaw
});
} else {
closer = setFsWatchListener(path10, absolutePath, options, {
listener,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw
});
}
return closer;
}
_handleFile(file2, stats, initialAdd) {
if (this.fsw.closed) {
return;
}
const dirname14 = sysPath.dirname(file2);
const basename6 = sysPath.basename(file2);
const parent = this.fsw._getWatchedDir(dirname14);
let prevStats = stats;
if (parent.has(basename6))
return;
const listener = async (path10, newStats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
return;
if (!newStats || newStats.mtimeMs === 0) {
try {
const newStats2 = await stat10(file2);
if (this.fsw.closed)
return;
const at = newStats2.atimeMs;
const mt = newStats2.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV.CHANGE, file2, newStats2);
}
if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
this.fsw._closeFile(path10);
prevStats = newStats2;
const closer2 = this._watchWithNodeFs(file2, listener);
if (closer2)
this.fsw._addPathCloser(path10, closer2);
} else {
prevStats = newStats2;
}
} catch (error44) {
this.fsw._remove(dirname14, basename6);
}
} else if (parent.has(basename6)) {
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV.CHANGE, file2, newStats);
}
prevStats = newStats;
}
};
const closer = this._watchWithNodeFs(file2, listener);
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
if (!this.fsw._throttle(EV.ADD, file2, 0))
return;
this.fsw._emit(EV.ADD, file2, stats);
}
return closer;
}
async _handleSymlink(entry, directory, path10, item) {
if (this.fsw.closed) {
return;
}
const full = entry.fullPath;
const dir = this.fsw._getWatchedDir(directory);
if (!this.fsw.options.followSymlinks) {
this.fsw._incrReadyCount();
let linkPath;
try {
linkPath = await fsrealpath(path10);
} catch (e) {
this.fsw._emitReady();
return true;
}
if (this.fsw.closed)
return;
if (dir.has(item)) {
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV.CHANGE, path10, entry.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV.ADD, path10, entry.stats);
}
this.fsw._emitReady();
return true;
}
if (this.fsw._symlinkPaths.has(full)) {
return true;
}
this.fsw._symlinkPaths.set(full, true);
}
_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
directory = sysPath.join(directory, "");
throttler = this.fsw._throttle("readdir", directory, 1000);
if (!throttler)
return;
const previous = this.fsw._getWatchedDir(wh.path);
const current = new Set;
let stream4 = this.fsw._readdirp(directory, {
fileFilter: (entry) => wh.filterPath(entry),
directoryFilter: (entry) => wh.filterDir(entry)
});
if (!stream4)
return;
stream4.on(STR_DATA, async (entry) => {
if (this.fsw.closed) {
stream4 = undefined;
return;
}
const item = entry.path;
let path10 = sysPath.join(directory, item);
current.add(item);
if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path10, item)) {
return;
}
if (this.fsw.closed) {
stream4 = undefined;
return;
}
if (item === target || !target && !previous.has(item)) {
this.fsw._incrReadyCount();
path10 = sysPath.join(dir, sysPath.relative(dir, path10));
this._addToNodeFs(path10, initialAdd, wh, depth + 1);
}
}).on(EV.ERROR, this._boundHandleError);
return new Promise((resolve11, reject) => {
if (!stream4)
return reject();
stream4.once(STR_END, () => {
if (this.fsw.closed) {
stream4 = undefined;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve11(undefined);
previous.getChildren().filter((item) => {
return item !== directory && !current.has(item);
}).forEach((item) => {
this.fsw._remove(directory, item);
});
stream4 = undefined;
if (wasThrottled)
this._handleRead(directory, false, wh, target, dir, depth, throttler);
});
});
}
async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath5) {
const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
const tracked = parentDir.has(sysPath.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
this.fsw._emit(EV.ADD_DIR, dir, stats);
}
parentDir.add(sysPath.basename(dir));
this.fsw._getWatchedDir(dir);
let throttler;
let closer;
const oDepth = this.fsw.options.depth;
if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath5)) {
if (!target) {
await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
if (this.fsw.closed)
return;
}
closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
if (stats2 && stats2.mtimeMs === 0)
return;
this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
});
}
return closer;
}
async _addToNodeFs(path10, initialAdd, priorWh, depth, target) {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path10) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path10);
if (priorWh) {
wh.filterPath = (entry) => priorWh.filterPath(entry);
wh.filterDir = (entry) => priorWh.filterDir(entry);
}
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed)
return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
ready();
return false;
}
const follow = this.fsw.options.followSymlinks;
let closer;
if (stats.isDirectory()) {
const absPath = sysPath.resolve(path10);
const targetPath = follow ? await fsrealpath(path10) : path10;
if (this.fsw.closed)
return;
closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
if (this.fsw.closed)
return;
if (absPath !== targetPath && targetPath !== undefined) {
this.fsw._symlinkPaths.set(absPath, targetPath);
}
} else if (stats.isSymbolicLink()) {
const targetPath = follow ? await fsrealpath(path10) : path10;
if (this.fsw.closed)
return;
const parent = sysPath.dirname(wh.watchPath);
this.fsw._getWatchedDir(parent).add(wh.watchPath);
this.fsw._emit(EV.ADD, wh.watchPath, stats);
closer = await this._handleDir(parent, stats, initialAdd, depth, path10, wh, targetPath);
if (this.fsw.closed)
return;
if (targetPath !== undefined) {
this.fsw._symlinkPaths.set(sysPath.resolve(path10), targetPath);
}
} else {
closer = this._handleFile(wh.watchPath, stats, initialAdd);
}
ready();
if (closer)
this.fsw._addPathCloser(path10, closer);
return false;
} catch (error44) {
if (this.fsw._handleError(error44)) {
ready();
return path10;
}
}
}
}
var STR_DATA = "data", STR_END = "end", STR_CLOSE = "close", EMPTY_FN = () => {}, pl, isWindows, isMacos, isLinux, isFreeBSD, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH = "watch", statMethods, KEY_LISTENERS = "listeners", KEY_ERR = "errHandlers", KEY_RAW = "rawEmitters", HANDLER_KEYS, binaryExtensions, isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()), foreach = (val, fn) => {
if (val instanceof Set) {
val.forEach(fn);
} else {
fn(val);
}
}, addAndConvert = (main, prop, item) => {
let container = main[prop];
if (!(container instanceof Set)) {
main[prop] = container = new Set([container]);
}
container.add(item);
}, clearItem = (cont) => (key) => {
const set2 = cont[key];
if (set2 instanceof Set) {
set2.clear();
} else {
delete cont[key];
}
}, delFromSet = (main, prop, item) => {
const container = main[prop];
if (container instanceof Set) {
container.delete(item);
} else if (container === item) {
delete main[prop];
}
}, isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val, FsWatchInstances, fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont)
return;
foreach(cont[listenerType], (listener) => {
listener(val1, val2, val3);
});
}, setFsWatchListener = (path10, fullPath, options, handlers) => {
const { listener, errHandler, rawEmitter } = handlers;
let cont = FsWatchInstances.get(fullPath);
let watcher;
if (!options.persistent) {
watcher = createFsWatchInstance(path10, options, listener, errHandler, rawEmitter);
if (!watcher)
return;
return watcher.close.bind(watcher);
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_ERR, errHandler);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
watcher = createFsWatchInstance(path10, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
if (!watcher)
return;
watcher.on(EV.ERROR, async (error44) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
if (cont)
cont.watcherUnusable = true;
if (isWindows && error44.code === "EPERM") {
try {
const fd = await open4(path10, "r");
await fd.close();
broadcastErr(error44);
} catch (err) {}
} else {
broadcastErr(error44);
}
});
cont = {
listeners: listener,
errHandlers: errHandler,
rawEmitters: rawEmitter,
watcher
};
FsWatchInstances.set(fullPath, cont);
}
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_ERR, errHandler);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
cont.watcher.close();
FsWatchInstances.delete(fullPath);
HANDLER_KEYS.forEach(clearItem(cont));
cont.watcher = undefined;
Object.freeze(cont);
}
};
}, FsWatchFileInstances, setFsWatchFileListener = (path10, fullPath, options, handlers) => {
const { listener, rawEmitter } = handlers;
let cont = FsWatchFileInstances.get(fullPath);
const copts = cont && cont.options;
if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
unwatchFile3(fullPath);
cont = undefined;
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
cont = {
listeners: listener,
rawEmitters: rawEmitter,
options,
watcher: watchFile3(fullPath, options, (curr, prev) => {
foreach(cont.rawEmitters, (rawEmitter2) => {
rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
});
const currmtime = curr.mtimeMs;
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
foreach(cont.listeners, (listener2) => listener2(path10, curr));
}
})
};
FsWatchFileInstances.set(fullPath, cont);
}
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
unwatchFile3(fullPath);
cont.options = cont.watcher = undefined;
Object.freeze(cont);
}
};
};
var init_handler = __esm(() => {
pl = process.platform;
isWindows = pl === "win32";
isMacos = pl === "darwin";
isLinux = pl === "linux";
isFreeBSD = pl === "freebsd";
isIBMi = osType() === "OS400";
EVENTS = {
ALL: "all",
READY: "ready",
ADD: "add",
CHANGE: "change",
ADD_DIR: "addDir",
UNLINK: "unlink",
UNLINK_DIR: "unlinkDir",
RAW: "raw",
ERROR: "error"
};
EV = EVENTS;
statMethods = { lstat: lstat2, stat: stat10 };
HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
binaryExtensions = new Set([
"3dm",
"3ds",
"3g2",
"3gp",
"7z",
"a",
"aac",
"adp",
"afdesign",
"afphoto",
"afpub",
"ai",
"aif",
"aiff",
"alz",
"ape",
"apk",
"appimage",
"ar",
"arj",
"asf",
"au",
"avi",
"bak",
"baml",
"bh",
"bin",
"bk",
"bmp",
"btif",
"bz2",
"bzip2",
"cab",
"caf",
"cgm",
"class",
"cmx",
"cpio",
"cr2",
"cur",
"dat",
"dcm",
"deb",
"dex",
"djvu",
"dll",
"dmg",
"dng",
"doc",
"docm",
"docx",
"dot",
"dotm",
"dra",
"DS_Store",
"dsk",
"dts",
"dtshd",
"dvb",
"dwg",
"dxf",
"ecelp4800",
"ecelp7470",
"ecelp9600",
"egg",
"eol",
"eot",
"epub",
"exe",
"f4v",
"fbs",
"fh",
"fla",
"flac",
"flatpak",
"fli",
"flv",
"fpx",
"fst",
"fvt",
"g3",
"gh",
"gif",
"graffle",
"gz",
"gzip",
"h261",
"h263",
"h264",
"icns",
"ico",
"ief",
"img",
"ipa",
"iso",
"jar",
"jpeg",
"jpg",
"jpgv",
"jpm",
"jxr",
"key",
"ktx",
"lha",
"lib",
"lvp",
"lz",
"lzh",
"lzma",
"lzo",
"m3u",
"m4a",
"m4v",
"mar",
"mdi",
"mht",
"mid",
"midi",
"mj2",
"mka",
"mkv",
"mmr",
"mng",
"mobi",
"mov",
"movie",
"mp3",
"mp4",
"mp4a",
"mpeg",
"mpg",
"mpga",
"mxu",
"nef",
"npx",
"numbers",
"nupkg",
"o",
"odp",
"ods",
"odt",
"oga",
"ogg",
"ogv",
"otf",
"ott",
"pages",
"pbm",
"pcx",
"pdb",
"pdf",
"pea",
"pgm",
"pic",
"png",
"pnm",
"pot",
"potm",
"potx",
"ppa",
"ppam",
"ppm",
"pps",
"ppsm",
"ppsx",
"ppt",
"pptm",
"pptx",
"psd",
"pya",
"pyc",
"pyo",
"pyv",
"qt",
"rar",
"ras",
"raw",
"resources",
"rgb",
"rip",
"rlc",
"rmf",
"rmvb",
"rpm",
"rtf",
"rz",
"s3m",
"s7z",
"scpt",
"sgi",
"shar",
"snap",
"sil",
"sketch",
"slk",
"smv",
"snk",
"so",
"stl",
"suo",
"sub",
"swf",
"tar",
"tbz",
"tbz2",
"tga",
"tgz",
"thmx",
"tif",
"tiff",
"tlz",
"ttc",
"ttf",
"txz",
"udf",
"uvh",
"uvi",
"uvm",
"uvp",
"uvs",
"uvu",
"viv",
"vob",
"war",
"wav",
"wax",
"wbmp",
"wdp",
"weba",
"webm",
"webp",
"whl",
"wim",
"wm",
"wma",
"wmv",
"wmx",
"woff",
"woff2",
"wrm",
"wvx",
"xbm",
"xif",
"xla",
"xlam",
"xls",
"xlsb",
"xlsm",
"xlsx",
"xlt",
"xltm",
"xltx",
"xm",
"xmind",
"xpi",
"xpm",
"xwd",
"xz",
"z",
"zip",
"zipx"
]);
FsWatchInstances = new Map;
FsWatchFileInstances = new Map;
});
// node_modules/chokidar/esm/index.js
import { stat as statcb } from "fs";
import { stat as stat11, readdir as readdir5 } from "fs/promises";
import { EventEmitter as EventEmitter4 } from "events";
import * as sysPath2 from "path";
function arrify(item) {
return Array.isArray(item) ? item : [item];
}
function createPattern(matcher) {
if (typeof matcher === "function")
return matcher;
if (typeof matcher === "string")
return (string4) => matcher === string4;
if (matcher instanceof RegExp)
return (string4) => matcher.test(string4);
if (typeof matcher === "object" && matcher !== null) {
return (string4) => {
if (matcher.path === string4)
return true;
if (matcher.recursive) {
const relative5 = sysPath2.relative(matcher.path, string4);
if (!relative5) {
return false;
}
return !relative5.startsWith("..") && !sysPath2.isAbsolute(relative5);
}
return false;
};
}
return () => false;
}
function normalizePath(path10) {
if (typeof path10 !== "string")
throw new Error("string expected");
path10 = sysPath2.normalize(path10);
path10 = path10.replace(/\\/g, "/");
let prepend = false;
if (path10.startsWith("//"))
prepend = true;
const DOUBLE_SLASH_RE2 = /\/\//;
while (path10.match(DOUBLE_SLASH_RE2))
path10 = path10.replace(DOUBLE_SLASH_RE2, "/");
if (prepend)
path10 = "/" + path10;
return path10;
}
function matchPatterns(patterns, testString, stats) {
const path10 = normalizePath(testString);
for (let index = 0;index < patterns.length; index++) {
const pattern = patterns[index];
if (pattern(path10, stats)) {
return true;
}
}
return false;
}
function anymatch(matchers, testString) {
if (matchers == null) {
throw new TypeError("anymatch: specify first argument");
}
const matchersArray = arrify(matchers);
const patterns = matchersArray.map((matcher) => createPattern(matcher));
if (testString == null) {
return (testString2, stats) => {
return matchPatterns(patterns, testString2, stats);
};
}
return matchPatterns(patterns, testString);
}
class DirEntry {
constructor(dir, removeWatcher) {
this.path = dir;
this._removeWatcher = removeWatcher;
this.items = new Set;
}
add(item) {
const { items } = this;
if (!items)
return;
if (item !== ONE_DOT && item !== TWO_DOTS)
items.add(item);
}
async remove(item) {
const { items } = this;
if (!items)
return;
items.delete(item);
if (items.size > 0)
return;
const dir = this.path;
try {
await readdir5(dir);
} catch (err) {
if (this._removeWatcher) {
this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
}
}
}
has(item) {
const { items } = this;
if (!items)
return;
return items.has(item);
}
getChildren() {
const { items } = this;
if (!items)
return [];
return [...items.values()];
}
dispose() {
this.items.clear();
this.path = "";
this._removeWatcher = EMPTY_FN;
this.items = EMPTY_SET;
Object.freeze(this);
}
}
class WatchHelper {
constructor(path10, follow, fsw) {
this.fsw = fsw;
const watchPath = path10;
this.path = path10 = path10.replace(REPLACER_RE, "");
this.watchPath = watchPath;
this.fullWatchPath = sysPath2.resolve(watchPath);
this.dirParts = [];
this.dirParts.forEach((parts) => {
if (parts.length > 1)
parts.pop();
});
this.followSymlinks = follow;
this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
}
entryPath(entry) {
return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
}
filterPath(entry) {
const { stats } = entry;
if (stats && stats.isSymbolicLink())
return this.filterDir(entry);
const resolvedPath = this.entryPath(entry);
return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
}
filterDir(entry) {
return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
}
}
function watch(paths2, options = {}) {
const watcher = new FSWatcher(options);
watcher.add(paths2);
return watcher;
}
var SLASH = "/", SLASH_SLASH = "//", ONE_DOT = ".", TWO_DOTS = "..", STRING_TYPE = "string", BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp), unifyPaths = (paths_) => {
const paths2 = arrify(paths_).flat();
if (!paths2.every((p) => typeof p === STRING_TYPE)) {
throw new TypeError(`Non-string provided as watch path: ${paths2}`);
}
return paths2.map(normalizePathToUnix);
}, toUnix = (string4) => {
let str = string4.replace(BACK_SLASH_RE, SLASH);
let prepend = false;
if (str.startsWith(SLASH_SLASH)) {
prepend = true;
}
while (str.match(DOUBLE_SLASH_RE)) {
str = str.replace(DOUBLE_SLASH_RE, SLASH);
}
if (prepend) {
str = SLASH + str;
}
return str;
}, normalizePathToUnix = (path10) => toUnix(sysPath2.normalize(toUnix(path10))), normalizeIgnored = (cwd2 = "") => (path10) => {
if (typeof path10 === "string") {
return normalizePathToUnix(sysPath2.isAbsolute(path10) ? path10 : sysPath2.join(cwd2, path10));
} else {
return path10;
}
}, getAbsolutePath = (path10, cwd2) => {
if (sysPath2.isAbsolute(path10)) {
return path10;
}
return sysPath2.join(cwd2, path10);
}, EMPTY_SET, STAT_METHOD_F = "stat", STAT_METHOD_L = "lstat", FSWatcher, esm_default;
var init_esm3 = __esm(() => {
init_esm2();
init_handler();
/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
BACK_SLASH_RE = /\\/g;
DOUBLE_SLASH_RE = /\/\//;
DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
REPLACER_RE = /^\.[/\\]/;
EMPTY_SET = Object.freeze(new Set);
FSWatcher = class FSWatcher extends EventEmitter4 {
constructor(_opts = {}) {
super();
this.closed = false;
this._closers = new Map;
this._ignoredPaths = new Set;
this._throttled = new Map;
this._streams = new Set;
this._symlinkPaths = new Map;
this._watched = new Map;
this._pendingWrites = new Map;
this._pendingUnlinks = new Map;
this._readyCount = 0;
this._readyEmitted = false;
const awf = _opts.awaitWriteFinish;
const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };
const opts = {
persistent: true,
ignoreInitial: false,
ignorePermissionErrors: false,
interval: 100,
binaryInterval: 300,
followSymlinks: true,
usePolling: false,
atomic: true,
..._opts,
ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
};
if (isIBMi)
opts.usePolling = true;
if (opts.atomic === undefined)
opts.atomic = !opts.usePolling;
const envPoll = process.env.CHOKIDAR_USEPOLLING;
if (envPoll !== undefined) {
const envLower = envPoll.toLowerCase();
if (envLower === "false" || envLower === "0")
opts.usePolling = false;
else if (envLower === "true" || envLower === "1")
opts.usePolling = true;
else
opts.usePolling = !!envLower;
}
const envInterval = process.env.CHOKIDAR_INTERVAL;
if (envInterval)
opts.interval = Number.parseInt(envInterval, 10);
let readyCalls = 0;
this._emitReady = () => {
readyCalls++;
if (readyCalls >= this._readyCount) {
this._emitReady = EMPTY_FN;
this._readyEmitted = true;
process.nextTick(() => this.emit(EVENTS.READY));
}
};
this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
this._boundRemove = this._remove.bind(this);
this.options = opts;
this._nodeFsHandler = new NodeFsHandler(this);
Object.freeze(opts);
}
_addIgnoredPath(matcher) {
if (isMatcherObject(matcher)) {
for (const ignored of this._ignoredPaths) {
if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
return;
}
}
}
this._ignoredPaths.add(matcher);
}
_removeIgnoredPath(matcher) {
this._ignoredPaths.delete(matcher);
if (typeof matcher === "string") {
for (const ignored of this._ignoredPaths) {
if (isMatcherObject(ignored) && ignored.path === matcher) {
this._ignoredPaths.delete(ignored);
}
}
}
}
add(paths_, _origAdd, _internal) {
const { cwd: cwd2 } = this.options;
this.closed = false;
this._closePromise = undefined;
let paths2 = unifyPaths(paths_);
if (cwd2) {
paths2 = paths2.map((path10) => {
const absPath = getAbsolutePath(path10, cwd2);
return absPath;
});
}
paths2.forEach((path10) => {
this._removeIgnoredPath(path10);
});
this._userIgnored = undefined;
if (!this._readyCount)
this._readyCount = 0;
this._readyCount += paths2.length;
Promise.all(paths2.map(async (path10) => {
const res = await this._nodeFsHandler._addToNodeFs(path10, !_internal, undefined, 0, _origAdd);
if (res)
this._emitReady();
return res;
})).then((results) => {
if (this.closed)
return;
results.forEach((item) => {
if (item)
this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
});
});
return this;
}
unwatch(paths_) {
if (this.closed)
return this;
const paths2 = unifyPaths(paths_);
const { cwd: cwd2 } = this.options;
paths2.forEach((path10) => {
if (!sysPath2.isAbsolute(path10) && !this._closers.has(path10)) {
if (cwd2)
path10 = sysPath2.join(cwd2, path10);
path10 = sysPath2.resolve(path10);
}
this._closePath(path10);
this._addIgnoredPath(path10);
if (this._watched.has(path10)) {
this._addIgnoredPath({
path: path10,
recursive: true
});
}
this._userIgnored = undefined;
});
return this;
}
close() {
if (this._closePromise) {
return this._closePromise;
}
this.closed = true;
this.removeAllListeners();
const closers = [];
this._closers.forEach((closerList) => closerList.forEach((closer) => {
const promise2 = closer();
if (promise2 instanceof Promise)
closers.push(promise2);
}));
this._streams.forEach((stream4) => stream4.destroy());
this._userIgnored = undefined;
this._readyCount = 0;
this._readyEmitted = false;
this._watched.forEach((dirent) => dirent.dispose());
this._closers.clear();
this._watched.clear();
this._streams.clear();
this._symlinkPaths.clear();
this._throttled.clear();
this._closePromise = closers.length ? Promise.all(closers).then(() => {
return;
}) : Promise.resolve();
return this._closePromise;
}
getWatched() {
const watchList = {};
this._watched.forEach((entry, dir) => {
const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
const index = key || ONE_DOT;
watchList[index] = entry.getChildren().sort();
});
return watchList;
}
emitWithAll(event, args) {
this.emit(event, ...args);
if (event !== EVENTS.ERROR)
this.emit(EVENTS.ALL, event, ...args);
}
async _emit(event, path10, stats) {
if (this.closed)
return;
const opts = this.options;
if (isWindows)
path10 = sysPath2.normalize(path10);
if (opts.cwd)
path10 = sysPath2.relative(opts.cwd, path10);
const args = [path10];
if (stats != null)
args.push(stats);
const awf = opts.awaitWriteFinish;
let pw;
if (awf && (pw = this._pendingWrites.get(path10))) {
pw.lastChange = new Date;
return this;
}
if (opts.atomic) {
if (event === EVENTS.UNLINK) {
this._pendingUnlinks.set(path10, [event, ...args]);
setTimeout(() => {
this._pendingUnlinks.forEach((entry, path11) => {
this.emit(...entry);
this.emit(EVENTS.ALL, ...entry);
this._pendingUnlinks.delete(path11);
});
}, typeof opts.atomic === "number" ? opts.atomic : 100);
return this;
}
if (event === EVENTS.ADD && this._pendingUnlinks.has(path10)) {
event = EVENTS.CHANGE;
this._pendingUnlinks.delete(path10);
}
}
if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
const awfEmit = (err, stats2) => {
if (err) {
event = EVENTS.ERROR;
args[0] = err;
this.emitWithAll(event, args);
} else if (stats2) {
if (args.length > 1) {
args[1] = stats2;
} else {
args.push(stats2);
}
this.emitWithAll(event, args);
}
};
this._awaitWriteFinish(path10, awf.stabilityThreshold, event, awfEmit);
return this;
}
if (event === EVENTS.CHANGE) {
const isThrottled = !this._throttle(EVENTS.CHANGE, path10, 50);
if (isThrottled)
return this;
}
if (opts.alwaysStat && stats === undefined && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path10) : path10;
let stats2;
try {
stats2 = await stat11(fullPath);
} catch (err) {}
if (!stats2 || this.closed)
return;
args.push(stats2);
}
this.emitWithAll(event, args);
return this;
}
_handleError(error44) {
const code = error44 && error44.code;
if (error44 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
this.emit(EVENTS.ERROR, error44);
}
return error44 || this.closed;
}
_throttle(actionType, path10, timeout) {
if (!this._throttled.has(actionType)) {
this._throttled.set(actionType, new Map);
}
const action = this._throttled.get(actionType);
if (!action)
throw new Error("invalid throttle");
const actionPath = action.get(path10);
if (actionPath) {
actionPath.count++;
return false;
}
let timeoutObject;
const clear = () => {
const item = action.get(path10);
const count3 = item ? item.count : 0;
action.delete(path10);
clearTimeout(timeoutObject);
if (item)
clearTimeout(item.timeoutObject);
return count3;
};
timeoutObject = setTimeout(clear, timeout);
const thr = { timeoutObject, clear, count: 0 };
action.set(path10, thr);
return thr;
}
_incrReadyCount() {
return this._readyCount++;
}
_awaitWriteFinish(path10, threshold, event, awfEmit) {
const awf = this.options.awaitWriteFinish;
if (typeof awf !== "object")
return;
const pollInterval = awf.pollInterval;
let timeoutHandler;
let fullPath = path10;
if (this.options.cwd && !sysPath2.isAbsolute(path10)) {
fullPath = sysPath2.join(this.options.cwd, path10);
}
const now2 = new Date;
const writes = this._pendingWrites;
function awaitWriteFinishFn(prevStat) {
statcb(fullPath, (err, curStat) => {
if (err || !writes.has(path10)) {
if (err && err.code !== "ENOENT")
awfEmit(err);
return;
}
const now3 = Number(new Date);
if (prevStat && curStat.size !== prevStat.size) {
writes.get(path10).lastChange = now3;
}
const pw = writes.get(path10);
const df = now3 - pw.lastChange;
if (df >= threshold) {
writes.delete(path10);
awfEmit(undefined, curStat);
} else {
timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
}
});
}
if (!writes.has(path10)) {
writes.set(path10, {
lastChange: now2,
cancelWait: () => {
writes.delete(path10);
clearTimeout(timeoutHandler);
return event;
}
});
timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
}
}
_isIgnored(path10, stats) {
if (this.options.atomic && DOT_RE.test(path10))
return true;
if (!this._userIgnored) {
const { cwd: cwd2 } = this.options;
const ign = this.options.ignored;
const ignored = (ign || []).map(normalizeIgnored(cwd2));
const ignoredPaths = [...this._ignoredPaths];
const list = [...ignoredPaths.map(normalizeIgnored(cwd2)), ...ignored];
this._userIgnored = anymatch(list, undefined);
}
return this._userIgnored(path10, stats);
}
_isntIgnored(path10, stat12) {
return !this._isIgnored(path10, stat12);
}
_getWatchHelpers(path10) {
return new WatchHelper(path10, this.options.followSymlinks, this);
}
_getWatchedDir(directory) {
const dir = sysPath2.resolve(directory);
if (!this._watched.has(dir))
this._watched.set(dir, new DirEntry(dir, this._boundRemove));
return this._watched.get(dir);
}
_hasReadPermissions(stats) {
if (this.options.ignorePermissionErrors)
return true;
return Boolean(Number(stats.mode) & 256);
}
_remove(directory, item, isDirectory) {
const path10 = sysPath2.join(directory, item);
const fullPath = sysPath2.resolve(path10);
isDirectory = isDirectory != null ? isDirectory : this._watched.has(path10) || this._watched.has(fullPath);
if (!this._throttle("remove", path10, 100))
return;
if (!isDirectory && this._watched.size === 1) {
this.add(directory, item, true);
}
const wp = this._getWatchedDir(path10);
const nestedDirectoryChildren = wp.getChildren();
nestedDirectoryChildren.forEach((nested) => this._remove(path10, nested));
const parent = this._getWatchedDir(directory);
const wasTracked = parent.has(item);
parent.remove(item);
if (this._symlinkPaths.has(fullPath)) {
this._symlinkPaths.delete(fullPath);
}
let relPath = path10;
if (this.options.cwd)
relPath = sysPath2.relative(this.options.cwd, path10);
if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
const event = this._pendingWrites.get(relPath).cancelWait();
if (event === EVENTS.ADD)
return;
}
this._watched.delete(path10);
this._watched.delete(fullPath);
const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
if (wasTracked && !this._isIgnored(path10))
this._emit(eventName, path10);
this._closePath(path10);
}
_closePath(path10) {
this._closeFile(path10);
const dir = sysPath2.dirname(path10);
this._getWatchedDir(dir).remove(sysPath2.basename(path10));
}
_closeFile(path10) {
const closers = this._closers.get(path10);
if (!closers)
return;
closers.forEach((closer) => closer());
this._closers.delete(path10);
}
_addPathCloser(path10, closer) {
if (!closer)
return;
let list = this._closers.get(path10);
if (!list) {
list = [];
this._closers.set(path10, list);
}
list.push(closer);
}
_readdirp(root2, opts) {
if (this.closed)
return;
const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
let stream4 = readdirp(root2, options);
this._streams.add(stream4);
stream4.once(STR_CLOSE, () => {
stream4 = undefined;
});
stream4.once(STR_END, () => {
if (stream4) {
this._streams.delete(stream4);
stream4 = undefined;
}
});
return stream4;
}
};
esm_default = { watch, FSWatcher };
});
// src/utils/settings/changeDetector.ts
var exports_changeDetector = {};
__export(exports_changeDetector, {
subscribe: () => subscribe2,
settingsChangeDetector: () => settingsChangeDetector,
resetForTesting: () => resetForTesting,
notifyChange: () => notifyChange,
initialize: () => initialize,
dispose: () => dispose
});
import { stat as stat12 } from "fs/promises";
import * as platformPath from "path";
async function initialize() {
if (getIsRemoteMode())
return;
if (initialized || disposed)
return;
initialized = true;
startMdmPoll();
registerCleanup(dispose);
const { dirs, settingsFiles, dropInDir } = await getWatchTargets();
if (disposed)
return;
if (dirs.length === 0)
return;
logForDebugging(`Watching for changes in setting files ${[...settingsFiles].join(", ")}...${dropInDir ? ` and drop-in directory ${dropInDir}` : ""}`);
watcher = esm_default.watch(dirs, {
persistent: true,
ignoreInitial: true,
depth: 0,
awaitWriteFinish: {
stabilityThreshold: testOverrides?.stabilityThreshold ?? FILE_STABILITY_THRESHOLD_MS,
pollInterval: testOverrides?.pollInterval ?? FILE_STABILITY_POLL_INTERVAL_MS
},
ignored: (path10, stats) => {
if (stats && !stats.isFile() && !stats.isDirectory())
return true;
if (path10.split(platformPath.sep).some((dir) => dir === ".git"))
return true;
if (!stats || stats.isDirectory())
return false;
const normalized = platformPath.normalize(path10);
if (settingsFiles.has(normalized))
return false;
if (dropInDir && normalized.startsWith(dropInDir + platformPath.sep) && normalized.endsWith(".json")) {
return false;
}
return true;
},
ignorePermissionErrors: true,
usePolling: false,
atomic: true
});
watcher.on("change", handleChange);
watcher.on("unlink", handleDelete);
watcher.on("add", handleAdd);
}
function dispose() {
disposed = true;
if (mdmPollTimer) {
clearInterval(mdmPollTimer);
mdmPollTimer = null;
}
for (const timer of pendingDeletions.values())
clearTimeout(timer);
pendingDeletions.clear();
lastMdmSnapshot = null;
clearInternalWrites();
settingsChanged.clear();
const w = watcher;
watcher = null;
return w ? w.close() : Promise.resolve();
}
async function getWatchTargets() {
const dirToSettingsFiles = new Map;
const dirsWithExistingFiles = new Set;
for (const source of SETTING_SOURCES) {
if (source === "flagSettings") {
continue;
}
const path10 = getSettingsFilePathForSource(source);
if (!path10) {
continue;
}
const dir = platformPath.dirname(path10);
if (!dirToSettingsFiles.has(dir)) {
dirToSettingsFiles.set(dir, new Set);
}
dirToSettingsFiles.get(dir).add(path10);
try {
const stats = await stat12(path10);
if (stats.isFile()) {
dirsWithExistingFiles.add(dir);
}
} catch {}
}
const settingsFiles = new Set;
for (const dir of dirsWithExistingFiles) {
const filesInDir = dirToSettingsFiles.get(dir);
if (filesInDir) {
for (const file2 of filesInDir) {
settingsFiles.add(file2);
}
}
}
let dropInDir = null;
const managedDropIn = getManagedSettingsDropInDir();
try {
const stats = await stat12(managedDropIn);
if (stats.isDirectory()) {
dirsWithExistingFiles.add(managedDropIn);
dropInDir = managedDropIn;
}
} catch {}
return { dirs: [...dirsWithExistingFiles], settingsFiles, dropInDir };
}
function settingSourceToConfigChangeSource(source) {
switch (source) {
case "userSettings":
return "user_settings";
case "projectSettings":
return "project_settings";
case "localSettings":
return "local_settings";
case "flagSettings":
case "policySettings":
return "policy_settings";
}
}
function handleChange(path10) {
const source = getSourceForPath(path10);
if (!source)
return;
const pendingTimer = pendingDeletions.get(path10);
if (pendingTimer) {
clearTimeout(pendingTimer);
pendingDeletions.delete(path10);
logForDebugging(`Cancelled pending deletion of ${path10} — file was recreated`);
}
if (consumeInternalWrite(path10, INTERNAL_WRITE_WINDOW_MS)) {
return;
}
logForDebugging(`Detected change to ${path10}`);
executeConfigChangeHooks(settingSourceToConfigChangeSource(source), path10).then((results) => {
if (hasBlockingResult(results)) {
logForDebugging(`ConfigChange hook blocked change to ${path10}`);
return;
}
fanOut(source);
});
}
function handleAdd(path10) {
const source = getSourceForPath(path10);
if (!source)
return;
const pendingTimer = pendingDeletions.get(path10);
if (pendingTimer) {
clearTimeout(pendingTimer);
pendingDeletions.delete(path10);
logForDebugging(`Cancelled pending deletion of ${path10} — file was re-added`);
}
handleChange(path10);
}
function handleDelete(path10) {
const source = getSourceForPath(path10);
if (!source)
return;
logForDebugging(`Detected deletion of ${path10}`);
if (pendingDeletions.has(path10))
return;
const timer = setTimeout((p, src) => {
pendingDeletions.delete(p);
executeConfigChangeHooks(settingSourceToConfigChangeSource(src), p).then((results) => {
if (hasBlockingResult(results)) {
logForDebugging(`ConfigChange hook blocked deletion of ${p}`);
return;
}
fanOut(src);
});
}, testOverrides?.deletionGrace ?? DELETION_GRACE_MS, path10, source);
pendingDeletions.set(path10, timer);
}
function getSourceForPath(path10) {
const normalizedPath = platformPath.normalize(path10);
const dropInDir = getManagedSettingsDropInDir();
if (normalizedPath.startsWith(dropInDir + platformPath.sep)) {
return "policySettings";
}
return SETTING_SOURCES.find((source) => getSettingsFilePathForSource(source) === normalizedPath);
}
function startMdmPoll() {
const initial = getMdmSettings();
const initialHkcu = getHkcuSettings();
lastMdmSnapshot = jsonStringify({
mdm: initial.settings,
hkcu: initialHkcu.settings
});
mdmPollTimer = setInterval(() => {
if (disposed)
return;
(async () => {
try {
const { mdm: current, hkcu: currentHkcu } = await refreshMdmSettings();
if (disposed)
return;
const currentSnapshot = jsonStringify({
mdm: current.settings,
hkcu: currentHkcu.settings
});
if (currentSnapshot !== lastMdmSnapshot) {
lastMdmSnapshot = currentSnapshot;
setMdmSettingsCache(current, currentHkcu);
logForDebugging("Detected MDM settings change via poll");
fanOut("policySettings");
}
} catch (error44) {
logForDebugging(`MDM poll error: ${errorMessage(error44)}`);
}
})();
}, testOverrides?.mdmPollInterval ?? MDM_POLL_INTERVAL_MS);
mdmPollTimer.unref();
}
function fanOut(source) {
resetSettingsCache();
settingsChanged.emit(source);
}
function notifyChange(source) {
logForDebugging(`Programmatic settings change notification for ${source}`);
fanOut(source);
}
function resetForTesting(overrides) {
if (mdmPollTimer) {
clearInterval(mdmPollTimer);
mdmPollTimer = null;
}
for (const timer of pendingDeletions.values())
clearTimeout(timer);
pendingDeletions.clear();
lastMdmSnapshot = null;
initialized = false;
disposed = false;
testOverrides = overrides ?? null;
const w = watcher;
watcher = null;
return w ? w.close() : Promise.resolve();
}
var FILE_STABILITY_THRESHOLD_MS = 1000, FILE_STABILITY_POLL_INTERVAL_MS = 500, INTERNAL_WRITE_WINDOW_MS = 5000, MDM_POLL_INTERVAL_MS, DELETION_GRACE_MS, watcher = null, mdmPollTimer = null, lastMdmSnapshot = null, initialized = false, disposed = false, pendingDeletions, settingsChanged, testOverrides = null, subscribe2, settingsChangeDetector;
var init_changeDetector = __esm(() => {
init_esm3();
init_state();
init_cleanupRegistry();
init_debug();
init_errors();
init_hooks5();
init_slowOperations();
init_constants2();
init_internalWrites();
init_managedPath();
init_settings();
init_settings2();
init_settingsCache();
MDM_POLL_INTERVAL_MS = 30 * 60 * 1000;
DELETION_GRACE_MS = FILE_STABILITY_THRESHOLD_MS + FILE_STABILITY_POLL_INTERVAL_MS + 200;
pendingDeletions = new Map;
settingsChanged = createSignal();
subscribe2 = settingsChanged.subscribe;
settingsChangeDetector = {
initialize,
dispose,
subscribe: subscribe2,
notifyChange,
resetForTesting
};
});
// src/hooks/useSettingsChange.ts
function useSettingsChange(onChange) {
const handleChange2 = import_react30.useCallback((source) => {
const newSettings = getSettings_DEPRECATED();
onChange(source, newSettings);
}, [onChange]);
import_react30.useEffect(() => settingsChangeDetector.subscribe(handleChange2), [handleChange2]);
}
var import_react30;
var init_useSettingsChange = __esm(() => {
init_changeDetector();
init_settings2();
import_react30 = __toESM(require_react(), 1);
});
// node_modules/lodash-es/last.js
function last(array2) {
var length = array2 == null ? 0 : array2.length;
return length ? array2[length - 1] : undefined;
}
var last_default;
var init_last = __esm(() => {
last_default = last;
});
// src/buddy/types.ts
var RARITIES, c6, duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk, SPECIES, EYES, HATS, STAT_NAMES, RARITY_WEIGHTS;
var init_types4 = __esm(() => {
RARITIES = [
"common",
"uncommon",
"rare",
"epic",
"legendary"
];
c6 = String.fromCharCode;
duck = c6(100, 117, 99, 107);
goose = c6(103, 111, 111, 115, 101);
blob = c6(98, 108, 111, 98);
cat = c6(99, 97, 116);
dragon = c6(100, 114, 97, 103, 111, 110);
octopus = c6(111, 99, 116, 111, 112, 117, 115);
owl = c6(111, 119, 108);
penguin = c6(112, 101, 110, 103, 117, 105, 110);
turtle = c6(116, 117, 114, 116, 108, 101);
snail = c6(115, 110, 97, 105, 108);
ghost = c6(103, 104, 111, 115, 116);
axolotl = c6(97, 120, 111, 108, 111, 116, 108);
capybara = c6(99, 97, 112, 121, 98, 97, 114, 97);
cactus = c6(99, 97, 99, 116, 117, 115);
robot = c6(114, 111, 98, 111, 116);
rabbit = c6(114, 97, 98, 98, 105, 116);
mushroom = c6(109, 117, 115, 104, 114, 111, 111, 109);
chonk = c6(99, 104, 111, 110, 107);
SPECIES = [
duck,
goose,
blob,
cat,
dragon,
octopus,
owl,
penguin,
turtle,
snail,
ghost,
axolotl,
capybara,
cactus,
robot,
rabbit,
mushroom,
chonk
];
EYES = ["·", "✦", "×", "◉", "@", "°"];
HATS = [
"none",
"crown",
"tophat",
"propeller",
"halo",
"wizard",
"beanie",
"tinyduck"
];
STAT_NAMES = [
"DEBUGGING",
"PATIENCE",
"CHAOS",
"WISDOM",
"SNARK"
];
RARITY_WEIGHTS = {
common: 60,
uncommon: 25,
rare: 10,
epic: 4,
legendary: 1
};
});
// src/buddy/companion.ts
function mulberry32(seed) {
let a2 = seed >>> 0;
return function() {
a2 |= 0;
a2 = a2 + 1831565813 | 0;
let t = Math.imul(a2 ^ a2 >>> 15, 1 | a2);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
function hashString(s) {
if (typeof Bun !== "undefined") {
return Number(BigInt(Bun.hash(s)) & 0xffffffffn);
}
let h2 = 2166136261;
for (let i2 = 0;i2 < s.length; i2++) {
h2 ^= s.charCodeAt(i2);
h2 = Math.imul(h2, 16777619);
}
return h2 >>> 0;
}
function pick2(rng, arr) {
return arr[Math.floor(rng() * arr.length)];
}
function rollRarity(rng) {
const total = Object.values(RARITY_WEIGHTS).reduce((a2, b) => a2 + b, 0);
let roll = rng() * total;
for (const rarity of RARITIES) {
roll -= RARITY_WEIGHTS[rarity];
if (roll < 0)
return rarity;
}
return "common";
}
function rollStats(rng, rarity) {
const floor = RARITY_FLOOR[rarity];
const peak = pick2(rng, STAT_NAMES);
let dump = pick2(rng, STAT_NAMES);
while (dump === peak)
dump = pick2(rng, STAT_NAMES);
const stats = {};
for (const name of STAT_NAMES) {
if (name === peak) {
stats[name] = Math.min(100, floor + 50 + Math.floor(rng() * 30));
} else if (name === dump) {
stats[name] = Math.max(1, floor - 10 + Math.floor(rng() * 15));
} else {
stats[name] = floor + Math.floor(rng() * 40);
}
}
return stats;
}
function rollFrom(rng) {
const rarity = rollRarity(rng);
const bones = {
rarity,
species: pick2(rng, SPECIES),
eye: pick2(rng, EYES),
hat: rarity === "common" ? "none" : pick2(rng, HATS),
shiny: rng() < 0.01,
stats: rollStats(rng, rarity)
};
return { bones, inspirationSeed: Math.floor(rng() * 1e9) };
}
function roll(userId) {
const key = userId + SALT;
if (rollCache?.key === key)
return rollCache.value;
const value = rollFrom(mulberry32(hashString(key)));
rollCache = { key, value };
return value;
}
function companionUserId() {
const config2 = getGlobalConfig();
return config2.oauthAccount?.accountUuid ?? config2.userID ?? "anon";
}
function getCompanion() {
const stored = getGlobalConfig().companion;
if (!stored)
return;
const { bones } = roll(companionUserId());
return { ...stored, ...bones };
}
var RARITY_FLOOR, SALT = "friend-2026-401", rollCache;
var init_companion = __esm(() => {
init_config();
init_types4();
RARITY_FLOOR = {
common: 5,
uncommon: 15,
rare: 25,
epic: 35,
legendary: 50
};
});
// src/buddy/prompt.ts
function companionIntroText(name, species) {
return `# Companion
A small ${species} named ${name} sits beside the user's input box and occasionally comments in a speech bubble. You're not ${name} — it's a separate watcher.
When the user addresses ${name} directly (by name), its bubble will answer. Your job in that moment is to stay out of the way: respond in ONE line or less, or just answer any part of the message meant for you. Don't explain that you're not ${name} — they know. Don't narrate what ${name} might say — the bubble handles that.`;
}
var init_prompt4 = __esm(() => {
init_config();
init_companion();
});
// src/constants/messages.ts
var NO_CONTENT_MESSAGE = "(no content)";
// node_modules/yaml/dist/nodes/identity.js
var require_identity = __commonJS((exports) => {
var ALIAS = Symbol.for("yaml.alias");
var DOC = Symbol.for("yaml.document");
var MAP = Symbol.for("yaml.map");
var PAIR = Symbol.for("yaml.pair");
var SCALAR = Symbol.for("yaml.scalar");
var SEQ = Symbol.for("yaml.seq");
var NODE_TYPE = Symbol.for("yaml.node.type");
var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
var isMap2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === "object")
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === "object")
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
exports.ALIAS = ALIAS;
exports.DOC = DOC;
exports.MAP = MAP;
exports.NODE_TYPE = NODE_TYPE;
exports.PAIR = PAIR;
exports.SCALAR = SCALAR;
exports.SEQ = SEQ;
exports.hasAnchor = hasAnchor;
exports.isAlias = isAlias;
exports.isCollection = isCollection;
exports.isDocument = isDocument;
exports.isMap = isMap2;
exports.isNode = isNode;
exports.isPair = isPair;
exports.isScalar = isScalar;
exports.isSeq = isSeq;
});
// node_modules/yaml/dist/visit.js
var require_visit = __commonJS((exports) => {
var identity4 = require_identity();
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove node");
function visit2(node, visitor) {
const visitor_ = initVisitor(visitor);
if (identity4.isDocument(node)) {
const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
} else
visit_(null, node, visitor_, Object.freeze([]));
}
visit2.BREAK = BREAK;
visit2.SKIP = SKIP;
visit2.REMOVE = REMOVE;
function visit_(key, node, visitor, path10) {
const ctrl = callVisitor(key, node, visitor, path10);
if (identity4.isNode(ctrl) || identity4.isPair(ctrl)) {
replaceNode(key, path10, ctrl);
return visit_(key, ctrl, visitor, path10);
}
if (typeof ctrl !== "symbol") {
if (identity4.isCollection(node)) {
path10 = Object.freeze(path10.concat(node));
for (let i2 = 0;i2 < node.items.length; ++i2) {
const ci = visit_(i2, node.items[i2], visitor, path10);
if (typeof ci === "number")
i2 = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i2, 1);
i2 -= 1;
}
}
} else if (identity4.isPair(node)) {
path10 = Object.freeze(path10.concat(node));
const ck = visit_("key", node.key, visitor, path10);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = visit_("value", node.value, visitor, path10);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
async function visitAsync(node, visitor) {
const visitor_ = initVisitor(visitor);
if (identity4.isDocument(node)) {
const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
} else
await visitAsync_(null, node, visitor_, Object.freeze([]));
}
visitAsync.BREAK = BREAK;
visitAsync.SKIP = SKIP;
visitAsync.REMOVE = REMOVE;
async function visitAsync_(key, node, visitor, path10) {
const ctrl = await callVisitor(key, node, visitor, path10);
if (identity4.isNode(ctrl) || identity4.isPair(ctrl)) {
replaceNode(key, path10, ctrl);
return visitAsync_(key, ctrl, visitor, path10);
}
if (typeof ctrl !== "symbol") {
if (identity4.isCollection(node)) {
path10 = Object.freeze(path10.concat(node));
for (let i2 = 0;i2 < node.items.length; ++i2) {
const ci = await visitAsync_(i2, node.items[i2], visitor, path10);
if (typeof ci === "number")
i2 = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i2, 1);
i2 -= 1;
}
}
} else if (identity4.isPair(node)) {
path10 = Object.freeze(path10.concat(node));
const ck = await visitAsync_("key", node.key, visitor, path10);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = await visitAsync_("value", node.value, visitor, path10);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
function initVisitor(visitor) {
if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
return Object.assign({
Alias: visitor.Node,
Map: visitor.Node,
Scalar: visitor.Node,
Seq: visitor.Node
}, visitor.Value && {
Map: visitor.Value,
Scalar: visitor.Value,
Seq: visitor.Value
}, visitor.Collection && {
Map: visitor.Collection,
Seq: visitor.Collection
}, visitor);
}
return visitor;
}
function callVisitor(key, node, visitor, path10) {
if (typeof visitor === "function")
return visitor(key, node, path10);
if (identity4.isMap(node))
return visitor.Map?.(key, node, path10);
if (identity4.isSeq(node))
return visitor.Seq?.(key, node, path10);
if (identity4.isPair(node))
return visitor.Pair?.(key, node, path10);
if (identity4.isScalar(node))
return visitor.Scalar?.(key, node, path10);
if (identity4.isAlias(node))
return visitor.Alias?.(key, node, path10);
return;
}
function replaceNode(key, path10, node) {
const parent = path10[path10.length - 1];
if (identity4.isCollection(parent)) {
parent.items[key] = node;
} else if (identity4.isPair(parent)) {
if (key === "key")
parent.key = node;
else
parent.value = node;
} else if (identity4.isDocument(parent)) {
parent.contents = node;
} else {
const pt = identity4.isAlias(parent) ? "alias" : "scalar";
throw new Error(`Cannot replace node with ${pt} parent`);
}
}
exports.visit = visit2;
exports.visitAsync = visitAsync;
});
// node_modules/yaml/dist/doc/directives.js
var require_directives = __commonJS((exports) => {
var identity4 = require_identity();
var visit2 = require_visit();
var escapeChars = {
"!": "%21",
",": "%2C",
"[": "%5B",
"]": "%5D",
"{": "%7B",
"}": "%7D"
};
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
class Directives {
constructor(yaml, tags) {
this.docStart = null;
this.docEnd = false;
this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
this.tags = Object.assign({}, Directives.defaultTags, tags);
}
clone() {
const copy = new Directives(this.yaml, this.tags);
copy.docStart = this.docStart;
return copy;
}
atDocument() {
const res = new Directives(this.yaml, this.tags);
switch (this.yaml.version) {
case "1.1":
this.atNextDocument = true;
break;
case "1.2":
this.atNextDocument = false;
this.yaml = {
explicit: Directives.defaultYaml.explicit,
version: "1.2"
};
this.tags = Object.assign({}, Directives.defaultTags);
break;
}
return res;
}
add(line, onError) {
if (this.atNextDocument) {
this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" };
this.tags = Object.assign({}, Directives.defaultTags);
this.atNextDocument = false;
}
const parts = line.trim().split(/[ \t]+/);
const name = parts.shift();
switch (name) {
case "%TAG": {
if (parts.length !== 2) {
onError(0, "%TAG directive should contain exactly two parts");
if (parts.length < 2)
return false;
}
const [handle, prefix] = parts;
this.tags[handle] = prefix;
return true;
}
case "%YAML": {
this.yaml.explicit = true;
if (parts.length !== 1) {
onError(0, "%YAML directive should contain exactly one part");
return false;
}
const [version2] = parts;
if (version2 === "1.1" || version2 === "1.2") {
this.yaml.version = version2;
return true;
} else {
const isValid = /^\d+\.\d+$/.test(version2);
onError(6, `Unsupported YAML version ${version2}`, isValid);
return false;
}
}
default:
onError(0, `Unknown directive ${name}`, true);
return false;
}
}
tagName(source, onError) {
if (source === "!")
return "!";
if (source[0] !== "!") {
onError(`Not a valid tag: ${source}`);
return null;
}
if (source[1] === "<") {
const verbatim = source.slice(2, -1);
if (verbatim === "!" || verbatim === "!!") {
onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
return null;
}
if (source[source.length - 1] !== ">")
onError("Verbatim tags must end with a >");
return verbatim;
}
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
if (!suffix)
onError(`The ${source} tag has no suffix`);
const prefix = this.tags[handle];
if (prefix) {
try {
return prefix + decodeURIComponent(suffix);
} catch (error44) {
onError(String(error44));
return null;
}
}
if (handle === "!")
return source;
onError(`Could not resolve tag: ${source}`);
return null;
}
tagString(tag) {
for (const [handle, prefix] of Object.entries(this.tags)) {
if (tag.startsWith(prefix))
return handle + escapeTagName(tag.substring(prefix.length));
}
return tag[0] === "!" ? tag : `!<${tag}>`;
}
toString(doc2) {
const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
const tagEntries = Object.entries(this.tags);
let tagNames;
if (doc2 && tagEntries.length > 0 && identity4.isNode(doc2.contents)) {
const tags = {};
visit2.visit(doc2.contents, (_key, node) => {
if (identity4.isNode(node) && node.tag)
tags[node.tag] = true;
});
tagNames = Object.keys(tags);
} else
tagNames = [];
for (const [handle, prefix] of tagEntries) {
if (handle === "!!" && prefix === "tag:yaml.org,2002:")
continue;
if (!doc2 || tagNames.some((tn) => tn.startsWith(prefix)))
lines.push(`%TAG ${handle} ${prefix}`);
}
return lines.join(`
`);
}
}
Directives.defaultYaml = { explicit: false, version: "1.2" };
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
exports.Directives = Directives;
});
// node_modules/yaml/dist/doc/anchors.js
var require_anchors = __commonJS((exports) => {
var identity4 = require_identity();
var visit2 = require_visit();
function anchorIsValid(anchor) {
if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
const sa = JSON.stringify(anchor);
const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
throw new Error(msg);
}
return true;
}
function anchorNames(root2) {
const anchors = new Set;
visit2.visit(root2, {
Value(_key, node) {
if (node.anchor)
anchors.add(node.anchor);
}
});
return anchors;
}
function findNewAnchor(prefix, exclude) {
for (let i2 = 1;; ++i2) {
const name = `${prefix}${i2}`;
if (!exclude.has(name))
return name;
}
}
function createNodeAnchors(doc2, prefix) {
const aliasObjects = [];
const sourceObjects = new Map;
let prevAnchors = null;
return {
onAnchor: (source) => {
aliasObjects.push(source);
prevAnchors ?? (prevAnchors = anchorNames(doc2));
const anchor = findNewAnchor(prefix, prevAnchors);
prevAnchors.add(anchor);
return anchor;
},
setAnchors: () => {
for (const source of aliasObjects) {
const ref = sourceObjects.get(source);
if (typeof ref === "object" && ref.anchor && (identity4.isScalar(ref.node) || identity4.isCollection(ref.node))) {
ref.node.anchor = ref.anchor;
} else {
const error44 = new Error("Failed to resolve repeated object (this should not happen)");
error44.source = source;
throw error44;
}
}
},
sourceObjects
};
}
exports.anchorIsValid = anchorIsValid;
exports.anchorNames = anchorNames;
exports.createNodeAnchors = createNodeAnchors;
exports.findNewAnchor = findNewAnchor;
});
// node_modules/yaml/dist/doc/applyReviver.js
var require_applyReviver = __commonJS((exports) => {
function applyReviver(reviver, obj, key, val) {
if (val && typeof val === "object") {
if (Array.isArray(val)) {
for (let i2 = 0, len = val.length;i2 < len; ++i2) {
const v0 = val[i2];
const v1 = applyReviver(reviver, val, String(i2), v0);
if (v1 === undefined)
delete val[i2];
else if (v1 !== v0)
val[i2] = v1;
}
} else if (val instanceof Map) {
for (const k of Array.from(val.keys())) {
const v0 = val.get(k);
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === undefined)
val.delete(k);
else if (v1 !== v0)
val.set(k, v1);
}
} else if (val instanceof Set) {
for (const v0 of Array.from(val)) {
const v1 = applyReviver(reviver, val, v0, v0);
if (v1 === undefined)
val.delete(v0);
else if (v1 !== v0) {
val.delete(v0);
val.add(v1);
}
}
} else {
for (const [k, v0] of Object.entries(val)) {
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === undefined)
delete val[k];
else if (v1 !== v0)
val[k] = v1;
}
}
}
return reviver.call(obj, key, val);
}
exports.applyReviver = applyReviver;
});
// node_modules/yaml/dist/nodes/toJS.js
var require_toJS = __commonJS((exports) => {
var identity4 = require_identity();
function toJS(value, arg, ctx) {
if (Array.isArray(value))
return value.map((v, i2) => toJS(v, String(i2), ctx));
if (value && typeof value.toJSON === "function") {
if (!ctx || !identity4.hasAnchor(value))
return value.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: undefined };
ctx.anchors.set(value, data);
ctx.onCreate = (res2) => {
data.res = res2;
delete ctx.onCreate;
};
const res = value.toJSON(arg, ctx);
if (ctx.onCreate)
ctx.onCreate(res);
return res;
}
if (typeof value === "bigint" && !ctx?.keep)
return Number(value);
return value;
}
exports.toJS = toJS;
});
// node_modules/yaml/dist/nodes/Node.js
var require_Node = __commonJS((exports) => {
var applyReviver = require_applyReviver();
var identity4 = require_identity();
var toJS = require_toJS();
class NodeBase {
constructor(type) {
Object.defineProperty(this, identity4.NODE_TYPE, { value: type });
}
clone() {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (this.range)
copy.range = this.range.slice();
return copy;
}
toJS(doc2, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
if (!identity4.isDocument(doc2))
throw new TypeError("A document argument is required");
const ctx = {
anchors: new Map,
doc: doc2,
keep: true,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS.toJS(this, "", ctx);
if (typeof onAnchor === "function")
for (const { count: count3, res: res2 } of ctx.anchors.values())
onAnchor(res2, count3);
return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
}
}
exports.NodeBase = NodeBase;
});
// node_modules/yaml/dist/nodes/Alias.js
var require_Alias = __commonJS((exports) => {
var anchors = require_anchors();
var visit2 = require_visit();
var identity4 = require_identity();
var Node2 = require_Node();
var toJS = require_toJS();
class Alias extends Node2.NodeBase {
constructor(source) {
super(identity4.ALIAS);
this.source = source;
Object.defineProperty(this, "tag", {
set() {
throw new Error("Alias nodes cannot have tags");
}
});
}
resolve(doc2, ctx) {
let nodes;
if (ctx?.aliasResolveCache) {
nodes = ctx.aliasResolveCache;
} else {
nodes = [];
visit2.visit(doc2, {
Node: (_key, node) => {
if (identity4.isAlias(node) || identity4.hasAnchor(node))
nodes.push(node);
}
});
if (ctx)
ctx.aliasResolveCache = nodes;
}
let found = undefined;
for (const node of nodes) {
if (node === this)
break;
if (node.anchor === this.source)
found = node;
}
return found;
}
toJSON(_arg, ctx) {
if (!ctx)
return { source: this.source };
const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx;
const source = this.resolve(doc2, ctx);
if (!source) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
let data = anchors2.get(source);
if (!data) {
toJS.toJS(source, null, ctx);
data = anchors2.get(source);
}
if (data?.res === undefined) {
const msg = "This should not happen: Alias anchor was not resolved?";
throw new ReferenceError(msg);
}
if (maxAliasCount >= 0) {
data.count += 1;
if (data.aliasCount === 0)
data.aliasCount = getAliasCount(doc2, source, anchors2);
if (data.count * data.aliasCount > maxAliasCount) {
const msg = "Excessive alias count indicates a resource exhaustion attack";
throw new ReferenceError(msg);
}
}
return data.res;
}
toString(ctx, _onComment, _onChompKeep) {
const src = `*${this.source}`;
if (ctx) {
anchors.anchorIsValid(this.source);
if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new Error(msg);
}
if (ctx.implicitKey)
return `${src} `;
}
return src;
}
}
function getAliasCount(doc2, node, anchors2) {
if (identity4.isAlias(node)) {
const source = node.resolve(doc2);
const anchor = anchors2 && source && anchors2.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
} else if (identity4.isCollection(node)) {
let count3 = 0;
for (const item of node.items) {
const c7 = getAliasCount(doc2, item, anchors2);
if (c7 > count3)
count3 = c7;
}
return count3;
} else if (identity4.isPair(node)) {
const kc = getAliasCount(doc2, node.key, anchors2);
const vc = getAliasCount(doc2, node.value, anchors2);
return Math.max(kc, vc);
}
return 1;
}
exports.Alias = Alias;
});
// node_modules/yaml/dist/nodes/Scalar.js
var require_Scalar = __commonJS((exports) => {
var identity4 = require_identity();
var Node2 = require_Node();
var toJS = require_toJS();
var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
class Scalar extends Node2.NodeBase {
constructor(value) {
super(identity4.SCALAR);
this.value = value;
}
toJSON(arg, ctx) {
return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
}
toString() {
return String(this.value);
}
}
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
Scalar.PLAIN = "PLAIN";
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
exports.Scalar = Scalar;
exports.isScalarValue = isScalarValue;
});
// node_modules/yaml/dist/doc/createNode.js
var require_createNode = __commonJS((exports) => {
var Alias = require_Alias();
var identity4 = require_identity();
var Scalar = require_Scalar();
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value, tagName, tags) {
if (tagName) {
const match = tags.filter((t) => t.tag === tagName);
const tagObj = match.find((t) => !t.format) ?? match[0];
if (!tagObj)
throw new Error(`Tag ${tagName} not found`);
return tagObj;
}
return tags.find((t) => t.identify?.(value) && !t.format);
}
function createNode2(value, tagName, ctx) {
if (identity4.isDocument(value))
value = value.contents;
if (identity4.isNode(value))
return value;
if (identity4.isPair(value)) {
const map3 = ctx.schema[identity4.MAP].createNode?.(ctx.schema, null, ctx);
map3.items.push(value);
return map3;
}
if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
value = value.valueOf();
}
const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
let ref = undefined;
if (aliasDuplicateObjects && value && typeof value === "object") {
ref = sourceObjects.get(value);
if (ref) {
ref.anchor ?? (ref.anchor = onAnchor(value));
return new Alias.Alias(ref.anchor);
} else {
ref = { anchor: null, node: null };
sourceObjects.set(value, ref);
}
}
if (tagName?.startsWith("!!"))
tagName = defaultTagPrefix + tagName.slice(2);
let tagObj = findTagObject(value, tagName, schema.tags);
if (!tagObj) {
if (value && typeof value.toJSON === "function") {
value = value.toJSON();
}
if (!value || typeof value !== "object") {
const node2 = new Scalar.Scalar(value);
if (ref)
ref.node = node2;
return node2;
}
tagObj = value instanceof Map ? schema[identity4.MAP] : (Symbol.iterator in Object(value)) ? schema[identity4.SEQ] : schema[identity4.MAP];
}
if (onTagObj) {
onTagObj(tagObj);
delete ctx.onTagObj;
}
const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value);
if (tagName)
node.tag = tagName;
else if (!tagObj.default)
node.tag = tagObj.tag;
if (ref)
ref.node = node;
return node;
}
exports.createNode = createNode2;
});
// node_modules/yaml/dist/nodes/Collection.js
var require_Collection = __commonJS((exports) => {
var createNode2 = require_createNode();
var identity4 = require_identity();
var Node2 = require_Node();
function collectionFromPath(schema, path10, value) {
let v = value;
for (let i2 = path10.length - 1;i2 >= 0; --i2) {
const k = path10[i2];
if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
const a2 = [];
a2[k] = v;
v = a2;
} else {
v = new Map([[k, v]]);
}
}
return createNode2.createNode(v, undefined, {
aliasDuplicateObjects: false,
keepUndefined: false,
onAnchor: () => {
throw new Error("This should not happen, please report a bug.");
},
schema,
sourceObjects: new Map
});
}
var isEmptyPath = (path10) => path10 == null || typeof path10 === "object" && !!path10[Symbol.iterator]().next().done;
class Collection extends Node2.NodeBase {
constructor(type, schema) {
super(type);
Object.defineProperty(this, "schema", {
value: schema,
configurable: true,
enumerable: false,
writable: true
});
}
clone(schema) {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema)
copy.schema = schema;
copy.items = copy.items.map((it) => identity4.isNode(it) || identity4.isPair(it) ? it.clone(schema) : it);
if (this.range)
copy.range = this.range.slice();
return copy;
}
addIn(path10, value) {
if (isEmptyPath(path10))
this.add(value);
else {
const [key, ...rest] = path10;
const node = this.get(key, true);
if (identity4.isCollection(node))
node.addIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
deleteIn(path10) {
const [key, ...rest] = path10;
if (rest.length === 0)
return this.delete(key);
const node = this.get(key, true);
if (identity4.isCollection(node))
return node.deleteIn(rest);
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
getIn(path10, keepScalar) {
const [key, ...rest] = path10;
const node = this.get(key, true);
if (rest.length === 0)
return !keepScalar && identity4.isScalar(node) ? node.value : node;
else
return identity4.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
}
hasAllNullValues(allowScalar) {
return this.items.every((node) => {
if (!identity4.isPair(node))
return false;
const n2 = node.value;
return n2 == null || allowScalar && identity4.isScalar(n2) && n2.value == null && !n2.commentBefore && !n2.comment && !n2.tag;
});
}
hasIn(path10) {
const [key, ...rest] = path10;
if (rest.length === 0)
return this.has(key);
const node = this.get(key, true);
return identity4.isCollection(node) ? node.hasIn(rest) : false;
}
setIn(path10, value) {
const [key, ...rest] = path10;
if (rest.length === 0) {
this.set(key, value);
} else {
const node = this.get(key, true);
if (identity4.isCollection(node))
node.setIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
}
exports.Collection = Collection;
exports.collectionFromPath = collectionFromPath;
exports.isEmptyPath = isEmptyPath;
});
// node_modules/yaml/dist/stringify/stringifyComment.js
var require_stringifyComment = __commonJS((exports) => {
var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
function indentComment(comment, indent) {
if (/^\n+$/.test(comment))
return comment.substring(1);
return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
var lineComment = (str, indent, comment) => str.endsWith(`
`) ? indentComment(comment, indent) : comment.includes(`
`) ? `
` + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
exports.indentComment = indentComment;
exports.lineComment = lineComment;
exports.stringifyComment = stringifyComment;
});
// node_modules/yaml/dist/stringify/foldFlowLines.js
var require_foldFlowLines = __commonJS((exports) => {
var FOLD_FLOW = "flow";
var FOLD_BLOCK = "block";
var FOLD_QUOTED = "quoted";
function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth: lineWidth2 = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
if (!lineWidth2 || lineWidth2 < 0)
return text;
if (lineWidth2 < minContentWidth)
minContentWidth = 0;
const endStep = Math.max(1 + minContentWidth, 1 + lineWidth2 - indent.length);
if (text.length <= endStep)
return text;
const folds = [];
const escapedFolds = {};
let end = lineWidth2 - indent.length;
if (typeof indentAtStart === "number") {
if (indentAtStart > lineWidth2 - Math.max(2, minContentWidth))
folds.push(0);
else
end = lineWidth2 - indentAtStart;
}
let split = undefined;
let prev = undefined;
let overflow = false;
let i2 = -1;
let escStart = -1;
let escEnd = -1;
if (mode === FOLD_BLOCK) {
i2 = consumeMoreIndentedLines(text, i2, indent.length);
if (i2 !== -1)
end = i2 + endStep;
}
for (let ch;ch = text[i2 += 1]; ) {
if (mode === FOLD_QUOTED && ch === "\\") {
escStart = i2;
switch (text[i2 + 1]) {
case "x":
i2 += 3;
break;
case "u":
i2 += 5;
break;
case "U":
i2 += 9;
break;
default:
i2 += 1;
}
escEnd = i2;
}
if (ch === `
`) {
if (mode === FOLD_BLOCK)
i2 = consumeMoreIndentedLines(text, i2, indent.length);
end = i2 + indent.length + endStep;
split = undefined;
} else {
if (ch === " " && prev && prev !== " " && prev !== `
` && prev !== "\t") {
const next = text[i2 + 1];
if (next && next !== " " && next !== `
` && next !== "\t")
split = i2;
}
if (i2 >= end) {
if (split) {
folds.push(split);
end = split + endStep;
split = undefined;
} else if (mode === FOLD_QUOTED) {
while (prev === " " || prev === "\t") {
prev = ch;
ch = text[i2 += 1];
overflow = true;
}
const j = i2 > escEnd + 1 ? i2 - 2 : escStart - 1;
if (escapedFolds[j])
return text;
folds.push(j);
escapedFolds[j] = true;
end = j + endStep;
split = undefined;
} else {
overflow = true;
}
}
}
prev = ch;
}
if (overflow && onOverflow)
onOverflow();
if (folds.length === 0)
return text;
if (onFold)
onFold();
let res = text.slice(0, folds[0]);
for (let i3 = 0;i3 < folds.length; ++i3) {
const fold = folds[i3];
const end2 = folds[i3 + 1] || text.length;
if (fold === 0)
res = `
${indent}${text.slice(0, end2)}`;
else {
if (mode === FOLD_QUOTED && escapedFolds[fold])
res += `${text[fold]}\\`;
res += `
${indent}${text.slice(fold + 1, end2)}`;
}
}
return res;
}
function consumeMoreIndentedLines(text, i2, indent) {
let end = i2;
let start = i2 + 1;
let ch = text[start];
while (ch === " " || ch === "\t") {
if (i2 < start + indent) {
ch = text[++i2];
} else {
do {
ch = text[++i2];
} while (ch && ch !== `
`);
end = i2;
start = i2 + 1;
ch = text[start];
}
}
return end;
}
exports.FOLD_BLOCK = FOLD_BLOCK;
exports.FOLD_FLOW = FOLD_FLOW;
exports.FOLD_QUOTED = FOLD_QUOTED;
exports.foldFlowLines = foldFlowLines;
});
// node_modules/yaml/dist/stringify/stringifyString.js
var require_stringifyString = __commonJS((exports) => {
var Scalar = require_Scalar();
var foldFlowLines = require_foldFlowLines();
var getFoldOptions = (ctx, isBlock) => ({
indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
lineWidth: ctx.options.lineWidth,
minContentWidth: ctx.options.minContentWidth
});
var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth2, indentLength) {
if (!lineWidth2 || lineWidth2 < 0)
return false;
const limit = lineWidth2 - indentLength;
const strLen = str.length;
if (strLen <= limit)
return false;
for (let i2 = 0, start = 0;i2 < strLen; ++i2) {
if (str[i2] === `
`) {
if (i2 - start > limit)
return true;
start = i2 + 1;
if (strLen - start <= limit)
return false;
}
}
return true;
}
function doubleQuotedString(value, ctx) {
const json2 = JSON.stringify(value);
if (ctx.options.doubleQuotedAsJSON)
return json2;
const { implicitKey } = ctx;
const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
let str = "";
let start = 0;
for (let i2 = 0, ch = json2[i2];ch; ch = json2[++i2]) {
if (ch === " " && json2[i2 + 1] === "\\" && json2[i2 + 2] === "n") {
str += json2.slice(start, i2) + "\\ ";
i2 += 1;
start = i2;
ch = "\\";
}
if (ch === "\\")
switch (json2[i2 + 1]) {
case "u":
{
str += json2.slice(start, i2);
const code = json2.substr(i2 + 2, 4);
switch (code) {
case "0000":
str += "\\0";
break;
case "0007":
str += "\\a";
break;
case "000b":
str += "\\v";
break;
case "001b":
str += "\\e";
break;
case "0085":
str += "\\N";
break;
case "00a0":
str += "\\_";
break;
case "2028":
str += "\\L";
break;
case "2029":
str += "\\P";
break;
default:
if (code.substr(0, 2) === "00")
str += "\\x" + code.substr(2);
else
str += json2.substr(i2, 6);
}
i2 += 5;
start = i2 + 1;
}
break;
case "n":
if (implicitKey || json2[i2 + 2] === '"' || json2.length < minMultiLineLength) {
i2 += 1;
} else {
str += json2.slice(start, i2) + `
`;
while (json2[i2 + 2] === "\\" && json2[i2 + 3] === "n" && json2[i2 + 4] !== '"') {
str += `
`;
i2 += 2;
}
str += indent;
if (json2[i2 + 2] === " ")
str += "\\";
i2 += 1;
start = i2 + 1;
}
break;
default:
i2 += 1;
}
}
str = start ? str + json2.slice(start) : json2;
return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value, ctx) {
if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes(`
`) || /[ \t]\n|\n[ \t]/.test(value))
return doubleQuotedString(value, ctx);
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value, ctx) {
const { singleQuote } = ctx.options;
let qs;
if (singleQuote === false)
qs = doubleQuotedString;
else {
const hasDouble = value.includes('"');
const hasSingle = value.includes("'");
if (hasDouble && !hasSingle)
qs = singleQuotedString;
else if (hasSingle && !hasDouble)
qs = doubleQuotedString;
else
qs = singleQuote ? singleQuotedString : doubleQuotedString;
}
return qs(value, ctx);
}
var blockEndNewlines;
try {
blockEndNewlines = new RegExp(`(^|(?
`;
let chomp;
let endStart;
for (endStart = value.length;endStart > 0; --endStart) {
const ch = value[endStart - 1];
if (ch !== `
` && ch !== "\t" && ch !== " ")
break;
}
let end = value.substring(endStart);
const endNlPos = end.indexOf(`
`);
if (endNlPos === -1) {
chomp = "-";
} else if (value === end || endNlPos !== end.length - 1) {
chomp = "+";
if (onChompKeep)
onChompKeep();
} else {
chomp = "";
}
if (end) {
value = value.slice(0, -end.length);
if (end[end.length - 1] === `
`)
end = end.slice(0, -1);
end = end.replace(blockEndNewlines, `$&${indent}`);
}
let startWithSpace = false;
let startEnd;
let startNlPos = -1;
for (startEnd = 0;startEnd < value.length; ++startEnd) {
const ch = value[startEnd];
if (ch === " ")
startWithSpace = true;
else if (ch === `
`)
startNlPos = startEnd;
else
break;
}
let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
if (start) {
value = value.substring(start.length);
start = start.replace(/\n+/g, `$&${indent}`);
}
const indentSize = indent ? "2" : "1";
let header = (startWithSpace ? indentSize : "") + chomp;
if (comment) {
header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
if (onComment)
onComment();
}
if (!literal2) {
const foldedValue = value.replace(/\n+/g, `
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
let literalFallback = false;
const foldOptions = getFoldOptions(ctx, true);
if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) {
foldOptions.onOverflow = () => {
literalFallback = true;
};
}
const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
if (!literalFallback)
return `>${header}
${indent}${body}`;
}
value = value.replace(/\n+/g, `$&${indent}`);
return `|${header}
${indent}${start}${value}${end}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value } = item;
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if (implicitKey && value.includes(`
`) || inFlow && /[[\]{},]/.test(value)) {
return quotedString(value, ctx);
}
if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
return implicitKey || inFlow || !value.includes(`
`) ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
}
if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes(`
`)) {
return blockString(item, ctx, onComment, onChompKeep);
}
if (containsDocumentMarker(value)) {
if (indent === "") {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
} else if (implicitKey && indent === indentStep) {
return quotedString(value, ctx);
}
}
const str = value.replace(/\n+/g, `$&
${indent}`);
if (actualString) {
const test2 = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
const { compat: compat2, tags } = ctx.doc.schema;
if (tags.some(test2) || compat2?.some(test2))
return quotedString(value, ctx);
}
return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
const { implicitKey, inFlow } = ctx;
const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
let { type } = item;
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
type = Scalar.Scalar.QUOTE_DOUBLE;
}
const _stringify = (_type) => {
switch (_type) {
case Scalar.Scalar.BLOCK_FOLDED:
case Scalar.Scalar.BLOCK_LITERAL:
return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
case Scalar.Scalar.QUOTE_DOUBLE:
return doubleQuotedString(ss.value, ctx);
case Scalar.Scalar.QUOTE_SINGLE:
return singleQuotedString(ss.value, ctx);
case Scalar.Scalar.PLAIN:
return plainString(ss, ctx, onComment, onChompKeep);
default:
return null;
}
};
let res = _stringify(type);
if (res === null) {
const { defaultKeyType, defaultStringType } = ctx.options;
const t = implicitKey && defaultKeyType || defaultStringType;
res = _stringify(t);
if (res === null)
throw new Error(`Unsupported default string type ${t}`);
}
return res;
}
exports.stringifyString = stringifyString;
});
// node_modules/yaml/dist/stringify/stringify.js
var require_stringify = __commonJS((exports) => {
var anchors = require_anchors();
var identity4 = require_identity();
var stringifyComment = require_stringifyComment();
var stringifyString = require_stringifyString();
function createStringifyContext(doc2, options) {
const opt = Object.assign({
blockQuote: true,
commentString: stringifyComment.stringifyComment,
defaultKeyType: null,
defaultStringType: "PLAIN",
directives: null,
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: "false",
flowCollectionPadding: true,
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
nullStr: "null",
simpleKeys: false,
singleQuote: null,
trailingComma: false,
trueStr: "true",
verifyAliasOrder: true
}, doc2.schema.toStringOptions, options);
let inFlow;
switch (opt.collectionStyle) {
case "block":
inFlow = false;
break;
case "flow":
inFlow = true;
break;
default:
inFlow = null;
}
return {
anchors: new Set,
doc: doc2,
flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
indent: "",
indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ",
inFlow,
options: opt
};
}
function getTagObject(tags, item) {
if (item.tag) {
const match = tags.filter((t) => t.tag === item.tag);
if (match.length > 0)
return match.find((t) => t.format === item.format) ?? match[0];
}
let tagObj = undefined;
let obj;
if (identity4.isScalar(item)) {
obj = item.value;
let match = tags.filter((t) => t.identify?.(obj));
if (match.length > 1) {
const testMatch = match.filter((t) => t.test);
if (testMatch.length > 0)
match = testMatch;
}
tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
} else {
obj = item;
tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
}
if (!tagObj) {
const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
throw new Error(`Tag not resolved for ${name} value`);
}
return tagObj;
}
function stringifyProps(node, tagObj, { anchors: anchors$1, doc: doc2 }) {
if (!doc2.directives)
return "";
const props = [];
const anchor = (identity4.isScalar(node) || identity4.isCollection(node)) && node.anchor;
if (anchor && anchors.anchorIsValid(anchor)) {
anchors$1.add(anchor);
props.push(`&${anchor}`);
}
const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
if (tag)
props.push(doc2.directives.tagString(tag));
return props.join(" ");
}
function stringify(item, ctx, onComment, onChompKeep) {
if (identity4.isPair(item))
return item.toString(ctx, onComment, onChompKeep);
if (identity4.isAlias(item)) {
if (ctx.doc.directives)
return item.toString(ctx);
if (ctx.resolvedAliases?.has(item)) {
throw new TypeError(`Cannot stringify circular structure without alias nodes`);
} else {
if (ctx.resolvedAliases)
ctx.resolvedAliases.add(item);
else
ctx.resolvedAliases = new Set([item]);
item = item.resolve(ctx.doc);
}
}
let tagObj = undefined;
const node = identity4.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o2) => tagObj = o2 });
tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
const props = stringifyProps(node, tagObj, ctx);
if (props.length > 0)
ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity4.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
if (!props)
return str;
return identity4.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
}
exports.createStringifyContext = createStringifyContext;
exports.stringify = stringify;
});
// node_modules/yaml/dist/stringify/stringifyPair.js
var require_stringifyPair = __commonJS((exports) => {
var identity4 = require_identity();
var Scalar = require_Scalar();
var stringify = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
const { allNullValues, doc: doc2, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
let keyComment = identity4.isNode(key) && key.comment || null;
if (simpleKeys) {
if (keyComment) {
throw new Error("With simple keys, key nodes cannot have comments");
}
if (identity4.isCollection(key) || !identity4.isNode(key) && typeof key === "object") {
const msg = "With simple keys, collection cannot be used as a key value";
throw new Error(msg);
}
}
let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity4.isCollection(key) || (identity4.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object"));
ctx = Object.assign({}, ctx, {
allNullValues: false,
implicitKey: !explicitKey && (simpleKeys || !allNullValues),
indent: indent + indentStep
});
let keyCommentDone = false;
let chompKeep = false;
let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
if (!explicitKey && !ctx.inFlow && str.length > 1024) {
if (simpleKeys)
throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
explicitKey = true;
}
if (ctx.inFlow) {
if (allNullValues || value == null) {
if (keyCommentDone && onComment)
onComment();
return str === "" ? "?" : explicitKey ? `? ${str}` : str;
}
} else if (allNullValues && !simpleKeys || value == null && explicitKey) {
str = `? ${str}`;
if (keyComment && !keyCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
if (keyCommentDone)
keyComment = null;
if (explicitKey) {
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
str = `? ${str}
${indent}:`;
} else {
str = `${str}:`;
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
}
let vsb, vcb, valueComment;
if (identity4.isNode(value)) {
vsb = !!value.spaceBefore;
vcb = value.commentBefore;
valueComment = value.comment;
} else {
vsb = false;
vcb = null;
valueComment = null;
if (value && typeof value === "object")
value = doc2.createNode(value);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && identity4.isScalar(value))
ctx.indentAtStart = str.length + 1;
chompKeep = false;
if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity4.isSeq(value) && !value.flow && !value.tag && !value.anchor) {
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
let ws = " ";
if (keyComment || vsb || vcb) {
ws = vsb ? `
` : "";
if (vcb) {
const cs = commentString(vcb);
ws += `
${stringifyComment.indentComment(cs, ctx.indent)}`;
}
if (valueStr === "" && !ctx.inFlow) {
if (ws === `
` && valueComment)
ws = `
`;
} else {
ws += `
${ctx.indent}`;
}
} else if (!explicitKey && identity4.isCollection(value)) {
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf(`
`);
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
if (hasNewline || !flow) {
let hasPropsLine = false;
if (hasNewline && (vs0 === "&" || vs0 === "!")) {
let sp0 = valueStr.indexOf(" ");
if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
sp0 = valueStr.indexOf(" ", sp0 + 1);
}
if (sp0 === -1 || nl0 < sp0)
hasPropsLine = true;
}
if (!hasPropsLine)
ws = `
${ctx.indent}`;
}
} else if (valueStr === "" || valueStr[0] === `
`) {
ws = "";
}
str += ws + valueStr;
if (ctx.inFlow) {
if (valueCommentDone && onComment)
onComment();
} else if (valueComment && !valueCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
} else if (chompKeep && onChompKeep) {
onChompKeep();
}
return str;
}
exports.stringifyPair = stringifyPair;
});
// node_modules/yaml/dist/log.js
var require_log = __commonJS((exports) => {
var node_process = __require("process");
function debug(logLevel, ...messages) {
if (logLevel === "debug")
console.log(...messages);
}
function warn(logLevel, warning) {
if (logLevel === "debug" || logLevel === "warn") {
if (typeof node_process.emitWarning === "function")
node_process.emitWarning(warning);
else
console.warn(warning);
}
}
exports.debug = debug;
exports.warn = warn;
});
// node_modules/yaml/dist/schema/yaml-1.1/merge.js
var require_merge = __commonJS((exports) => {
var identity4 = require_identity();
var Scalar = require_Scalar();
var MERGE_KEY = "<<";
var merge3 = {
identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
default: "key",
tag: "tag:yaml.org,2002:merge",
test: /^<<$/,
resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
addToJSMap: addMergeToJSMap
}),
stringify: () => MERGE_KEY
};
var isMergeKey = (ctx, key) => (merge3.identify(key) || identity4.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default);
function addMergeToJSMap(ctx, map3, value) {
value = ctx && identity4.isAlias(value) ? value.resolve(ctx.doc) : value;
if (identity4.isSeq(value))
for (const it of value.items)
mergeValue(ctx, map3, it);
else if (Array.isArray(value))
for (const it of value)
mergeValue(ctx, map3, it);
else
mergeValue(ctx, map3, value);
}
function mergeValue(ctx, map3, value) {
const source = ctx && identity4.isAlias(value) ? value.resolve(ctx.doc) : value;
if (!identity4.isMap(source))
throw new Error("Merge sources must be maps or map aliases");
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value2] of srcMap) {
if (map3 instanceof Map) {
if (!map3.has(key))
map3.set(key, value2);
} else if (map3 instanceof Set) {
map3.add(key);
} else if (!Object.prototype.hasOwnProperty.call(map3, key)) {
Object.defineProperty(map3, key, {
value: value2,
writable: true,
enumerable: true,
configurable: true
});
}
}
return map3;
}
exports.addMergeToJSMap = addMergeToJSMap;
exports.isMergeKey = isMergeKey;
exports.merge = merge3;
});
// node_modules/yaml/dist/nodes/addPairToJSMap.js
var require_addPairToJSMap = __commonJS((exports) => {
var log2 = require_log();
var merge3 = require_merge();
var stringify = require_stringify();
var identity4 = require_identity();
var toJS = require_toJS();
function addPairToJSMap(ctx, map3, { key, value }) {
if (identity4.isNode(key) && key.addToJSMap)
key.addToJSMap(ctx, map3, value);
else if (merge3.isMergeKey(ctx, key))
merge3.addMergeToJSMap(ctx, map3, value);
else {
const jsKey = toJS.toJS(key, "", ctx);
if (map3 instanceof Map) {
map3.set(jsKey, toJS.toJS(value, jsKey, ctx));
} else if (map3 instanceof Set) {
map3.add(jsKey);
} else {
const stringKey = stringifyKey(key, jsKey, ctx);
const jsValue = toJS.toJS(value, stringKey, ctx);
if (stringKey in map3)
Object.defineProperty(map3, stringKey, {
value: jsValue,
writable: true,
enumerable: true,
configurable: true
});
else
map3[stringKey] = jsValue;
}
}
return map3;
}
function stringifyKey(key, jsKey, ctx) {
if (jsKey === null)
return "";
if (typeof jsKey !== "object")
return String(jsKey);
if (identity4.isNode(key) && ctx?.doc) {
const strCtx = stringify.createStringifyContext(ctx.doc, {});
strCtx.anchors = new Set;
for (const node of ctx.anchors.keys())
strCtx.anchors.add(node.anchor);
strCtx.inFlow = true;
strCtx.inStringifyKey = true;
const strKey = key.toString(strCtx);
if (!ctx.mapKeyWarned) {
let jsonStr = JSON.stringify(strKey);
if (jsonStr.length > 40)
jsonStr = jsonStr.substring(0, 36) + '..."';
log2.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
ctx.mapKeyWarned = true;
}
return strKey;
}
return JSON.stringify(jsKey);
}
exports.addPairToJSMap = addPairToJSMap;
});
// node_modules/yaml/dist/nodes/Pair.js
var require_Pair = __commonJS((exports) => {
var createNode2 = require_createNode();
var stringifyPair = require_stringifyPair();
var addPairToJSMap = require_addPairToJSMap();
var identity4 = require_identity();
function createPair(key, value, ctx) {
const k = createNode2.createNode(key, undefined, ctx);
const v = createNode2.createNode(value, undefined, ctx);
return new Pair(k, v);
}
class Pair {
constructor(key, value = null) {
Object.defineProperty(this, identity4.NODE_TYPE, { value: identity4.PAIR });
this.key = key;
this.value = value;
}
clone(schema) {
let { key, value } = this;
if (identity4.isNode(key))
key = key.clone(schema);
if (identity4.isNode(value))
value = value.clone(schema);
return new Pair(key, value);
}
toJSON(_, ctx) {
const pair = ctx?.mapAsMap ? new Map : {};
return addPairToJSMap.addPairToJSMap(ctx, pair, this);
}
toString(ctx, onComment, onChompKeep) {
return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
}
}
exports.Pair = Pair;
exports.createPair = createPair;
});
// node_modules/yaml/dist/stringify/stringifyCollection.js
var require_stringifyCollection = __commonJS((exports) => {
var identity4 = require_identity();
var stringify = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyCollection(collection, ctx, options) {
const flow = ctx.inFlow ?? collection.flow;
const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection;
return stringify2(collection, ctx, options);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
const { indent, options: { commentString } } = ctx;
const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
let chompKeep = false;
const lines = [];
for (let i2 = 0;i2 < items.length; ++i2) {
const item = items[i2];
let comment2 = null;
if (identity4.isNode(item)) {
if (!chompKeep && item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
if (item.comment)
comment2 = item.comment;
} else if (identity4.isPair(item)) {
const ik = identity4.isNode(item.key) ? item.key : null;
if (ik) {
if (!chompKeep && ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
}
}
chompKeep = false;
let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
if (comment2)
str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
if (chompKeep && comment2)
chompKeep = false;
lines.push(blockItemPrefix + str2);
}
let str;
if (lines.length === 0) {
str = flowChars.start + flowChars.end;
} else {
str = lines[0];
for (let i2 = 1;i2 < lines.length; ++i2) {
const line = lines[i2];
str += line ? `
${indent}${line}` : `
`;
}
}
if (comment) {
str += `
` + stringifyComment.indentComment(commentString(comment), indent);
if (onComment)
onComment();
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
itemIndent += indentStep;
const itemCtx = Object.assign({}, ctx, {
indent: itemIndent,
inFlow: true,
type: null
});
let reqNewline = false;
let linesAtValue = 0;
const lines = [];
for (let i2 = 0;i2 < items.length; ++i2) {
const item = items[i2];
let comment = null;
if (identity4.isNode(item)) {
if (item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, false);
if (item.comment)
comment = item.comment;
} else if (identity4.isPair(item)) {
const ik = identity4.isNode(item.key) ? item.key : null;
if (ik) {
if (ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, false);
if (ik.comment)
reqNewline = true;
}
const iv = identity4.isNode(item.value) ? item.value : null;
if (iv) {
if (iv.comment)
comment = iv.comment;
if (iv.commentBefore)
reqNewline = true;
} else if (item.value == null && ik?.comment) {
comment = ik.comment;
}
}
if (comment)
reqNewline = true;
let str = stringify.stringify(item, itemCtx, () => comment = null);
reqNewline || (reqNewline = lines.length > linesAtValue || str.includes(`
`));
if (i2 < items.length - 1) {
str += ",";
} else if (ctx.options.trailingComma) {
if (ctx.options.lineWidth > 0) {
reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth);
}
if (reqNewline) {
str += ",";
}
}
if (comment)
str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
lines.push(str);
linesAtValue = lines.length;
}
const { start, end } = flowChars;
if (lines.length === 0) {
return start + end;
} else {
if (!reqNewline) {
const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
}
if (reqNewline) {
let str = start;
for (const line of lines)
str += line ? `
${indentStep}${indent}${line}` : `
`;
return `${str}
${indent}${end}`;
} else {
return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
}
}
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
if (comment && chompKeep)
comment = comment.replace(/^\n+/, "");
if (comment) {
const ic = stringifyComment.indentComment(commentString(comment), indent);
lines.push(ic.trimStart());
}
}
exports.stringifyCollection = stringifyCollection;
});
// node_modules/yaml/dist/nodes/YAMLMap.js
var require_YAMLMap = __commonJS((exports) => {
var stringifyCollection = require_stringifyCollection();
var addPairToJSMap = require_addPairToJSMap();
var Collection = require_Collection();
var identity4 = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
function findPair(items, key) {
const k = identity4.isScalar(key) ? key.value : key;
for (const it of items) {
if (identity4.isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (identity4.isScalar(it.key) && it.key.value === k)
return it;
}
}
return;
}
class YAMLMap extends Collection.Collection {
static get tagName() {
return "tag:yaml.org,2002:map";
}
constructor(schema) {
super(identity4.MAP, schema);
this.items = [];
}
static from(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map3 = new this(schema);
const add = (key, value) => {
if (typeof replacer === "function")
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map3.items.push(Pair.createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
} else if (obj && typeof obj === "object") {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === "function") {
map3.items.sort(schema.sortMapEntries);
}
return map3;
}
add(pair, overwrite) {
let _pair;
if (identity4.isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== "object" || !("key" in pair)) {
_pair = new Pair.Pair(pair, pair?.value);
} else
_pair = new Pair.Pair(pair.key, pair.value);
const prev = findPair(this.items, _pair.key);
const sortEntries = this.schema?.sortMapEntries;
if (prev) {
if (!overwrite)
throw new Error(`Key ${_pair.key} already set`);
if (identity4.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
prev.value.value = _pair.value;
else
prev.value = _pair.value;
} else if (sortEntries) {
const i2 = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
if (i2 === -1)
this.items.push(_pair);
else
this.items.splice(i2, 0, _pair);
} else {
this.items.push(_pair);
}
}
delete(key) {
const it = findPair(this.items, key);
if (!it)
return false;
const del = this.items.splice(this.items.indexOf(it), 1);
return del.length > 0;
}
get(key, keepScalar) {
const it = findPair(this.items, key);
const node = it?.value;
return (!keepScalar && identity4.isScalar(node) ? node.value : node) ?? undefined;
}
has(key) {
return !!findPair(this.items, key);
}
set(key, value) {
this.add(new Pair.Pair(key, value), true);
}
toJSON(_, ctx, Type) {
const map3 = Type ? new Type : ctx?.mapAsMap ? new Map : {};
if (ctx?.onCreate)
ctx.onCreate(map3);
for (const item of this.items)
addPairToJSMap.addPairToJSMap(ctx, map3, item);
return map3;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!identity4.isPair(item))
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
}
if (!ctx.allNullValues && this.hasAllNullValues(false))
ctx = Object.assign({}, ctx, { allNullValues: true });
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: "",
flowChars: { start: "{", end: "}" },
itemIndent: ctx.indent || "",
onChompKeep,
onComment
});
}
}
exports.YAMLMap = YAMLMap;
exports.findPair = findPair;
});
// node_modules/yaml/dist/schema/common/map.js
var require_map = __commonJS((exports) => {
var identity4 = require_identity();
var YAMLMap = require_YAMLMap();
var map3 = {
collection: "map",
default: true,
nodeClass: YAMLMap.YAMLMap,
tag: "tag:yaml.org,2002:map",
resolve(map4, onError) {
if (!identity4.isMap(map4))
onError("Expected a mapping for this tag");
return map4;
},
createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
};
exports.map = map3;
});
// node_modules/yaml/dist/nodes/YAMLSeq.js
var require_YAMLSeq = __commonJS((exports) => {
var createNode2 = require_createNode();
var stringifyCollection = require_stringifyCollection();
var Collection = require_Collection();
var identity4 = require_identity();
var Scalar = require_Scalar();
var toJS = require_toJS();
class YAMLSeq extends Collection.Collection {
static get tagName() {
return "tag:yaml.org,2002:seq";
}
constructor(schema) {
super(identity4.SEQ, schema);
this.items = [];
}
add(value) {
this.items.push(value);
}
delete(key) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return false;
const del = this.items.splice(idx, 1);
return del.length > 0;
}
get(key, keepScalar) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return;
const it = this.items[idx];
return !keepScalar && identity4.isScalar(it) ? it.value : it;
}
has(key) {
const idx = asItemIndex(key);
return typeof idx === "number" && idx < this.items.length;
}
set(key, value) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (identity4.isScalar(prev) && Scalar.isScalarValue(value))
prev.value = value;
else
this.items[idx] = value;
}
toJSON(_, ctx) {
const seq = [];
if (ctx?.onCreate)
ctx.onCreate(seq);
let i2 = 0;
for (const item of this.items)
seq.push(toJS.toJS(item, String(i2++), ctx));
return seq;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: "- ",
flowChars: { start: "[", end: "]" },
itemIndent: (ctx.indent || "") + " ",
onChompKeep,
onComment
});
}
static from(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new this(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i2 = 0;
for (let it of obj) {
if (typeof replacer === "function") {
const key = obj instanceof Set ? it : String(i2++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode2.createNode(it, undefined, ctx));
}
}
return seq;
}
}
function asItemIndex(key) {
let idx = identity4.isScalar(key) ? key.value : key;
if (idx && typeof idx === "string")
idx = Number(idx);
return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}
exports.YAMLSeq = YAMLSeq;
});
// node_modules/yaml/dist/schema/common/seq.js
var require_seq = __commonJS((exports) => {
var identity4 = require_identity();
var YAMLSeq = require_YAMLSeq();
var seq = {
collection: "seq",
default: true,
nodeClass: YAMLSeq.YAMLSeq,
tag: "tag:yaml.org,2002:seq",
resolve(seq2, onError) {
if (!identity4.isSeq(seq2))
onError("Expected a sequence for this tag");
return seq2;
},
createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
};
exports.seq = seq;
});
// node_modules/yaml/dist/schema/common/string.js
var require_string = __commonJS((exports) => {
var stringifyString = require_stringifyString();
var string4 = {
identify: (value) => typeof value === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify(item, ctx, onComment, onChompKeep) {
ctx = Object.assign({ actualString: true }, ctx);
return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
}
};
exports.string = string4;
});
// node_modules/yaml/dist/schema/common/null.js
var require_null = __commonJS((exports) => {
var Scalar = require_Scalar();
var nullTag2 = {
identify: (value) => value == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^(?:~|[Nn]ull|NULL)?$/,
resolve: () => new Scalar.Scalar(null),
stringify: ({ source }, ctx) => typeof source === "string" && nullTag2.test.test(source) ? source : ctx.options.nullStr
};
exports.nullTag = nullTag2;
});
// node_modules/yaml/dist/schema/core/bool.js
var require_bool = __commonJS((exports) => {
var Scalar = require_Scalar();
var boolTag5 = {
identify: (value) => typeof value === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"),
stringify({ source, value }, ctx) {
if (source && boolTag5.test.test(source)) {
const sv = source[0] === "t" || source[0] === "T";
if (value === sv)
return source;
}
return value ? ctx.options.trueStr : ctx.options.falseStr;
}
};
exports.boolTag = boolTag5;
});
// node_modules/yaml/dist/stringify/stringifyNumber.js
var require_stringifyNumber = __commonJS((exports) => {
function stringifyNumber({ format: format4, minFractionDigits, tag, value }) {
if (typeof value === "bigint")
return String(value);
const num = typeof value === "number" ? value : Number(value);
if (!isFinite(num))
return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
let n2 = Object.is(value, -0) ? "-0" : JSON.stringify(value);
if (!format4 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n2)) {
let i2 = n2.indexOf(".");
if (i2 < 0) {
i2 = n2.length;
n2 += ".";
}
let d = minFractionDigits - (n2.length - i2 - 1);
while (d-- > 0)
n2 += "0";
}
return n2;
}
exports.stringifyNumber = stringifyNumber;
});
// node_modules/yaml/dist/schema/core/float.js
var require_float = __commonJS((exports) => {
var Scalar = require_Scalar();
var stringifyNumber = require_stringifyNumber();
var floatNaN = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
var floatExp = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
var float = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str));
const dot = str.indexOf(".");
if (dot !== -1 && str[str.length - 1] === "0")
node.minFractionDigits = str.length - dot - 1;
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports.float = float;
exports.floatExp = floatExp;
exports.floatNaN = floatNaN;
});
// node_modules/yaml/dist/schema/core/int.js
var require_int = __commonJS((exports) => {
var stringifyNumber = require_stringifyNumber();
var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
function intStringify(node, radix, prefix) {
const { value } = node;
if (intIdentify(value) && value >= 0)
return prefix + value.toString(radix);
return stringifyNumber.stringifyNumber(node);
}
var intOct = {
identify: (value) => intIdentify(value) && value >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^0o[0-7]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
stringify: (node) => intStringify(node, 8, "0o")
};
var int2 = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9]+$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
var intHex = {
identify: (value) => intIdentify(value) && value >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^0x[0-9a-fA-F]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: (node) => intStringify(node, 16, "0x")
};
exports.int = int2;
exports.intHex = intHex;
exports.intOct = intOct;
});
// node_modules/yaml/dist/schema/core/schema.js
var require_schema2 = __commonJS((exports) => {
var map3 = require_map();
var _null4 = require_null();
var seq = require_seq();
var string4 = require_string();
var bool = require_bool();
var float = require_float();
var int2 = require_int();
var schema = [
map3.map,
seq.seq,
string4.string,
_null4.nullTag,
bool.boolTag,
int2.intOct,
int2.int,
int2.intHex,
float.floatNaN,
float.floatExp,
float.float
];
exports.schema = schema;
});
// node_modules/yaml/dist/schema/json/schema.js
var require_schema3 = __commonJS((exports) => {
var Scalar = require_Scalar();
var map3 = require_map();
var seq = require_seq();
function intIdentify(value) {
return typeof value === "bigint" || Number.isInteger(value);
}
var stringifyJSON = ({ value }) => JSON.stringify(value);
var jsonScalars = [
{
identify: (value) => typeof value === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify: stringifyJSON
},
{
identify: (value) => value == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^null$/,
resolve: () => null,
stringify: stringifyJSON
},
{
identify: (value) => typeof value === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^true$|^false$/,
resolve: (str) => str === "true",
stringify: stringifyJSON
},
{
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^-?(?:0|[1-9][0-9]*)$/,
resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
},
{
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
resolve: (str) => parseFloat(str),
stringify: stringifyJSON
}
];
var jsonError = {
default: true,
tag: "",
test: /^/,
resolve(str, onError) {
onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
return str;
}
};
var schema = [map3.map, seq.seq].concat(jsonScalars, jsonError);
exports.schema = schema;
});
// node_modules/yaml/dist/schema/yaml-1.1/binary.js
var require_binary = __commonJS((exports) => {
var node_buffer = __require("buffer");
var Scalar = require_Scalar();
var stringifyString = require_stringifyString();
var binary = {
identify: (value) => value instanceof Uint8Array,
default: false,
tag: "tag:yaml.org,2002:binary",
resolve(src, onError) {
if (typeof node_buffer.Buffer === "function") {
return node_buffer.Buffer.from(src, "base64");
} else if (typeof atob === "function") {
const str = atob(src.replace(/[\n\r]/g, ""));
const buffer = new Uint8Array(str.length);
for (let i2 = 0;i2 < str.length; ++i2)
buffer[i2] = str.charCodeAt(i2);
return buffer;
} else {
onError("This environment does not support reading binary tags; either Buffer or atob is required");
return src;
}
},
stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
if (!value)
return "";
const buf = value;
let str;
if (typeof node_buffer.Buffer === "function") {
str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64");
} else if (typeof btoa === "function") {
let s = "";
for (let i2 = 0;i2 < buf.length; ++i2)
s += String.fromCharCode(buf[i2]);
str = btoa(s);
} else {
throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
}
type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
const lineWidth2 = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
const n2 = Math.ceil(str.length / lineWidth2);
const lines = new Array(n2);
for (let i2 = 0, o2 = 0;i2 < n2; ++i2, o2 += lineWidth2) {
lines[i2] = str.substr(o2, lineWidth2);
}
str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? `
` : " ");
}
return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
}
};
exports.binary = binary;
});
// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
var require_pairs = __commonJS((exports) => {
var identity4 = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
var YAMLSeq = require_YAMLSeq();
function resolvePairs(seq, onError) {
if (identity4.isSeq(seq)) {
for (let i2 = 0;i2 < seq.items.length; ++i2) {
let item = seq.items[i2];
if (identity4.isPair(item))
continue;
else if (identity4.isMap(item)) {
if (item.items.length > 1)
onError("Each pair must have its own sequence indicator");
const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
if (item.commentBefore)
pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
if (item.comment) {
const cn = pair.value ?? pair.key;
cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
}
item = pair;
}
seq.items[i2] = identity4.isPair(item) ? item : new Pair.Pair(item);
}
} else
onError("Expected a sequence for this tag");
return seq;
}
function createPairs(schema, iterable, ctx) {
const { replacer } = ctx;
const pairs2 = new YAMLSeq.YAMLSeq(schema);
pairs2.tag = "tag:yaml.org,2002:pairs";
let i2 = 0;
if (iterable && Symbol.iterator in Object(iterable))
for (let it of iterable) {
if (typeof replacer === "function")
it = replacer.call(iterable, String(i2++), it);
let key, value;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value = it[1];
} else
throw new TypeError(`Expected [key, value] tuple: ${it}`);
} else if (it && it instanceof Object) {
const keys2 = Object.keys(it);
if (keys2.length === 1) {
key = keys2[0];
value = it[key];
} else {
throw new TypeError(`Expected tuple with one key, not ${keys2.length} keys`);
}
} else {
key = it;
}
pairs2.items.push(Pair.createPair(key, value, ctx));
}
return pairs2;
}
var pairs = {
collection: "seq",
default: false,
tag: "tag:yaml.org,2002:pairs",
resolve: resolvePairs,
createNode: createPairs
};
exports.createPairs = createPairs;
exports.pairs = pairs;
exports.resolvePairs = resolvePairs;
});
// node_modules/yaml/dist/schema/yaml-1.1/omap.js
var require_omap = __commonJS((exports) => {
var identity4 = require_identity();
var toJS = require_toJS();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var pairs = require_pairs();
class YAMLOMap extends YAMLSeq.YAMLSeq {
constructor() {
super();
this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
this.tag = YAMLOMap.tag;
}
toJSON(_, ctx) {
if (!ctx)
return super.toJSON(_);
const map3 = new Map;
if (ctx?.onCreate)
ctx.onCreate(map3);
for (const pair of this.items) {
let key, value;
if (identity4.isPair(pair)) {
key = toJS.toJS(pair.key, "", ctx);
value = toJS.toJS(pair.value, key, ctx);
} else {
key = toJS.toJS(pair, "", ctx);
}
if (map3.has(key))
throw new Error("Ordered maps must not include duplicate keys");
map3.set(key, value);
}
return map3;
}
static from(schema, iterable, ctx) {
const pairs$1 = pairs.createPairs(schema, iterable, ctx);
const omap2 = new this;
omap2.items = pairs$1.items;
return omap2;
}
}
YAMLOMap.tag = "tag:yaml.org,2002:omap";
var omap = {
collection: "seq",
identify: (value) => value instanceof Map,
nodeClass: YAMLOMap,
default: false,
tag: "tag:yaml.org,2002:omap",
resolve(seq, onError) {
const pairs$1 = pairs.resolvePairs(seq, onError);
const seenKeys = [];
for (const { key } of pairs$1.items) {
if (identity4.isScalar(key)) {
if (seenKeys.includes(key.value)) {
onError(`Ordered maps must not include duplicate keys: ${key.value}`);
} else {
seenKeys.push(key.value);
}
}
}
return Object.assign(new YAMLOMap, pairs$1);
},
createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
};
exports.YAMLOMap = YAMLOMap;
exports.omap = omap;
});
// node_modules/yaml/dist/schema/yaml-1.1/bool.js
var require_bool2 = __commonJS((exports) => {
var Scalar = require_Scalar();
function boolStringify({ value, source }, ctx) {
const boolObj = value ? trueTag : falseTag;
if (source && boolObj.test.test(source))
return source;
return value ? ctx.options.trueStr : ctx.options.falseStr;
}
var trueTag = {
identify: (value) => value === true,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
resolve: () => new Scalar.Scalar(true),
stringify: boolStringify
};
var falseTag = {
identify: (value) => value === false,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
resolve: () => new Scalar.Scalar(false),
stringify: boolStringify
};
exports.falseTag = falseTag;
exports.trueTag = trueTag;
});
// node_modules/yaml/dist/schema/yaml-1.1/float.js
var require_float2 = __commonJS((exports) => {
var Scalar = require_Scalar();
var stringifyNumber = require_stringifyNumber();
var floatNaN = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
var floatExp = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str.replace(/_/g, "")),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
var float = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, "")));
const dot = str.indexOf(".");
if (dot !== -1) {
const f = str.substring(dot + 1).replace(/_/g, "");
if (f[f.length - 1] === "0")
node.minFractionDigits = f.length;
}
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports.float = float;
exports.floatExp = floatExp;
exports.floatNaN = floatNaN;
});
// node_modules/yaml/dist/schema/yaml-1.1/int.js
var require_int2 = __commonJS((exports) => {
var stringifyNumber = require_stringifyNumber();
var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
function intResolve(str, offset, radix, { intAsBigInt }) {
const sign = str[0];
if (sign === "-" || sign === "+")
offset += 1;
str = str.substring(offset).replace(/_/g, "");
if (intAsBigInt) {
switch (radix) {
case 2:
str = `0b${str}`;
break;
case 8:
str = `0o${str}`;
break;
case 16:
str = `0x${str}`;
break;
}
const n3 = BigInt(str);
return sign === "-" ? BigInt(-1) * n3 : n3;
}
const n2 = parseInt(str, radix);
return sign === "-" ? -1 * n2 : n2;
}
function intStringify(node, radix, prefix) {
const { value } = node;
if (intIdentify(value)) {
const str = value.toString(radix);
return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
}
return stringifyNumber.stringifyNumber(node);
}
var intBin = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "BIN",
test: /^[-+]?0b[0-1_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
stringify: (node) => intStringify(node, 2, "0b")
};
var intOct = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^[-+]?0[0-7_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
stringify: (node) => intStringify(node, 8, "0")
};
var int2 = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9][0-9_]*$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
var intHex = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^[-+]?0x[0-9a-fA-F_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: (node) => intStringify(node, 16, "0x")
};
exports.int = int2;
exports.intBin = intBin;
exports.intHex = intHex;
exports.intOct = intOct;
});
// node_modules/yaml/dist/schema/yaml-1.1/set.js
var require_set = __commonJS((exports) => {
var identity4 = require_identity();
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
class YAMLSet extends YAMLMap.YAMLMap {
constructor(schema) {
super(schema);
this.tag = YAMLSet.tag;
}
add(key) {
let pair;
if (identity4.isPair(key))
pair = key;
else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
pair = new Pair.Pair(key.key, null);
else
pair = new Pair.Pair(key, null);
const prev = YAMLMap.findPair(this.items, pair.key);
if (!prev)
this.items.push(pair);
}
get(key, keepPair) {
const pair = YAMLMap.findPair(this.items, key);
return !keepPair && identity4.isPair(pair) ? identity4.isScalar(pair.key) ? pair.key.value : pair.key : pair;
}
set(key, value) {
if (typeof value !== "boolean")
throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
const prev = YAMLMap.findPair(this.items, key);
if (prev && !value) {
this.items.splice(this.items.indexOf(prev), 1);
} else if (!prev && value) {
this.items.push(new Pair.Pair(key));
}
}
toJSON(_, ctx) {
return super.toJSON(_, ctx, Set);
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
if (this.hasAllNullValues(true))
return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
else
throw new Error("Set items must all have null values");
}
static from(schema, iterable, ctx) {
const { replacer } = ctx;
const set3 = new this(schema);
if (iterable && Symbol.iterator in Object(iterable))
for (let value of iterable) {
if (typeof replacer === "function")
value = replacer.call(iterable, value, value);
set3.items.push(Pair.createPair(value, null, ctx));
}
return set3;
}
}
YAMLSet.tag = "tag:yaml.org,2002:set";
var set2 = {
collection: "map",
identify: (value) => value instanceof Set,
nodeClass: YAMLSet,
default: false,
tag: "tag:yaml.org,2002:set",
createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
resolve(map3, onError) {
if (identity4.isMap(map3)) {
if (map3.hasAllNullValues(true))
return Object.assign(new YAMLSet, map3);
else
onError("Set items must all have null values");
} else
onError("Expected a mapping for this tag");
return map3;
}
};
exports.YAMLSet = YAMLSet;
exports.set = set2;
});
// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
var require_timestamp = __commonJS((exports) => {
var stringifyNumber = require_stringifyNumber();
function parseSexagesimal(str, asBigInt) {
const sign = str[0];
const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
const num = (n2) => asBigInt ? BigInt(n2) : Number(n2);
const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
return sign === "-" ? num(-1) * res : res;
}
function stringifySexagesimal(node) {
let { value } = node;
let num = (n2) => n2;
if (typeof value === "bigint")
num = (n2) => BigInt(n2);
else if (isNaN(value) || !isFinite(value))
return stringifyNumber.stringifyNumber(node);
let sign = "";
if (value < 0) {
sign = "-";
value *= num(-1);
}
const _60 = num(60);
const parts = [value % _60];
if (value < 60) {
parts.unshift(0);
} else {
value = (value - parts[0]) / _60;
parts.unshift(value % _60);
if (value >= 60) {
value = (value - parts[0]) / _60;
parts.unshift(value);
}
}
return sign + parts.map((n2) => String(n2).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
}
var intTime = {
identify: (value) => typeof value === "bigint" || Number.isInteger(value),
default: true,
tag: "tag:yaml.org,2002:int",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
stringify: stringifySexagesimal
};
var floatTime = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
resolve: (str) => parseSexagesimal(str, false),
stringify: stringifySexagesimal
};
var timestamp = {
identify: (value) => value instanceof Date,
default: true,
tag: "tag:yaml.org,2002:timestamp",
test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})" + "(?:" + "(?:t|T|[ \\t]+)" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)" + "(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?" + ")?$"),
resolve(str) {
const match = str.match(timestamp.test);
if (!match)
throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
const [, year, month, day, hour, minute, second] = match.map(Number);
const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
let date5 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
const tz = match[8];
if (tz && tz !== "Z") {
let d = parseSexagesimal(tz, false);
if (Math.abs(d) < 30)
d *= 60;
date5 -= 60000 * d;
}
return new Date(date5);
},
stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
};
exports.floatTime = floatTime;
exports.intTime = intTime;
exports.timestamp = timestamp;
});
// node_modules/yaml/dist/schema/yaml-1.1/schema.js
var require_schema4 = __commonJS((exports) => {
var map3 = require_map();
var _null4 = require_null();
var seq = require_seq();
var string4 = require_string();
var binary = require_binary();
var bool = require_bool2();
var float = require_float2();
var int2 = require_int2();
var merge3 = require_merge();
var omap = require_omap();
var pairs = require_pairs();
var set2 = require_set();
var timestamp = require_timestamp();
var schema = [
map3.map,
seq.seq,
string4.string,
_null4.nullTag,
bool.trueTag,
bool.falseTag,
int2.intBin,
int2.intOct,
int2.int,
int2.intHex,
float.floatNaN,
float.floatExp,
float.float,
binary.binary,
merge3.merge,
omap.omap,
pairs.pairs,
set2.set,
timestamp.intTime,
timestamp.floatTime,
timestamp.timestamp
];
exports.schema = schema;
});
// node_modules/yaml/dist/schema/tags.js
var require_tags = __commonJS((exports) => {
var map3 = require_map();
var _null4 = require_null();
var seq = require_seq();
var string4 = require_string();
var bool = require_bool();
var float = require_float();
var int2 = require_int();
var schema = require_schema2();
var schema$1 = require_schema3();
var binary = require_binary();
var merge3 = require_merge();
var omap = require_omap();
var pairs = require_pairs();
var schema$2 = require_schema4();
var set2 = require_set();
var timestamp = require_timestamp();
var schemas3 = new Map([
["core", schema.schema],
["failsafe", [map3.map, seq.seq, string4.string]],
["json", schema$1.schema],
["yaml11", schema$2.schema],
["yaml-1.1", schema$2.schema]
]);
var tagsByName = {
binary: binary.binary,
bool: bool.boolTag,
float: float.float,
floatExp: float.floatExp,
floatNaN: float.floatNaN,
floatTime: timestamp.floatTime,
int: int2.int,
intHex: int2.intHex,
intOct: int2.intOct,
intTime: timestamp.intTime,
map: map3.map,
merge: merge3.merge,
null: _null4.nullTag,
omap: omap.omap,
pairs: pairs.pairs,
seq: seq.seq,
set: set2.set,
timestamp: timestamp.timestamp
};
var coreKnownTags = {
"tag:yaml.org,2002:binary": binary.binary,
"tag:yaml.org,2002:merge": merge3.merge,
"tag:yaml.org,2002:omap": omap.omap,
"tag:yaml.org,2002:pairs": pairs.pairs,
"tag:yaml.org,2002:set": set2.set,
"tag:yaml.org,2002:timestamp": timestamp.timestamp
};
function getTags(customTags, schemaName, addMergeTag) {
const schemaTags = schemas3.get(schemaName);
if (schemaTags && !customTags) {
return addMergeTag && !schemaTags.includes(merge3.merge) ? schemaTags.concat(merge3.merge) : schemaTags.slice();
}
let tags = schemaTags;
if (!tags) {
if (Array.isArray(customTags))
tags = [];
else {
const keys2 = Array.from(schemas3.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown schema "${schemaName}"; use one of ${keys2} or define customTags array`);
}
}
if (Array.isArray(customTags)) {
for (const tag of customTags)
tags = tags.concat(tag);
} else if (typeof customTags === "function") {
tags = customTags(tags.slice());
}
if (addMergeTag)
tags = tags.concat(merge3.merge);
return tags.reduce((tags2, tag) => {
const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
if (!tagObj) {
const tagName = JSON.stringify(tag);
const keys2 = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown custom tag ${tagName}; use one of ${keys2}`);
}
if (!tags2.includes(tagObj))
tags2.push(tagObj);
return tags2;
}, []);
}
exports.coreKnownTags = coreKnownTags;
exports.getTags = getTags;
});
// node_modules/yaml/dist/schema/Schema.js
var require_Schema = __commonJS((exports) => {
var identity4 = require_identity();
var map3 = require_map();
var seq = require_seq();
var string4 = require_string();
var tags = require_tags();
var sortMapEntriesByKey = (a2, b) => a2.key < b.key ? -1 : a2.key > b.key ? 1 : 0;
class Schema {
constructor({ compat: compat2, customTags, merge: merge3, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
this.compat = Array.isArray(compat2) ? tags.getTags(compat2, "compat") : compat2 ? tags.getTags(null, compat2) : null;
this.name = typeof schema === "string" && schema || "core";
this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
this.tags = tags.getTags(customTags, this.name, merge3);
this.toStringOptions = toStringDefaults ?? null;
Object.defineProperty(this, identity4.MAP, { value: map3.map });
Object.defineProperty(this, identity4.SCALAR, { value: string4.string });
Object.defineProperty(this, identity4.SEQ, { value: seq.seq });
this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
}
clone() {
const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
copy.tags = this.tags.slice();
return copy;
}
}
exports.Schema = Schema;
});
// node_modules/yaml/dist/stringify/stringifyDocument.js
var require_stringifyDocument = __commonJS((exports) => {
var identity4 = require_identity();
var stringify = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyDocument(doc2, options) {
const lines = [];
let hasDirectives = options.directives === true;
if (options.directives !== false && doc2.directives) {
const dir = doc2.directives.toString(doc2);
if (dir) {
lines.push(dir);
hasDirectives = true;
} else if (doc2.directives.docStart)
hasDirectives = true;
}
if (hasDirectives)
lines.push("---");
const ctx = stringify.createStringifyContext(doc2, options);
const { commentString } = ctx.options;
if (doc2.commentBefore) {
if (lines.length !== 1)
lines.unshift("");
const cs = commentString(doc2.commentBefore);
lines.unshift(stringifyComment.indentComment(cs, ""));
}
let chompKeep = false;
let contentComment = null;
if (doc2.contents) {
if (identity4.isNode(doc2.contents)) {
if (doc2.contents.spaceBefore && hasDirectives)
lines.push("");
if (doc2.contents.commentBefore) {
const cs = commentString(doc2.contents.commentBefore);
lines.push(stringifyComment.indentComment(cs, ""));
}
ctx.forceBlockIndent = !!doc2.comment;
contentComment = doc2.contents.comment;
}
const onChompKeep = contentComment ? undefined : () => chompKeep = true;
let body = stringify.stringify(doc2.contents, ctx, () => contentComment = null, onChompKeep);
if (contentComment)
body += stringifyComment.lineComment(body, "", commentString(contentComment));
if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
lines[lines.length - 1] = `--- ${body}`;
} else
lines.push(body);
} else {
lines.push(stringify.stringify(doc2.contents, ctx));
}
if (doc2.directives?.docEnd) {
if (doc2.comment) {
const cs = commentString(doc2.comment);
if (cs.includes(`
`)) {
lines.push("...");
lines.push(stringifyComment.indentComment(cs, ""));
} else {
lines.push(`... ${cs}`);
}
} else {
lines.push("...");
}
} else {
let dc = doc2.comment;
if (dc && chompKeep)
dc = dc.replace(/^\n+/, "");
if (dc) {
if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
lines.push("");
lines.push(stringifyComment.indentComment(commentString(dc), ""));
}
}
return lines.join(`
`) + `
`;
}
exports.stringifyDocument = stringifyDocument;
});
// node_modules/yaml/dist/doc/Document.js
var require_Document = __commonJS((exports) => {
var Alias = require_Alias();
var Collection = require_Collection();
var identity4 = require_identity();
var Pair = require_Pair();
var toJS = require_toJS();
var Schema = require_Schema();
var stringifyDocument = require_stringifyDocument();
var anchors = require_anchors();
var applyReviver = require_applyReviver();
var createNode2 = require_createNode();
var directives = require_directives();
class Document {
constructor(value, replacer, options) {
this.commentBefore = null;
this.comment = null;
this.errors = [];
this.warnings = [];
Object.defineProperty(this, identity4.NODE_TYPE, { value: identity4.DOC });
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options === undefined && replacer) {
options = replacer;
replacer = undefined;
}
const opt = Object.assign({
intAsBigInt: false,
keepSourceTokens: false,
logLevel: "warn",
prettyErrors: true,
strict: true,
stringKeys: false,
uniqueKeys: true,
version: "1.2"
}, options);
this.options = opt;
let { version: version2 } = opt;
if (options?._directives) {
this.directives = options._directives.atDocument();
if (this.directives.yaml.explicit)
version2 = this.directives.yaml.version;
} else
this.directives = new directives.Directives({ version: version2 });
this.setSchema(version2, options);
this.contents = value === undefined ? null : this.createNode(value, _replacer, options);
}
clone() {
const copy = Object.create(Document.prototype, {
[identity4.NODE_TYPE]: { value: identity4.DOC }
});
copy.commentBefore = this.commentBefore;
copy.comment = this.comment;
copy.errors = this.errors.slice();
copy.warnings = this.warnings.slice();
copy.options = Object.assign({}, this.options);
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
copy.contents = identity4.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
if (this.range)
copy.range = this.range.slice();
return copy;
}
add(value) {
if (assertCollection(this.contents))
this.contents.add(value);
}
addIn(path10, value) {
if (assertCollection(this.contents))
this.contents.addIn(path10, value);
}
createAlias(node, name) {
if (!node.anchor) {
const prev = anchors.anchorNames(this);
node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name;
}
return new Alias.Alias(node.anchor);
}
createNode(value, replacer, options) {
let _replacer = undefined;
if (typeof replacer === "function") {
value = replacer.call({ "": value }, "", value);
_replacer = replacer;
} else if (Array.isArray(replacer)) {
const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
const asStr = replacer.filter(keyToStr).map(String);
if (asStr.length > 0)
replacer = replacer.concat(asStr);
_replacer = replacer;
} else if (options === undefined && replacer) {
options = replacer;
replacer = undefined;
}
const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a");
const ctx = {
aliasDuplicateObjects: aliasDuplicateObjects ?? true,
keepUndefined: keepUndefined ?? false,
onAnchor,
onTagObj,
replacer: _replacer,
schema: this.schema,
sourceObjects
};
const node = createNode2.createNode(value, tag, ctx);
if (flow && identity4.isCollection(node))
node.flow = true;
setAnchors();
return node;
}
createPair(key, value, options = {}) {
const k = this.createNode(key, null, options);
const v = this.createNode(value, null, options);
return new Pair.Pair(k, v);
}
delete(key) {
return assertCollection(this.contents) ? this.contents.delete(key) : false;
}
deleteIn(path10) {
if (Collection.isEmptyPath(path10)) {
if (this.contents == null)
return false;
this.contents = null;
return true;
}
return assertCollection(this.contents) ? this.contents.deleteIn(path10) : false;
}
get(key, keepScalar) {
return identity4.isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined;
}
getIn(path10, keepScalar) {
if (Collection.isEmptyPath(path10))
return !keepScalar && identity4.isScalar(this.contents) ? this.contents.value : this.contents;
return identity4.isCollection(this.contents) ? this.contents.getIn(path10, keepScalar) : undefined;
}
has(key) {
return identity4.isCollection(this.contents) ? this.contents.has(key) : false;
}
hasIn(path10) {
if (Collection.isEmptyPath(path10))
return this.contents !== undefined;
return identity4.isCollection(this.contents) ? this.contents.hasIn(path10) : false;
}
set(key, value) {
if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, [key], value);
} else if (assertCollection(this.contents)) {
this.contents.set(key, value);
}
}
setIn(path10, value) {
if (Collection.isEmptyPath(path10)) {
this.contents = value;
} else if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, Array.from(path10), value);
} else if (assertCollection(this.contents)) {
this.contents.setIn(path10, value);
}
}
setSchema(version2, options = {}) {
if (typeof version2 === "number")
version2 = String(version2);
let opt;
switch (version2) {
case "1.1":
if (this.directives)
this.directives.yaml.version = "1.1";
else
this.directives = new directives.Directives({ version: "1.1" });
opt = { resolveKnownTags: false, schema: "yaml-1.1" };
break;
case "1.2":
case "next":
if (this.directives)
this.directives.yaml.version = version2;
else
this.directives = new directives.Directives({ version: version2 });
opt = { resolveKnownTags: true, schema: "core" };
break;
case null:
if (this.directives)
delete this.directives;
opt = null;
break;
default: {
const sv = JSON.stringify(version2);
throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
}
}
if (options.schema instanceof Object)
this.schema = options.schema;
else if (opt)
this.schema = new Schema.Schema(Object.assign(opt, options));
else
throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
}
toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
const ctx = {
anchors: new Map,
doc: this,
keep: !json2,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
if (typeof onAnchor === "function")
for (const { count: count3, res: res2 } of ctx.anchors.values())
onAnchor(res2, count3);
return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
}
toJSON(jsonArg, onAnchor) {
return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
}
toString(options = {}) {
if (this.errors.length > 0)
throw new Error("Document with errors cannot be stringified");
if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
const s = JSON.stringify(options.indent);
throw new Error(`"indent" option must be a positive integer, not ${s}`);
}
return stringifyDocument.stringifyDocument(this, options);
}
}
function assertCollection(contents) {
if (identity4.isCollection(contents))
return true;
throw new Error("Expected a YAML collection as document contents");
}
exports.Document = Document;
});
// node_modules/yaml/dist/errors.js
var require_errors6 = __commonJS((exports) => {
class YAMLError extends Error {
constructor(name, pos, code, message) {
super();
this.name = name;
this.code = code;
this.message = message;
this.pos = pos;
}
}
class YAMLParseError extends YAMLError {
constructor(pos, code, message) {
super("YAMLParseError", pos, code, message);
}
}
class YAMLWarning extends YAMLError {
constructor(pos, code, message) {
super("YAMLWarning", pos, code, message);
}
}
var prettifyError2 = (src, lc) => (error44) => {
if (error44.pos[0] === -1)
return;
error44.linePos = error44.pos.map((pos) => lc.linePos(pos));
const { line, col } = error44.linePos[0];
error44.message += ` at line ${line}, column ${col}`;
let ci = col - 1;
let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
if (ci >= 60 && lineStr.length > 80) {
const trimStart = Math.min(ci - 39, lineStr.length - 79);
lineStr = "…" + lineStr.substring(trimStart);
ci -= trimStart - 1;
}
if (lineStr.length > 80)
lineStr = lineStr.substring(0, 79) + "…";
if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
if (prev.length > 80)
prev = prev.substring(0, 79) + `…
`;
lineStr = prev + lineStr;
}
if (/[^ ]/.test(lineStr)) {
let count3 = 1;
const end = error44.linePos[1];
if (end?.line === line && end.col > col) {
count3 = Math.max(1, Math.min(end.col - col, 80 - ci));
}
const pointer = " ".repeat(ci) + "^".repeat(count3);
error44.message += `:
${lineStr}
${pointer}
`;
}
};
exports.YAMLError = YAMLError;
exports.YAMLParseError = YAMLParseError;
exports.YAMLWarning = YAMLWarning;
exports.prettifyError = prettifyError2;
});
// node_modules/yaml/dist/compose/resolve-props.js
var require_resolve_props = __commonJS((exports) => {
function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
let spaceBefore = false;
let atNewline = startOnNewline;
let hasSpace = startOnNewline;
let comment = "";
let commentSep = "";
let hasNewline = false;
let reqSpace = false;
let tab = null;
let anchor = null;
let tag = null;
let newlineAfterProp = null;
let comma = null;
let found = null;
let start = null;
for (const token of tokens) {
if (reqSpace) {
if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
reqSpace = false;
}
if (tab) {
if (atNewline && token.type !== "comment" && token.type !== "newline") {
onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
}
tab = null;
}
switch (token.type) {
case "space":
if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("\t")) {
tab = token;
}
hasSpace = true;
break;
case "comment": {
if (!hasSpace)
onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = token.source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += commentSep + cb;
commentSep = "";
atNewline = false;
break;
}
case "newline":
if (atNewline) {
if (comment)
comment += token.source;
else if (!found || indicator !== "seq-item-ind")
spaceBefore = true;
} else
commentSep += token.source;
atNewline = true;
hasNewline = true;
if (anchor || tag)
newlineAfterProp = token;
hasSpace = true;
break;
case "anchor":
if (anchor)
onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
if (token.source.endsWith(":"))
onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
anchor = token;
start ?? (start = token.offset);
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
case "tag": {
if (tag)
onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
tag = token;
start ?? (start = token.offset);
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
}
case indicator:
if (anchor || tag)
onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
if (found)
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
found = token;
atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
hasSpace = false;
break;
case "comma":
if (flow) {
if (comma)
onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
comma = token;
atNewline = false;
hasSpace = false;
break;
}
default:
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
atNewline = false;
hasSpace = false;
}
}
const last2 = tokens[tokens.length - 1];
const end = last2 ? last2.offset + last2.source.length : offset;
if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
}
if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
return {
comma,
found,
spaceBefore,
comment,
hasNewline,
anchor,
tag,
newlineAfterProp,
end,
start: start ?? end
};
}
exports.resolveProps = resolveProps;
});
// node_modules/yaml/dist/compose/util-contains-newline.js
var require_util_contains_newline = __commonJS((exports) => {
function containsNewline(key) {
if (!key)
return null;
switch (key.type) {
case "alias":
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
if (key.source.includes(`
`))
return true;
if (key.end) {
for (const st of key.end)
if (st.type === "newline")
return true;
}
return false;
case "flow-collection":
for (const it of key.items) {
for (const st of it.start)
if (st.type === "newline")
return true;
if (it.sep) {
for (const st of it.sep)
if (st.type === "newline")
return true;
}
if (containsNewline(it.key) || containsNewline(it.value))
return true;
}
return false;
default:
return true;
}
}
exports.containsNewline = containsNewline;
});
// node_modules/yaml/dist/compose/util-flow-indent-check.js
var require_util_flow_indent_check = __commonJS((exports) => {
var utilContainsNewline = require_util_contains_newline();
function flowIndentCheck(indent, fc, onError) {
if (fc?.type === "flow-collection") {
const end = fc.end[0];
if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
const msg = "Flow end indicator should be more indented than parent";
onError(end, "BAD_INDENT", msg, true);
}
}
}
exports.flowIndentCheck = flowIndentCheck;
});
// node_modules/yaml/dist/compose/util-map-includes.js
var require_util_map_includes = __commonJS((exports) => {
var identity4 = require_identity();
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;
if (uniqueKeys === false)
return false;
const isEqual2 = typeof uniqueKeys === "function" ? uniqueKeys : (a2, b) => a2 === b || identity4.isScalar(a2) && identity4.isScalar(b) && a2.value === b.value;
return items.some((pair) => isEqual2(pair.key, search));
}
exports.mapIncludes = mapIncludes;
});
// node_modules/yaml/dist/compose/resolve-block-map.js
var require_resolve_block_map = __commonJS((exports) => {
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var resolveProps = require_resolve_props();
var utilContainsNewline = require_util_contains_newline();
var utilFlowIndentCheck = require_util_flow_indent_check();
var utilMapIncludes = require_util_map_includes();
var startColMsg = "All mapping items must start at the same column";
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
const map3 = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bm.offset;
let commentEnd = null;
for (const collItem of bm.items) {
const { start, key, sep: sep6, value } = collItem;
const keyProps = resolveProps.resolveProps(start, {
indicator: "explicit-key-ind",
next: key ?? sep6?.[0],
offset,
onError,
parentIndent: bm.indent,
startOnNewline: true
});
const implicitKey = !keyProps.found;
if (implicitKey) {
if (key) {
if (key.type === "block-seq")
onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
else if ("indent" in key && key.indent !== bm.indent)
onError(offset, "BAD_INDENT", startColMsg);
}
if (!keyProps.anchor && !keyProps.tag && !sep6) {
commentEnd = keyProps.end;
if (keyProps.comment) {
if (map3.comment)
map3.comment += `
` + keyProps.comment;
else
map3.comment = keyProps.comment;
}
continue;
}
if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
}
} else if (keyProps.found?.indent !== bm.indent) {
onError(offset, "BAD_INDENT", startColMsg);
}
ctx.atKey = true;
const keyStart = keyProps.end;
const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
ctx.atKey = false;
if (utilMapIncludes.mapIncludes(ctx, map3.items, keyNode))
onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
const valueProps = resolveProps.resolveProps(sep6 ?? [], {
indicator: "map-value-ind",
next: value,
offset: keyNode.range[2],
onError,
parentIndent: bm.indent,
startOnNewline: !key || key.type === "block-scalar"
});
offset = valueProps.end;
if (valueProps.found) {
if (implicitKey) {
if (value?.type === "block-map" && !valueProps.hasNewline)
onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
}
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep6, null, valueProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
offset = valueNode.range[2];
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map3.items.push(pair);
} else {
if (implicitKey)
onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += `
` + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map3.items.push(pair);
}
}
if (commentEnd && commentEnd < offset)
onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
map3.range = [bm.offset, offset, commentEnd ?? offset];
return map3;
}
exports.resolveBlockMap = resolveBlockMap;
});
// node_modules/yaml/dist/compose/resolve-block-seq.js
var require_resolve_block_seq = __commonJS((exports) => {
var YAMLSeq = require_YAMLSeq();
var resolveProps = require_resolve_props();
var utilFlowIndentCheck = require_util_flow_indent_check();
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
const seq = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
if (ctx.atKey)
ctx.atKey = false;
let offset = bs.offset;
let commentEnd = null;
for (const { start, value } of bs.items) {
const props = resolveProps.resolveProps(start, {
indicator: "seq-item-ind",
next: value,
offset,
onError,
parentIndent: bs.indent,
startOnNewline: true
});
if (!props.found) {
if (props.anchor || props.tag || value) {
if (value?.type === "block-seq")
onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
else
onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
} else {
commentEnd = props.end;
if (props.comment)
seq.comment = props.comment;
continue;
}
}
const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
offset = node.range[2];
seq.items.push(node);
}
seq.range = [bs.offset, offset, commentEnd ?? offset];
return seq;
}
exports.resolveBlockSeq = resolveBlockSeq;
});
// node_modules/yaml/dist/compose/resolve-end.js
var require_resolve_end = __commonJS((exports) => {
function resolveEnd(end, offset, reqSpace, onError) {
let comment = "";
if (end) {
let hasSpace = false;
let sep6 = "";
for (const token of end) {
const { source, type } = token;
switch (type) {
case "space":
hasSpace = true;
break;
case "comment": {
if (reqSpace && !hasSpace)
onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += sep6 + cb;
sep6 = "";
break;
}
case "newline":
if (comment)
sep6 += source;
hasSpace = true;
break;
default:
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
}
offset += source.length;
}
}
return { comment, offset };
}
exports.resolveEnd = resolveEnd;
});
// node_modules/yaml/dist/compose/resolve-flow-collection.js
var require_resolve_flow_collection = __commonJS((exports) => {
var identity4 = require_identity();
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var resolveEnd = require_resolve_end();
var resolveProps = require_resolve_props();
var utilContainsNewline = require_util_contains_newline();
var utilMapIncludes = require_util_map_includes();
var blockMsg = "Block collections are not allowed within flow collections";
var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
const isMap2 = fc.start.source === "{";
const fcName = isMap2 ? "flow map" : "flow sequence";
const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
const coll = new NodeClass(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)
ctx.atRoot = false;
if (ctx.atKey)
ctx.atKey = false;
let offset = fc.offset + fc.start.source.length;
for (let i2 = 0;i2 < fc.items.length; ++i2) {
const collItem = fc.items[i2];
const { start, key, sep: sep6, value } = collItem;
const props = resolveProps.resolveProps(start, {
flow: fcName,
indicator: "explicit-key-ind",
next: key ?? sep6?.[0],
offset,
onError,
parentIndent: fc.indent,
startOnNewline: false
});
if (!props.found) {
if (!props.anchor && !props.tag && !sep6 && !value) {
if (i2 === 0 && props.comma)
onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
else if (i2 < fc.items.length - 1)
onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
if (props.comment) {
if (coll.comment)
coll.comment += `
` + props.comment;
else
coll.comment = props.comment;
}
offset = props.end;
continue;
}
if (!isMap2 && ctx.options.strict && utilContainsNewline.containsNewline(key))
onError(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
}
if (i2 === 0) {
if (props.comma)
onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
} else {
if (!props.comma)
onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
if (props.comment) {
let prevItemComment = "";
loop:
for (const st of start) {
switch (st.type) {
case "comma":
case "space":
break;
case "comment":
prevItemComment = st.source.substring(1);
break loop;
default:
break loop;
}
}
if (prevItemComment) {
let prev = coll.items[coll.items.length - 1];
if (identity4.isPair(prev))
prev = prev.value ?? prev.key;
if (prev.comment)
prev.comment += `
` + prevItemComment;
else
prev.comment = prevItemComment;
props.comment = props.comment.substring(prevItemComment.length + 1);
}
}
}
if (!isMap2 && !sep6 && !props.found) {
const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep6, null, props, onError);
coll.items.push(valueNode);
offset = valueNode.range[2];
if (isBlock(value))
onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else {
ctx.atKey = true;
const keyStart = props.end;
const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError);
if (isBlock(key))
onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
ctx.atKey = false;
const valueProps = resolveProps.resolveProps(sep6 ?? [], {
flow: fcName,
indicator: "map-value-ind",
next: value,
offset: keyNode.range[2],
onError,
parentIndent: fc.indent,
startOnNewline: false
});
if (valueProps.found) {
if (!isMap2 && !props.found && ctx.options.strict) {
if (sep6)
for (const st of sep6) {
if (st === valueProps.found)
break;
if (st.type === "newline") {
onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
break;
}
}
if (props.start < valueProps.found.offset - 1024)
onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
}
} else if (value) {
if ("source" in value && value.source?.[0] === ":")
onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`);
else
onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
}
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep6, null, valueProps, onError) : null;
if (valueNode) {
if (isBlock(value))
onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += `
` + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
if (isMap2) {
const map3 = coll;
if (utilMapIncludes.mapIncludes(ctx, map3.items, keyNode))
onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
map3.items.push(pair);
} else {
const map3 = new YAMLMap.YAMLMap(ctx.schema);
map3.flow = true;
map3.items.push(pair);
const endRange = (valueNode ?? keyNode).range;
map3.range = [keyNode.range[0], endRange[1], endRange[2]];
coll.items.push(map3);
}
offset = valueNode ? valueNode.range[2] : valueProps.end;
}
}
const expectedEnd = isMap2 ? "}" : "]";
const [ce, ...ee] = fc.end;
let cePos = offset;
if (ce?.source === expectedEnd)
cePos = ce.offset + ce.source.length;
else {
const name = fcName[0].toUpperCase() + fcName.substring(1);
const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
if (ce && ce.source.length !== 1)
ee.unshift(ce);
}
if (ee.length > 0) {
const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
if (end.comment) {
if (coll.comment)
coll.comment += `
` + end.comment;
else
coll.comment = end.comment;
}
coll.range = [fc.offset, cePos, end.offset];
} else {
coll.range = [fc.offset, cePos, cePos];
}
return coll;
}
exports.resolveFlowCollection = resolveFlowCollection;
});
// node_modules/yaml/dist/compose/compose-collection.js
var require_compose_collection = __commonJS((exports) => {
var identity4 = require_identity();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var resolveBlockMap = require_resolve_block_map();
var resolveBlockSeq = require_resolve_block_seq();
var resolveFlowCollection = require_resolve_flow_collection();
function resolveCollection(CN, ctx, token, onError, tagName, tag) {
const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
const Coll = coll.constructor;
if (tagName === "!" || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
if (tagName)
coll.tag = tagName;
return coll;
}
function composeCollection(CN, ctx, token, props, onError) {
const tagToken = props.tag;
const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
if (token.type === "block-seq") {
const { anchor, newlineAfterProp: nl } = props;
const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
if (lastProp && (!nl || nl.offset < lastProp.offset)) {
const message = "Missing newline after block sequence props";
onError(lastProp, "MISSING_CHAR", message);
}
}
const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
return resolveCollection(CN, ctx, token, onError, tagName);
}
let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt?.collection === expType) {
ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
tag = kt;
} else {
if (kt) {
onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
} else {
onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
}
return resolveCollection(CN, ctx, token, onError, tagName);
}
}
const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
const node = identity4.isNode(res) ? res : new Scalar.Scalar(res);
node.range = coll.range;
node.tag = tagName;
if (tag?.format)
node.format = tag.format;
return node;
}
exports.composeCollection = composeCollection;
});
// node_modules/yaml/dist/compose/resolve-block-scalar.js
var require_resolve_block_scalar = __commonJS((exports) => {
var Scalar = require_Scalar();
function resolveBlockScalar(ctx, scalar, onError) {
const start = scalar.offset;
const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
if (!header)
return { value: "", type: null, comment: "", range: [start, start, start] };
const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
const lines = scalar.source ? splitLines(scalar.source) : [];
let chompStart = lines.length;
for (let i2 = lines.length - 1;i2 >= 0; --i2) {
const content = lines[i2][1];
if (content === "" || content === "\r")
chompStart = i2;
else
break;
}
if (chompStart === 0) {
const value2 = header.chomp === "+" && lines.length > 0 ? `
`.repeat(Math.max(1, lines.length - 1)) : "";
let end2 = start + header.length;
if (scalar.source)
end2 += scalar.source.length;
return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
}
let trimIndent = scalar.indent + header.indent;
let offset = scalar.offset + header.length;
let contentStart = 0;
for (let i2 = 0;i2 < chompStart; ++i2) {
const [indent, content] = lines[i2];
if (content === "" || content === "\r") {
if (header.indent === 0 && indent.length > trimIndent)
trimIndent = indent.length;
} else {
if (indent.length < trimIndent) {
const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
onError(offset + indent.length, "MISSING_CHAR", message);
}
if (header.indent === 0)
trimIndent = indent.length;
contentStart = i2;
if (trimIndent === 0 && !ctx.atRoot) {
const message = "Block scalar values in collections must be indented";
onError(offset, "BAD_INDENT", message);
}
break;
}
offset += indent.length + content.length + 1;
}
for (let i2 = lines.length - 1;i2 >= chompStart; --i2) {
if (lines[i2][0].length > trimIndent)
chompStart = i2 + 1;
}
let value = "";
let sep6 = "";
let prevMoreIndented = false;
for (let i2 = 0;i2 < contentStart; ++i2)
value += lines[i2][0].slice(trimIndent) + `
`;
for (let i2 = contentStart;i2 < chompStart; ++i2) {
let [indent, content] = lines[i2];
offset += indent.length + content.length + 1;
const crlf = content[content.length - 1] === "\r";
if (crlf)
content = content.slice(0, -1);
if (content && indent.length < trimIndent) {
const src = header.indent ? "explicit indentation indicator" : "first line";
const message = `Block scalar lines must not be less indented than their ${src}`;
onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
indent = "";
}
if (type === Scalar.Scalar.BLOCK_LITERAL) {
value += sep6 + indent.slice(trimIndent) + content;
sep6 = `
`;
} else if (indent.length > trimIndent || content[0] === "\t") {
if (sep6 === " ")
sep6 = `
`;
else if (!prevMoreIndented && sep6 === `
`)
sep6 = `
`;
value += sep6 + indent.slice(trimIndent) + content;
sep6 = `
`;
prevMoreIndented = true;
} else if (content === "") {
if (sep6 === `
`)
value += `
`;
else
sep6 = `
`;
} else {
value += sep6 + content;
sep6 = " ";
prevMoreIndented = false;
}
}
switch (header.chomp) {
case "-":
break;
case "+":
for (let i2 = chompStart;i2 < lines.length; ++i2)
value += `
` + lines[i2][0].slice(trimIndent);
if (value[value.length - 1] !== `
`)
value += `
`;
break;
default:
value += `
`;
}
const end = start + header.length + scalar.source.length;
return { value, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset, props }, strict, onError) {
if (props[0].type !== "block-scalar-header") {
onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
return null;
}
const { source } = props[0];
const mode = source[0];
let indent = 0;
let chomp = "";
let error44 = -1;
for (let i2 = 1;i2 < source.length; ++i2) {
const ch = source[i2];
if (!chomp && (ch === "-" || ch === "+"))
chomp = ch;
else {
const n2 = Number(ch);
if (!indent && n2)
indent = n2;
else if (error44 === -1)
error44 = offset + i2;
}
}
if (error44 !== -1)
onError(error44, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
let hasSpace = false;
let comment = "";
let length = source.length;
for (let i2 = 1;i2 < props.length; ++i2) {
const token = props[i2];
switch (token.type) {
case "space":
hasSpace = true;
case "newline":
length += token.source.length;
break;
case "comment":
if (strict && !hasSpace) {
const message = "Comments must be separated from other tokens by white space characters";
onError(token, "MISSING_CHAR", message);
}
length += token.source.length;
comment = token.source.substring(1);
break;
case "error":
onError(token, "UNEXPECTED_TOKEN", token.message);
length += token.source.length;
break;
default: {
const message = `Unexpected token in block scalar header: ${token.type}`;
onError(token, "UNEXPECTED_TOKEN", message);
const ts = token.source;
if (ts && typeof ts === "string")
length += ts.length;
}
}
}
return { mode, indent, chomp, comment, length };
}
function splitLines(source) {
const split = source.split(/\n( *)/);
const first = split[0];
const m = first.match(/^( *)/);
const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
const lines = [line0];
for (let i2 = 1;i2 < split.length; i2 += 2)
lines.push([split[i2], split[i2 + 1]]);
return lines;
}
exports.resolveBlockScalar = resolveBlockScalar;
});
// node_modules/yaml/dist/compose/resolve-flow-scalar.js
var require_resolve_flow_scalar = __commonJS((exports) => {
var Scalar = require_Scalar();
var resolveEnd = require_resolve_end();
function resolveFlowScalar(scalar, strict, onError) {
const { offset, type, source, end } = scalar;
let _type;
let value;
const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
switch (type) {
case "scalar":
_type = Scalar.Scalar.PLAIN;
value = plainValue(source, _onError);
break;
case "single-quoted-scalar":
_type = Scalar.Scalar.QUOTE_SINGLE;
value = singleQuotedValue(source, _onError);
break;
case "double-quoted-scalar":
_type = Scalar.Scalar.QUOTE_DOUBLE;
value = doubleQuotedValue(source, _onError);
break;
default:
onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
return {
value: "",
type: null,
comment: "",
range: [offset, offset + source.length, offset + source.length]
};
}
const valueEnd = offset + source.length;
const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
return {
value,
type: _type,
comment: re.comment,
range: [offset, valueEnd, re.offset]
};
}
function plainValue(source, onError) {
let badChar = "";
switch (source[0]) {
case "\t":
badChar = "a tab character";
break;
case ",":
badChar = "flow indicator character ,";
break;
case "%":
badChar = "directive indicator character %";
break;
case "|":
case ">": {
badChar = `block scalar indicator ${source[0]}`;
break;
}
case "@":
case "`": {
badChar = `reserved character ${source[0]}`;
break;
}
}
if (badChar)
onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
return foldLines(source);
}
function singleQuotedValue(source, onError) {
if (source[source.length - 1] !== "'" || source.length === 1)
onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
return foldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function foldLines(source) {
let first, line;
try {
first = new RegExp(`(.*?)(? wsStart ? source.slice(wsStart, i2 + 1) : ch;
} else {
res += ch;
}
}
if (source[source.length - 1] !== '"' || source.length === 1)
onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
return res;
}
function foldNewline(source, offset) {
let fold = "";
let ch = source[offset + 1];
while (ch === " " || ch === "\t" || ch === `
` || ch === "\r") {
if (ch === "\r" && source[offset + 2] !== `
`)
break;
if (ch === `
`)
fold += `
`;
offset += 1;
ch = source[offset + 1];
}
if (!fold)
fold = " ";
return { fold, offset };
}
var escapeCodes = {
"0": "\x00",
a: "\x07",
b: "\b",
e: "\x1B",
f: "\f",
n: `
`,
r: "\r",
t: "\t",
v: "\v",
N: "
",
_: " ",
L: "\u2028",
P: "\u2029",
" ": " ",
'"': '"',
"/": "/",
"\\": "\\",
"\t": "\t"
};
function parseCharCode(source, offset, length, onError) {
const cc = source.substr(offset, length);
const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
const code = ok ? parseInt(cc, 16) : NaN;
if (isNaN(code)) {
const raw = source.substr(offset - 2, length + 2);
onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
return raw;
}
return String.fromCodePoint(code);
}
exports.resolveFlowScalar = resolveFlowScalar;
});
// node_modules/yaml/dist/compose/compose-scalar.js
var require_compose_scalar = __commonJS((exports) => {
var identity4 = require_identity();
var Scalar = require_Scalar();
var resolveBlockScalar = require_resolve_block_scalar();
var resolveFlowScalar = require_resolve_flow_scalar();
function composeScalar(ctx, token, tagToken, onError) {
const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
let tag;
if (ctx.options.stringKeys && ctx.atKey) {
tag = ctx.schema[identity4.SCALAR];
} else if (tagName)
tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
else if (token.type === "scalar")
tag = findScalarTagByTest(ctx, value, token, onError);
else
tag = ctx.schema[identity4.SCALAR];
let scalar;
try {
const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
scalar = identity4.isScalar(res) ? res : new Scalar.Scalar(res);
} catch (error44) {
const msg = error44 instanceof Error ? error44.message : String(error44);
onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
scalar = new Scalar.Scalar(value);
}
scalar.range = range;
scalar.source = value;
if (type)
scalar.type = type;
if (tagName)
scalar.tag = tagName;
if (tag.format)
scalar.format = tag.format;
if (comment)
scalar.comment = comment;
return scalar;
}
function findScalarTagByName(schema, value, tagName, tagToken, onError) {
if (tagName === "!")
return schema[identity4.SCALAR];
const matchWithTest = [];
for (const tag of schema.tags) {
if (!tag.collection && tag.tag === tagName) {
if (tag.default && tag.test)
matchWithTest.push(tag);
else
return tag;
}
}
for (const tag of matchWithTest)
if (tag.test?.test(value))
return tag;
const kt = schema.knownTags[tagName];
if (kt && !kt.collection) {
schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
return kt;
}
onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
return schema[identity4.SCALAR];
}
function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity4.SCALAR];
if (schema.compat) {
const compat2 = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity4.SCALAR];
if (tag.tag !== compat2.tag) {
const ts = directives.tagString(tag.tag);
const cs = directives.tagString(compat2.tag);
const msg = `Value may be parsed as either ${ts} or ${cs}`;
onError(token, "TAG_RESOLVE_FAILED", msg, true);
}
}
return tag;
}
exports.composeScalar = composeScalar;
});
// node_modules/yaml/dist/compose/util-empty-scalar-position.js
var require_util_empty_scalar_position = __commonJS((exports) => {
function emptyScalarPosition(offset, before, pos) {
if (before) {
pos ?? (pos = before.length);
for (let i2 = pos - 1;i2 >= 0; --i2) {
let st = before[i2];
switch (st.type) {
case "space":
case "comment":
case "newline":
offset -= st.source.length;
continue;
}
st = before[++i2];
while (st?.type === "space") {
offset += st.source.length;
st = before[++i2];
}
break;
}
}
return offset;
}
exports.emptyScalarPosition = emptyScalarPosition;
});
// node_modules/yaml/dist/compose/compose-node.js
var require_compose_node = __commonJS((exports) => {
var Alias = require_Alias();
var identity4 = require_identity();
var composeCollection = require_compose_collection();
var composeScalar = require_compose_scalar();
var resolveEnd = require_resolve_end();
var utilEmptyScalarPosition = require_util_empty_scalar_position();
var CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props, onError) {
const atKey = ctx.atKey;
const { spaceBefore, comment, anchor, tag } = props;
let node;
let isSrcToken = true;
switch (token.type) {
case "alias":
node = composeAlias(ctx, token, onError);
if (anchor || tag)
onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
break;
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "block-scalar":
node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
break;
case "block-map":
case "block-seq":
case "flow-collection":
try {
node = composeCollection.composeCollection(CN, ctx, token, props, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
} catch (error44) {
const message = error44 instanceof Error ? error44.message : String(error44);
onError(token, "RESOURCE_EXHAUSTION", message);
}
break;
default: {
const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
onError(token, "UNEXPECTED_TOKEN", message);
isSrcToken = false;
}
}
node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));
if (anchor && node.anchor === "")
onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
if (atKey && ctx.options.stringKeys && (!identity4.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
const msg = "With stringKeys, all keys must be strings";
onError(tag ?? token, "NON_STRING_KEY", msg);
}
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
if (token.type === "scalar" && token.source === "")
node.comment = comment;
else
node.commentBefore = comment;
}
if (ctx.options.keepSourceTokens && isSrcToken)
node.srcToken = token;
return node;
}
function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
const token = {
type: "scalar",
offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
indent: -1,
source: ""
};
const node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor) {
node.anchor = anchor.source.substring(1);
if (node.anchor === "")
onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
}
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
node.comment = comment;
node.range[2] = end;
}
return node;
}
function composeAlias({ options }, { offset, source, end }, onError) {
const alias = new Alias.Alias(source.substring(1));
if (alias.source === "")
onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
if (alias.source.endsWith(":"))
onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
const valueEnd = offset + source.length;
const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
alias.range = [offset, valueEnd, re.offset];
if (re.comment)
alias.comment = re.comment;
return alias;
}
exports.composeEmptyNode = composeEmptyNode;
exports.composeNode = composeNode;
});
// node_modules/yaml/dist/compose/compose-doc.js
var require_compose_doc = __commonJS((exports) => {
var Document = require_Document();
var composeNode = require_compose_node();
var resolveEnd = require_resolve_end();
var resolveProps = require_resolve_props();
function composeDoc(options, directives, { offset, start, value, end }, onError) {
const opts = Object.assign({ _directives: directives }, options);
const doc2 = new Document.Document(undefined, opts);
const ctx = {
atKey: false,
atRoot: true,
directives: doc2.directives,
options: doc2.options,
schema: doc2.schema
};
const props = resolveProps.resolveProps(start, {
indicator: "doc-start",
next: value ?? end?.[0],
offset,
onError,
parentIndent: 0,
startOnNewline: true
});
if (props.found) {
doc2.directives.docStart = true;
if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline)
onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
}
doc2.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
const contentEnd = doc2.contents.range[2];
const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
if (re.comment)
doc2.comment = re.comment;
doc2.range = [offset, contentEnd, re.offset];
return doc2;
}
exports.composeDoc = composeDoc;
});
// node_modules/yaml/dist/compose/composer.js
var require_composer = __commonJS((exports) => {
var node_process = __require("process");
var directives = require_directives();
var Document = require_Document();
var errors3 = require_errors6();
var identity4 = require_identity();
var composeDoc = require_compose_doc();
var resolveEnd = require_resolve_end();
function getErrorPos(src) {
if (typeof src === "number")
return [src, src + 1];
if (Array.isArray(src))
return src.length === 2 ? src : [src[0], src[1]];
const { offset, source } = src;
return [offset, offset + (typeof source === "string" ? source.length : 1)];
}
function parsePrelude(prelude) {
let comment = "";
let atComment = false;
let afterEmptyLine = false;
for (let i2 = 0;i2 < prelude.length; ++i2) {
const source = prelude[i2];
switch (source[0]) {
case "#":
comment += (comment === "" ? "" : afterEmptyLine ? `
` : `
`) + (source.substring(1) || " ");
atComment = true;
afterEmptyLine = false;
break;
case "%":
if (prelude[i2 + 1]?.[0] !== "#")
i2 += 1;
atComment = false;
break;
default:
if (!atComment)
afterEmptyLine = true;
atComment = false;
}
}
return { comment, afterEmptyLine };
}
class Composer {
constructor(options = {}) {
this.doc = null;
this.atDirectives = false;
this.prelude = [];
this.errors = [];
this.warnings = [];
this.onError = (source, code, message, warning) => {
const pos = getErrorPos(source);
if (warning)
this.warnings.push(new errors3.YAMLWarning(pos, code, message));
else
this.errors.push(new errors3.YAMLParseError(pos, code, message));
};
this.directives = new directives.Directives({ version: options.version || "1.2" });
this.options = options;
}
decorate(doc2, afterDoc) {
const { comment, afterEmptyLine } = parsePrelude(this.prelude);
if (comment) {
const dc = doc2.contents;
if (afterDoc) {
doc2.comment = doc2.comment ? `${doc2.comment}
${comment}` : comment;
} else if (afterEmptyLine || doc2.directives.docStart || !dc) {
doc2.commentBefore = comment;
} else if (identity4.isCollection(dc) && !dc.flow && dc.items.length > 0) {
let it = dc.items[0];
if (identity4.isPair(it))
it = it.key;
const cb = it.commentBefore;
it.commentBefore = cb ? `${comment}
${cb}` : comment;
} else {
const cb = dc.commentBefore;
dc.commentBefore = cb ? `${comment}
${cb}` : comment;
}
}
if (afterDoc) {
Array.prototype.push.apply(doc2.errors, this.errors);
Array.prototype.push.apply(doc2.warnings, this.warnings);
} else {
doc2.errors = this.errors;
doc2.warnings = this.warnings;
}
this.prelude = [];
this.errors = [];
this.warnings = [];
}
streamInfo() {
return {
comment: parsePrelude(this.prelude).comment,
directives: this.directives,
errors: this.errors,
warnings: this.warnings
};
}
*compose(tokens, forceDoc = false, endOffset = -1) {
for (const token of tokens)
yield* this.next(token);
yield* this.end(forceDoc, endOffset);
}
*next(token) {
if (node_process.env.LOG_STREAM)
console.dir(token, { depth: null });
switch (token.type) {
case "directive":
this.directives.add(token.source, (offset, message, warning) => {
const pos = getErrorPos(token);
pos[0] += offset;
this.onError(pos, "BAD_DIRECTIVE", message, warning);
});
this.prelude.push(token.source);
this.atDirectives = true;
break;
case "document": {
const doc2 = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
if (this.atDirectives && !doc2.directives.docStart)
this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
this.decorate(doc2, false);
if (this.doc)
yield this.doc;
this.doc = doc2;
this.atDirectives = false;
break;
}
case "byte-order-mark":
case "space":
break;
case "comment":
case "newline":
this.prelude.push(token.source);
break;
case "error": {
const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
const error44 = new errors3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
if (this.atDirectives || !this.doc)
this.errors.push(error44);
else
this.doc.errors.push(error44);
break;
}
case "doc-end": {
if (!this.doc) {
const msg = "Unexpected doc-end without preceding document";
this.errors.push(new errors3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
break;
}
this.doc.directives.docEnd = true;
const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
this.decorate(this.doc, true);
if (end.comment) {
const dc = this.doc.comment;
this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
}
this.doc.range[2] = end.offset;
break;
}
default:
this.errors.push(new errors3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
}
}
*end(forceDoc = false, endOffset = -1) {
if (this.doc) {
this.decorate(this.doc, true);
yield this.doc;
this.doc = null;
} else if (forceDoc) {
const opts = Object.assign({ _directives: this.directives }, this.options);
const doc2 = new Document.Document(undefined, opts);
if (this.atDirectives)
this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
doc2.range = [0, endOffset, endOffset];
this.decorate(doc2, false);
yield doc2;
}
}
}
exports.Composer = Composer;
});
// node_modules/yaml/dist/parse/cst-scalar.js
var require_cst_scalar = __commonJS((exports) => {
var resolveBlockScalar = require_resolve_block_scalar();
var resolveFlowScalar = require_resolve_flow_scalar();
var errors3 = require_errors6();
var stringifyString = require_stringifyString();
function resolveAsScalar(token, strict = true, onError) {
if (token) {
const _onError = (pos, code, message) => {
const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
if (onError)
onError(offset, code, message);
else
throw new errors3.YAMLParseError([offset, offset + 1], code, message);
};
switch (token.type) {
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
case "block-scalar":
return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
}
}
return null;
}
function createScalarToken(value, context2) {
const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context2;
const source = stringifyString.stringifyString({ type, value }, {
implicitKey,
indent: indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
const end = context2.end ?? [
{ type: "newline", offset: -1, indent, source: `
` }
];
switch (source[0]) {
case "|":
case ">": {
const he = source.indexOf(`
`);
const head = source.substring(0, he);
const body = source.substring(he + 1) + `
`;
const props = [
{ type: "block-scalar-header", offset, indent, source: head }
];
if (!addEndtoBlockProps(props, end))
props.push({ type: "newline", offset: -1, indent, source: `
` });
return { type: "block-scalar", offset, indent, props, source: body };
}
case '"':
return { type: "double-quoted-scalar", offset, indent, source, end };
case "'":
return { type: "single-quoted-scalar", offset, indent, source, end };
default:
return { type: "scalar", offset, indent, source, end };
}
}
function setScalarValue(token, value, context2 = {}) {
let { afterKey = false, implicitKey = false, inFlow = false, type } = context2;
let indent = "indent" in token ? token.indent : null;
if (afterKey && typeof indent === "number")
indent += 2;
if (!type)
switch (token.type) {
case "single-quoted-scalar":
type = "QUOTE_SINGLE";
break;
case "double-quoted-scalar":
type = "QUOTE_DOUBLE";
break;
case "block-scalar": {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
break;
}
default:
type = "PLAIN";
}
const source = stringifyString.stringifyString({ type, value }, {
implicitKey: implicitKey || indent === null,
indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
switch (source[0]) {
case "|":
case ">":
setBlockScalarValue(token, source);
break;
case '"':
setFlowScalarValue(token, source, "double-quoted-scalar");
break;
case "'":
setFlowScalarValue(token, source, "single-quoted-scalar");
break;
default:
setFlowScalarValue(token, source, "scalar");
}
}
function setBlockScalarValue(token, source) {
const he = source.indexOf(`
`);
const head = source.substring(0, he);
const body = source.substring(he + 1) + `
`;
if (token.type === "block-scalar") {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
header.source = head;
token.source = body;
} else {
const { offset } = token;
const indent = "indent" in token ? token.indent : -1;
const props = [
{ type: "block-scalar-header", offset, indent, source: head }
];
if (!addEndtoBlockProps(props, "end" in token ? token.end : undefined))
props.push({ type: "newline", offset: -1, indent, source: `
` });
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type: "block-scalar", indent, props, source: body });
}
}
function addEndtoBlockProps(props, end) {
if (end)
for (const st of end)
switch (st.type) {
case "space":
case "comment":
props.push(st);
break;
case "newline":
props.push(st);
return true;
}
return false;
}
function setFlowScalarValue(token, source, type) {
switch (token.type) {
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
token.type = type;
token.source = source;
break;
case "block-scalar": {
const end = token.props.slice(1);
let oa = source.length;
if (token.props[0].type === "block-scalar-header")
oa -= token.props[0].source.length;
for (const tok of end)
tok.offset += oa;
delete token.props;
Object.assign(token, { type, source, end });
break;
}
case "block-map":
case "block-seq": {
const offset = token.offset + source.length;
const nl = { type: "newline", offset, indent: token.indent, source: `
` };
delete token.items;
Object.assign(token, { type, source, end: [nl] });
break;
}
default: {
const indent = "indent" in token ? token.indent : -1;
const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type, indent, source, end });
}
}
}
exports.createScalarToken = createScalarToken;
exports.resolveAsScalar = resolveAsScalar;
exports.setScalarValue = setScalarValue;
});
// node_modules/yaml/dist/parse/cst-stringify.js
var require_cst_stringify = __commonJS((exports) => {
var stringify = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst);
function stringifyToken(token) {
switch (token.type) {
case "block-scalar": {
let res = "";
for (const tok of token.props)
res += stringifyToken(tok);
return res + token.source;
}
case "block-map":
case "block-seq": {
let res = "";
for (const item of token.items)
res += stringifyItem(item);
return res;
}
case "flow-collection": {
let res = token.start.source;
for (const item of token.items)
res += stringifyItem(item);
for (const st of token.end)
res += st.source;
return res;
}
case "document": {
let res = stringifyItem(token);
if (token.end)
for (const st of token.end)
res += st.source;
return res;
}
default: {
let res = token.source;
if ("end" in token && token.end)
for (const st of token.end)
res += st.source;
return res;
}
}
}
function stringifyItem({ start, key, sep: sep6, value }) {
let res = "";
for (const st of start)
res += st.source;
if (key)
res += stringifyToken(key);
if (sep6)
for (const st of sep6)
res += st.source;
if (value)
res += stringifyToken(value);
return res;
}
exports.stringify = stringify;
});
// node_modules/yaml/dist/parse/cst-visit.js
var require_cst_visit = __commonJS((exports) => {
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove item");
function visit2(cst, visitor) {
if ("type" in cst && cst.type === "document")
cst = { start: cst.start, value: cst.value };
_visit(Object.freeze([]), cst, visitor);
}
visit2.BREAK = BREAK;
visit2.SKIP = SKIP;
visit2.REMOVE = REMOVE;
visit2.itemAtPath = (cst, path10) => {
let item = cst;
for (const [field, index] of path10) {
const tok = item?.[field];
if (tok && "items" in tok) {
item = tok.items[index];
} else
return;
}
return item;
};
visit2.parentCollection = (cst, path10) => {
const parent = visit2.itemAtPath(cst, path10.slice(0, -1));
const field = path10[path10.length - 1][0];
const coll = parent?.[field];
if (coll && "items" in coll)
return coll;
throw new Error("Parent collection not found");
};
function _visit(path10, item, visitor) {
let ctrl = visitor(item, path10);
if (typeof ctrl === "symbol")
return ctrl;
for (const field of ["key", "value"]) {
const token = item[field];
if (token && "items" in token) {
for (let i2 = 0;i2 < token.items.length; ++i2) {
const ci = _visit(Object.freeze(path10.concat([[field, i2]])), token.items[i2], visitor);
if (typeof ci === "number")
i2 = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
token.items.splice(i2, 1);
i2 -= 1;
}
}
if (typeof ctrl === "function" && field === "key")
ctrl = ctrl(item, path10);
}
}
return typeof ctrl === "function" ? ctrl(item, path10) : ctrl;
}
exports.visit = visit2;
});
// node_modules/yaml/dist/parse/cst.js
var require_cst = __commonJS((exports) => {
var cstScalar = require_cst_scalar();
var cstStringify = require_cst_stringify();
var cstVisit = require_cst_visit();
var BOM = "\uFEFF";
var DOCUMENT = "\x02";
var FLOW_END = "\x18";
var SCALAR = "\x1F";
var isCollection = (token) => !!token && ("items" in token);
var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
function prettyToken(token) {
switch (token) {
case BOM:
return "";
case DOCUMENT:
return "";
case FLOW_END:
return "";
case SCALAR:
return "";
default:
return JSON.stringify(token);
}
}
function tokenType(source) {
switch (source) {
case BOM:
return "byte-order-mark";
case DOCUMENT:
return "doc-mode";
case FLOW_END:
return "flow-error-end";
case SCALAR:
return "scalar";
case "---":
return "doc-start";
case "...":
return "doc-end";
case "":
case `
`:
case `\r
`:
return "newline";
case "-":
return "seq-item-ind";
case "?":
return "explicit-key-ind";
case ":":
return "map-value-ind";
case "{":
return "flow-map-start";
case "}":
return "flow-map-end";
case "[":
return "flow-seq-start";
case "]":
return "flow-seq-end";
case ",":
return "comma";
}
switch (source[0]) {
case " ":
case "\t":
return "space";
case "#":
return "comment";
case "%":
return "directive-line";
case "*":
return "alias";
case "&":
return "anchor";
case "!":
return "tag";
case "'":
return "single-quoted-scalar";
case '"':
return "double-quoted-scalar";
case "|":
case ">":
return "block-scalar-header";
}
return null;
}
exports.createScalarToken = cstScalar.createScalarToken;
exports.resolveAsScalar = cstScalar.resolveAsScalar;
exports.setScalarValue = cstScalar.setScalarValue;
exports.stringify = cstStringify.stringify;
exports.visit = cstVisit.visit;
exports.BOM = BOM;
exports.DOCUMENT = DOCUMENT;
exports.FLOW_END = FLOW_END;
exports.SCALAR = SCALAR;
exports.isCollection = isCollection;
exports.isScalar = isScalar;
exports.prettyToken = prettyToken;
exports.tokenType = tokenType;
});
// node_modules/yaml/dist/parse/lexer.js
var require_lexer = __commonJS((exports) => {
var cst = require_cst();
function isEmpty(ch) {
switch (ch) {
case undefined:
case " ":
case `
`:
case "\r":
case "\t":
return true;
default:
return false;
}
}
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(` ,[]{}
\r `);
var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
class Lexer {
constructor() {
this.atEnd = false;
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
this.buffer = "";
this.flowKey = false;
this.flowLevel = 0;
this.indentNext = 0;
this.indentValue = 0;
this.lineEndPos = null;
this.next = null;
this.pos = 0;
}
*lex(source, incomplete = false) {
if (source) {
if (typeof source !== "string")
throw TypeError("source is not a string");
this.buffer = this.buffer ? this.buffer + source : source;
this.lineEndPos = null;
}
this.atEnd = !incomplete;
let next = this.next ?? "stream";
while (next && (incomplete || this.hasChars(1)))
next = yield* this.parseNext(next);
}
atLineEnd() {
let i2 = this.pos;
let ch = this.buffer[i2];
while (ch === " " || ch === "\t")
ch = this.buffer[++i2];
if (!ch || ch === "#" || ch === `
`)
return true;
if (ch === "\r")
return this.buffer[i2 + 1] === `
`;
return false;
}
charAt(n2) {
return this.buffer[this.pos + n2];
}
continueScalar(offset) {
let ch = this.buffer[offset];
if (this.indentNext > 0) {
let indent = 0;
while (ch === " ")
ch = this.buffer[++indent + offset];
if (ch === "\r") {
const next = this.buffer[indent + offset + 1];
if (next === `
` || !next && !this.atEnd)
return offset + indent + 1;
}
return ch === `
` || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
}
if (ch === "-" || ch === ".") {
const dt = this.buffer.substr(offset, 3);
if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3]))
return -1;
}
return offset;
}
getLine() {
let end = this.lineEndPos;
if (typeof end !== "number" || end !== -1 && end < this.pos) {
end = this.buffer.indexOf(`
`, this.pos);
this.lineEndPos = end;
}
if (end === -1)
return this.atEnd ? this.buffer.substring(this.pos) : null;
if (this.buffer[end - 1] === "\r")
end -= 1;
return this.buffer.substring(this.pos, end);
}
hasChars(n2) {
return this.pos + n2 <= this.buffer.length;
}
setNext(state) {
this.buffer = this.buffer.substring(this.pos);
this.pos = 0;
this.lineEndPos = null;
this.next = state;
return null;
}
peek(n2) {
return this.buffer.substr(this.pos, n2);
}
*parseNext(next) {
switch (next) {
case "stream":
return yield* this.parseStream();
case "line-start":
return yield* this.parseLineStart();
case "block-start":
return yield* this.parseBlockStart();
case "doc":
return yield* this.parseDocument();
case "flow":
return yield* this.parseFlowCollection();
case "quoted-scalar":
return yield* this.parseQuotedScalar();
case "block-scalar":
return yield* this.parseBlockScalar();
case "plain-scalar":
return yield* this.parsePlainScalar();
}
}
*parseStream() {
let line = this.getLine();
if (line === null)
return this.setNext("stream");
if (line[0] === cst.BOM) {
yield* this.pushCount(1);
line = line.substring(1);
}
if (line[0] === "%") {
let dirEnd = line.length;
let cs = line.indexOf("#");
while (cs !== -1) {
const ch = line[cs - 1];
if (ch === " " || ch === "\t") {
dirEnd = cs - 1;
break;
} else {
cs = line.indexOf("#", cs + 1);
}
}
while (true) {
const ch = line[dirEnd - 1];
if (ch === " " || ch === "\t")
dirEnd -= 1;
else
break;
}
const n2 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
yield* this.pushCount(line.length - n2);
this.pushNewline();
return "stream";
}
if (this.atLineEnd()) {
const sp = yield* this.pushSpaces(true);
yield* this.pushCount(line.length - sp);
yield* this.pushNewline();
return "stream";
}
yield cst.DOCUMENT;
return yield* this.parseLineStart();
}
*parseLineStart() {
const ch = this.charAt(0);
if (!ch && !this.atEnd)
return this.setNext("line-start");
if (ch === "-" || ch === ".") {
if (!this.atEnd && !this.hasChars(4))
return this.setNext("line-start");
const s = this.peek(3);
if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
this.indentValue = 0;
this.indentNext = 0;
return s === "---" ? "doc" : "stream";
}
}
this.indentValue = yield* this.pushSpaces(false);
if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
this.indentNext = this.indentValue;
return yield* this.parseBlockStart();
}
*parseBlockStart() {
const [ch0, ch1] = this.peek(2);
if (!ch1 && !this.atEnd)
return this.setNext("block-start");
if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
const n2 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
this.indentNext = this.indentValue + 1;
this.indentValue += n2;
return yield* this.parseBlockStart();
}
return "doc";
}
*parseDocument() {
yield* this.pushSpaces(true);
const line = this.getLine();
if (line === null)
return this.setNext("doc");
let n2 = yield* this.pushIndicators();
switch (line[n2]) {
case "#":
yield* this.pushCount(line.length - n2);
case undefined:
yield* this.pushNewline();
return yield* this.parseLineStart();
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel = 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
return "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "doc";
case '"':
case "'":
return yield* this.parseQuotedScalar();
case "|":
case ">":
n2 += yield* this.parseBlockScalarHeader();
n2 += yield* this.pushSpaces(true);
yield* this.pushCount(line.length - n2);
yield* this.pushNewline();
return yield* this.parseBlockScalar();
default:
return yield* this.parsePlainScalar();
}
}
*parseFlowCollection() {
let nl, sp;
let indent = -1;
do {
nl = yield* this.pushNewline();
if (nl > 0) {
sp = yield* this.pushSpaces(false);
this.indentValue = indent = sp;
} else {
sp = 0;
}
sp += yield* this.pushSpaces(true);
} while (nl + sp > 0);
const line = this.getLine();
if (line === null)
return this.setNext("flow");
if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
if (!atFlowEndMarker) {
this.flowLevel = 0;
yield cst.FLOW_END;
return yield* this.parseLineStart();
}
}
let n2 = 0;
while (line[n2] === ",") {
n2 += yield* this.pushCount(1);
n2 += yield* this.pushSpaces(true);
this.flowKey = false;
}
n2 += yield* this.pushIndicators();
switch (line[n2]) {
case undefined:
return "flow";
case "#":
yield* this.pushCount(line.length - n2);
return "flow";
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel += 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
this.flowKey = true;
this.flowLevel -= 1;
return this.flowLevel ? "flow" : "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "flow";
case '"':
case "'":
this.flowKey = true;
return yield* this.parseQuotedScalar();
case ":": {
const next = this.charAt(1);
if (this.flowKey || isEmpty(next) || next === ",") {
this.flowKey = false;
yield* this.pushCount(1);
yield* this.pushSpaces(true);
return "flow";
}
}
default:
this.flowKey = false;
return yield* this.parsePlainScalar();
}
}
*parseQuotedScalar() {
const quote = this.charAt(0);
let end = this.buffer.indexOf(quote, this.pos + 1);
if (quote === "'") {
while (end !== -1 && this.buffer[end + 1] === "'")
end = this.buffer.indexOf("'", end + 2);
} else {
while (end !== -1) {
let n2 = 0;
while (this.buffer[end - 1 - n2] === "\\")
n2 += 1;
if (n2 % 2 === 0)
break;
end = this.buffer.indexOf('"', end + 1);
}
}
const qb = this.buffer.substring(0, end);
let nl = qb.indexOf(`
`, this.pos);
if (nl !== -1) {
while (nl !== -1) {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = qb.indexOf(`
`, cs);
}
if (nl !== -1) {
end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
}
}
if (end === -1) {
if (!this.atEnd)
return this.setNext("quoted-scalar");
end = this.buffer.length;
}
yield* this.pushToIndex(end + 1, false);
return this.flowLevel ? "flow" : "doc";
}
*parseBlockScalarHeader() {
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
let i2 = this.pos;
while (true) {
const ch = this.buffer[++i2];
if (ch === "+")
this.blockScalarKeep = true;
else if (ch > "0" && ch <= "9")
this.blockScalarIndent = Number(ch) - 1;
else if (ch !== "-")
break;
}
return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
}
*parseBlockScalar() {
let nl = this.pos - 1;
let indent = 0;
let ch;
loop:
for (let i3 = this.pos;ch = this.buffer[i3]; ++i3) {
switch (ch) {
case " ":
indent += 1;
break;
case `
`:
nl = i3;
indent = 0;
break;
case "\r": {
const next = this.buffer[i3 + 1];
if (!next && !this.atEnd)
return this.setNext("block-scalar");
if (next === `
`)
break;
}
default:
break loop;
}
}
if (!ch && !this.atEnd)
return this.setNext("block-scalar");
if (indent >= this.indentNext) {
if (this.blockScalarIndent === -1)
this.indentNext = indent;
else {
this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
}
do {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = this.buffer.indexOf(`
`, cs);
} while (nl !== -1);
if (nl === -1) {
if (!this.atEnd)
return this.setNext("block-scalar");
nl = this.buffer.length;
}
}
let i2 = nl + 1;
ch = this.buffer[i2];
while (ch === " ")
ch = this.buffer[++i2];
if (ch === "\t") {
while (ch === "\t" || ch === " " || ch === "\r" || ch === `
`)
ch = this.buffer[++i2];
nl = i2 - 1;
} else if (!this.blockScalarKeep) {
do {
let i3 = nl - 1;
let ch2 = this.buffer[i3];
if (ch2 === "\r")
ch2 = this.buffer[--i3];
const lastChar = i3;
while (ch2 === " ")
ch2 = this.buffer[--i3];
if (ch2 === `
` && i3 >= this.pos && i3 + 1 + indent > lastChar)
nl = i3;
else
break;
} while (true);
}
yield cst.SCALAR;
yield* this.pushToIndex(nl + 1, true);
return yield* this.parseLineStart();
}
*parsePlainScalar() {
const inFlow = this.flowLevel > 0;
let end = this.pos - 1;
let i2 = this.pos - 1;
let ch;
while (ch = this.buffer[++i2]) {
if (ch === ":") {
const next = this.buffer[i2 + 1];
if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
break;
end = i2;
} else if (isEmpty(ch)) {
let next = this.buffer[i2 + 1];
if (ch === "\r") {
if (next === `
`) {
i2 += 1;
ch = `
`;
next = this.buffer[i2 + 1];
} else
end = i2;
}
if (next === "#" || inFlow && flowIndicatorChars.has(next))
break;
if (ch === `
`) {
const cs = this.continueScalar(i2 + 1);
if (cs === -1)
break;
i2 = Math.max(i2, cs - 2);
}
} else {
if (inFlow && flowIndicatorChars.has(ch))
break;
end = i2;
}
}
if (!ch && !this.atEnd)
return this.setNext("plain-scalar");
yield cst.SCALAR;
yield* this.pushToIndex(end + 1, true);
return inFlow ? "flow" : "doc";
}
*pushCount(n2) {
if (n2 > 0) {
yield this.buffer.substr(this.pos, n2);
this.pos += n2;
return n2;
}
return 0;
}
*pushToIndex(i2, allowEmpty) {
const s = this.buffer.slice(this.pos, i2);
if (s) {
yield s;
this.pos += s.length;
return s.length;
} else if (allowEmpty)
yield "";
return 0;
}
*pushIndicators() {
switch (this.charAt(0)) {
case "!":
return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
case "&":
return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
case "-":
case "?":
case ":": {
const inFlow = this.flowLevel > 0;
const ch1 = this.charAt(1);
if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
if (!inFlow)
this.indentNext = this.indentValue + 1;
else if (this.flowKey)
this.flowKey = false;
return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
}
}
}
return 0;
}
*pushTag() {
if (this.charAt(1) === "<") {
let i2 = this.pos + 2;
let ch = this.buffer[i2];
while (!isEmpty(ch) && ch !== ">")
ch = this.buffer[++i2];
return yield* this.pushToIndex(ch === ">" ? i2 + 1 : i2, false);
} else {
let i2 = this.pos + 1;
let ch = this.buffer[i2];
while (ch) {
if (tagChars.has(ch))
ch = this.buffer[++i2];
else if (ch === "%" && hexDigits.has(this.buffer[i2 + 1]) && hexDigits.has(this.buffer[i2 + 2])) {
ch = this.buffer[i2 += 3];
} else
break;
}
return yield* this.pushToIndex(i2, false);
}
}
*pushNewline() {
const ch = this.buffer[this.pos];
if (ch === `
`)
return yield* this.pushCount(1);
else if (ch === "\r" && this.charAt(1) === `
`)
return yield* this.pushCount(2);
else
return 0;
}
*pushSpaces(allowTabs) {
let i2 = this.pos - 1;
let ch;
do {
ch = this.buffer[++i2];
} while (ch === " " || allowTabs && ch === "\t");
const n2 = i2 - this.pos;
if (n2 > 0) {
yield this.buffer.substr(this.pos, n2);
this.pos = i2;
}
return n2;
}
*pushUntil(test2) {
let i2 = this.pos;
let ch = this.buffer[i2];
while (!test2(ch))
ch = this.buffer[++i2];
return yield* this.pushToIndex(i2, false);
}
}
exports.Lexer = Lexer;
});
// node_modules/yaml/dist/parse/line-counter.js
var require_line_counter = __commonJS((exports) => {
class LineCounter {
constructor() {
this.lineStarts = [];
this.addNewLine = (offset) => this.lineStarts.push(offset);
this.linePos = (offset) => {
let low = 0;
let high = this.lineStarts.length;
while (low < high) {
const mid = low + high >> 1;
if (this.lineStarts[mid] < offset)
low = mid + 1;
else
high = mid;
}
if (this.lineStarts[low] === offset)
return { line: low + 1, col: 1 };
if (low === 0)
return { line: 0, col: offset };
const start = this.lineStarts[low - 1];
return { line: low, col: offset - start + 1 };
};
}
}
exports.LineCounter = LineCounter;
});
// node_modules/yaml/dist/parse/parser.js
var require_parser = __commonJS((exports) => {
var node_process = __require("process");
var cst = require_cst();
var lexer = require_lexer();
function includesToken(list, type) {
for (let i2 = 0;i2 < list.length; ++i2)
if (list[i2].type === type)
return true;
return false;
}
function findNonEmptyIndex(list) {
for (let i2 = 0;i2 < list.length; ++i2) {
switch (list[i2].type) {
case "space":
case "comment":
case "newline":
break;
default:
return i2;
}
}
return -1;
}
function isFlowToken(token) {
switch (token?.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "flow-collection":
return true;
default:
return false;
}
}
function getPrevProps(parent) {
switch (parent.type) {
case "document":
return parent.start;
case "block-map": {
const it = parent.items[parent.items.length - 1];
return it.sep ?? it.start;
}
case "block-seq":
return parent.items[parent.items.length - 1].start;
default:
return [];
}
}
function getFirstKeyStartProps(prev) {
if (prev.length === 0)
return [];
let i2 = prev.length;
loop:
while (--i2 >= 0) {
switch (prev[i2].type) {
case "doc-start":
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
case "newline":
break loop;
}
}
while (prev[++i2]?.type === "space") {}
return prev.splice(i2, prev.length);
}
function fixFlowSeqItems(fc) {
if (fc.start.type === "flow-seq-start") {
for (const it of fc.items) {
if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
if (it.key)
it.value = it.key;
delete it.key;
if (isFlowToken(it.value)) {
if (it.value.end)
Array.prototype.push.apply(it.value.end, it.sep);
else
it.value.end = it.sep;
} else
Array.prototype.push.apply(it.start, it.sep);
delete it.sep;
}
}
}
}
class Parser2 {
constructor(onNewLine) {
this.atNewLine = true;
this.atScalar = false;
this.indent = 0;
this.offset = 0;
this.onKeyLine = false;
this.stack = [];
this.source = "";
this.type = "";
this.lexer = new lexer.Lexer;
this.onNewLine = onNewLine;
}
*parse(source, incomplete = false) {
if (this.onNewLine && this.offset === 0)
this.onNewLine(0);
for (const lexeme of this.lexer.lex(source, incomplete))
yield* this.next(lexeme);
if (!incomplete)
yield* this.end();
}
*next(source) {
this.source = source;
if (node_process.env.LOG_TOKENS)
console.log("|", cst.prettyToken(source));
if (this.atScalar) {
this.atScalar = false;
yield* this.step();
this.offset += source.length;
return;
}
const type = cst.tokenType(source);
if (!type) {
const message = `Not a YAML token: ${source}`;
yield* this.pop({ type: "error", offset: this.offset, message, source });
this.offset += source.length;
} else if (type === "scalar") {
this.atNewLine = false;
this.atScalar = true;
this.type = "scalar";
} else {
this.type = type;
yield* this.step();
switch (type) {
case "newline":
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine)
this.onNewLine(this.offset + source.length);
break;
case "space":
if (this.atNewLine && source[0] === " ")
this.indent += source.length;
break;
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
if (this.atNewLine)
this.indent += source.length;
break;
case "doc-mode":
case "flow-error-end":
return;
default:
this.atNewLine = false;
}
this.offset += source.length;
}
}
*end() {
while (this.stack.length > 0)
yield* this.pop();
}
get sourceToken() {
const st = {
type: this.type,
offset: this.offset,
indent: this.indent,
source: this.source
};
return st;
}
*step() {
const top = this.peek(1);
if (this.type === "doc-end" && top?.type !== "doc-end") {
while (this.stack.length > 0)
yield* this.pop();
this.stack.push({
type: "doc-end",
offset: this.offset,
source: this.source
});
return;
}
if (!top)
return yield* this.stream();
switch (top.type) {
case "document":
return yield* this.document(top);
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return yield* this.scalar(top);
case "block-scalar":
return yield* this.blockScalar(top);
case "block-map":
return yield* this.blockMap(top);
case "block-seq":
return yield* this.blockSequence(top);
case "flow-collection":
return yield* this.flowCollection(top);
case "doc-end":
return yield* this.documentEnd(top);
}
yield* this.pop();
}
peek(n2) {
return this.stack[this.stack.length - n2];
}
*pop(error44) {
const token = error44 ?? this.stack.pop();
if (!token) {
const message = "Tried to pop an empty stack";
yield { type: "error", offset: this.offset, source: "", message };
} else if (this.stack.length === 0) {
yield token;
} else {
const top = this.peek(1);
if (token.type === "block-scalar") {
token.indent = "indent" in top ? top.indent : 0;
} else if (token.type === "flow-collection" && top.type === "document") {
token.indent = 0;
}
if (token.type === "flow-collection")
fixFlowSeqItems(token);
switch (top.type) {
case "document":
top.value = token;
break;
case "block-scalar":
top.props.push(token);
break;
case "block-map": {
const it = top.items[top.items.length - 1];
if (it.value) {
top.items.push({ start: [], key: token, sep: [] });
this.onKeyLine = true;
return;
} else if (it.sep) {
it.value = token;
} else {
Object.assign(it, { key: token, sep: [] });
this.onKeyLine = !it.explicitKey;
return;
}
break;
}
case "block-seq": {
const it = top.items[top.items.length - 1];
if (it.value)
top.items.push({ start: [], value: token });
else
it.value = token;
break;
}
case "flow-collection": {
const it = top.items[top.items.length - 1];
if (!it || it.value)
top.items.push({ start: [], key: token, sep: [] });
else if (it.sep)
it.value = token;
else
Object.assign(it, { key: token, sep: [] });
return;
}
default:
yield* this.pop();
yield* this.pop(token);
}
if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
const last2 = token.items[token.items.length - 1];
if (last2 && !last2.sep && !last2.value && last2.start.length > 0 && findNonEmptyIndex(last2.start) === -1 && (token.indent === 0 || last2.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
if (top.type === "document")
top.end = last2.start;
else
top.items.push({ start: last2.start });
token.items.splice(-1, 1);
}
}
}
}
*stream() {
switch (this.type) {
case "directive-line":
yield { type: "directive", offset: this.offset, source: this.source };
return;
case "byte-order-mark":
case "space":
case "comment":
case "newline":
yield this.sourceToken;
return;
case "doc-mode":
case "doc-start": {
const doc2 = {
type: "document",
offset: this.offset,
start: []
};
if (this.type === "doc-start")
doc2.start.push(this.sourceToken);
this.stack.push(doc2);
return;
}
}
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML stream`,
source: this.source
};
}
*document(doc2) {
if (doc2.value)
return yield* this.lineEnd(doc2);
switch (this.type) {
case "doc-start": {
if (findNonEmptyIndex(doc2.start) !== -1) {
yield* this.pop();
yield* this.step();
} else
doc2.start.push(this.sourceToken);
return;
}
case "anchor":
case "tag":
case "space":
case "comment":
case "newline":
doc2.start.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(doc2);
if (bv)
this.stack.push(bv);
else {
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML document`,
source: this.source
};
}
}
*scalar(scalar) {
if (this.type === "map-value-ind") {
const prev = getPrevProps(this.peek(2));
const start = getFirstKeyStartProps(prev);
let sep6;
if (scalar.end) {
sep6 = scalar.end;
sep6.push(this.sourceToken);
delete scalar.end;
} else
sep6 = [this.sourceToken];
const map3 = {
type: "block-map",
offset: scalar.offset,
indent: scalar.indent,
items: [{ start, key: scalar, sep: sep6 }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map3;
} else
yield* this.lineEnd(scalar);
}
*blockScalar(scalar) {
switch (this.type) {
case "space":
case "comment":
case "newline":
scalar.props.push(this.sourceToken);
return;
case "scalar":
scalar.source = this.source;
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine) {
let nl = this.source.indexOf(`
`) + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf(`
`, nl) + 1;
}
}
yield* this.pop();
break;
default:
yield* this.pop();
yield* this.step();
}
}
*blockMap(map3) {
const it = map3.items[map3.items.length - 1];
switch (this.type) {
case "newline":
this.onKeyLine = false;
if (it.value) {
const end = "end" in it.value ? it.value.end : undefined;
const last2 = Array.isArray(end) ? end[end.length - 1] : undefined;
if (last2?.type === "comment")
end?.push(this.sourceToken);
else
map3.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "space":
case "comment":
if (it.value) {
map3.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
if (this.atIndentedComment(it.start, map3.indent)) {
const prev = map3.items[map3.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
map3.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
}
if (this.indent >= map3.indent) {
const atMapIndent = !this.onKeyLine && this.indent === map3.indent;
const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
let start = [];
if (atNextItem && it.sep && !it.value) {
const nl = [];
for (let i2 = 0;i2 < it.sep.length; ++i2) {
const st = it.sep[i2];
switch (st.type) {
case "newline":
nl.push(i2);
break;
case "space":
break;
case "comment":
if (st.indent > map3.indent)
nl.length = 0;
break;
default:
nl.length = 0;
}
}
if (nl.length >= 2)
start = it.sep.splice(nl[1]);
}
switch (this.type) {
case "anchor":
case "tag":
if (atNextItem || it.value) {
start.push(this.sourceToken);
map3.items.push({ start });
this.onKeyLine = true;
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "explicit-key-ind":
if (!it.sep && !it.explicitKey) {
it.start.push(this.sourceToken);
it.explicitKey = true;
} else if (atNextItem || it.value) {
start.push(this.sourceToken);
map3.items.push({ start, explicitKey: true });
} else {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken], explicitKey: true }]
});
}
this.onKeyLine = true;
return;
case "map-value-ind":
if (it.explicitKey) {
if (!it.sep) {
if (includesToken(it.start, "newline")) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else {
const start2 = getFirstKeyStartProps(it.start);
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key: null, sep: [this.sourceToken] }]
});
}
} else if (it.value) {
map3.items.push({ start: [], key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
});
} else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
const start2 = getFirstKeyStartProps(it.start);
const key = it.key;
const sep6 = it.sep;
sep6.push(this.sourceToken);
delete it.key;
delete it.sep;
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key, sep: sep6 }]
});
} else if (start.length > 0) {
it.sep = it.sep.concat(start, this.sourceToken);
} else {
it.sep.push(this.sourceToken);
}
} else {
if (!it.sep) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else if (it.value || atNextItem) {
map3.items.push({ start, key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [], key: null, sep: [this.sourceToken] }]
});
} else {
it.sep.push(this.sourceToken);
}
}
this.onKeyLine = true;
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs2 = this.flowScalar(this.type);
if (atNextItem || it.value) {
map3.items.push({ start, key: fs2, sep: [] });
this.onKeyLine = true;
} else if (it.sep) {
this.stack.push(fs2);
} else {
Object.assign(it, { key: fs2, sep: [] });
this.onKeyLine = true;
}
return;
}
default: {
const bv = this.startBlockValue(map3);
if (bv) {
if (bv.type === "block-seq") {
if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) {
yield* this.pop({
type: "error",
offset: this.offset,
message: "Unexpected block-seq-ind on same line with key",
source: this.source
});
return;
}
} else if (atMapIndent) {
map3.items.push({ start });
}
this.stack.push(bv);
return;
}
}
}
}
yield* this.pop();
yield* this.step();
}
*blockSequence(seq) {
const it = seq.items[seq.items.length - 1];
switch (this.type) {
case "newline":
if (it.value) {
const end = "end" in it.value ? it.value.end : undefined;
const last2 = Array.isArray(end) ? end[end.length - 1] : undefined;
if (last2?.type === "comment")
end?.push(this.sourceToken);
else
seq.items.push({ start: [this.sourceToken] });
} else
it.start.push(this.sourceToken);
return;
case "space":
case "comment":
if (it.value)
seq.items.push({ start: [this.sourceToken] });
else {
if (this.atIndentedComment(it.start, seq.indent)) {
const prev = seq.items[seq.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
seq.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
case "anchor":
case "tag":
if (it.value || this.indent <= seq.indent)
break;
it.start.push(this.sourceToken);
return;
case "seq-item-ind":
if (this.indent !== seq.indent)
break;
if (it.value || includesToken(it.start, "seq-item-ind"))
seq.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
}
if (this.indent > seq.indent) {
const bv = this.startBlockValue(seq);
if (bv) {
this.stack.push(bv);
return;
}
}
yield* this.pop();
yield* this.step();
}
*flowCollection(fc) {
const it = fc.items[fc.items.length - 1];
if (this.type === "flow-error-end") {
let top;
do {
yield* this.pop();
top = this.peek(1);
} while (top?.type === "flow-collection");
} else if (fc.end.length === 0) {
switch (this.type) {
case "comma":
case "explicit-key-ind":
if (!it || it.sep)
fc.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
case "map-value-ind":
if (!it || it.value)
fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
Object.assign(it, { key: null, sep: [this.sourceToken] });
return;
case "space":
case "comment":
case "newline":
case "anchor":
case "tag":
if (!it || it.value)
fc.items.push({ start: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
it.start.push(this.sourceToken);
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs2 = this.flowScalar(this.type);
if (!it || it.value)
fc.items.push({ start: [], key: fs2, sep: [] });
else if (it.sep)
this.stack.push(fs2);
else
Object.assign(it, { key: fs2, sep: [] });
return;
}
case "flow-map-end":
case "flow-seq-end":
fc.end.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(fc);
if (bv)
this.stack.push(bv);
else {
yield* this.pop();
yield* this.step();
}
} else {
const parent = this.peek(2);
if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
yield* this.pop();
yield* this.step();
} else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
fixFlowSeqItems(fc);
const sep6 = fc.end.splice(1, fc.end.length);
sep6.push(this.sourceToken);
const map3 = {
type: "block-map",
offset: fc.offset,
indent: fc.indent,
items: [{ start, key: fc, sep: sep6 }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map3;
} else {
yield* this.lineEnd(fc);
}
}
}
flowScalar(type) {
if (this.onNewLine) {
let nl = this.source.indexOf(`
`) + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf(`
`, nl) + 1;
}
}
return {
type,
offset: this.offset,
indent: this.indent,
source: this.source
};
}
startBlockValue(parent) {
switch (this.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return this.flowScalar(this.type);
case "block-scalar-header":
return {
type: "block-scalar",
offset: this.offset,
indent: this.indent,
props: [this.sourceToken],
source: ""
};
case "flow-map-start":
case "flow-seq-start":
return {
type: "flow-collection",
offset: this.offset,
indent: this.indent,
start: this.sourceToken,
items: [],
end: []
};
case "seq-item-ind":
return {
type: "block-seq",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
};
case "explicit-key-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
start.push(this.sourceToken);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, explicitKey: true }]
};
}
case "map-value-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
};
}
}
return null;
}
atIndentedComment(start, indent) {
if (this.type !== "comment")
return false;
if (this.indent <= indent)
return false;
return start.every((st) => st.type === "newline" || st.type === "space");
}
*documentEnd(docEnd) {
if (this.type !== "doc-mode") {
if (docEnd.end)
docEnd.end.push(this.sourceToken);
else
docEnd.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
*lineEnd(token) {
switch (this.type) {
case "comma":
case "doc-start":
case "doc-end":
case "flow-seq-end":
case "flow-map-end":
case "map-value-ind":
yield* this.pop();
yield* this.step();
break;
case "newline":
this.onKeyLine = false;
case "space":
case "comment":
default:
if (token.end)
token.end.push(this.sourceToken);
else
token.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
}
exports.Parser = Parser2;
});
// node_modules/yaml/dist/public-api.js
var require_public_api = __commonJS((exports) => {
var composer = require_composer();
var Document = require_Document();
var errors3 = require_errors6();
var log2 = require_log();
var identity4 = require_identity();
var lineCounter = require_line_counter();
var parser = require_parser();
function parseOptions(options) {
const prettyErrors = options.prettyErrors !== false;
const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter || null;
return { lineCounter: lineCounter$1, prettyErrors };
}
function parseAllDocuments(source, options = {}) {
const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
const composer$1 = new composer.Composer(options);
const docs = Array.from(composer$1.compose(parser$1.parse(source)));
if (prettyErrors && lineCounter2)
for (const doc2 of docs) {
doc2.errors.forEach(errors3.prettifyError(source, lineCounter2));
doc2.warnings.forEach(errors3.prettifyError(source, lineCounter2));
}
if (docs.length > 0)
return docs;
return Object.assign([], { empty: true }, composer$1.streamInfo());
}
function parseDocument(source, options = {}) {
const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
const composer$1 = new composer.Composer(options);
let doc2 = null;
for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
if (!doc2)
doc2 = _doc;
else if (doc2.options.logLevel !== "silent") {
doc2.errors.push(new errors3.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
break;
}
}
if (prettyErrors && lineCounter2) {
doc2.errors.forEach(errors3.prettifyError(source, lineCounter2));
doc2.warnings.forEach(errors3.prettifyError(source, lineCounter2));
}
return doc2;
}
function parse7(src, reviver, options) {
let _reviver = undefined;
if (typeof reviver === "function") {
_reviver = reviver;
} else if (options === undefined && reviver && typeof reviver === "object") {
options = reviver;
}
const doc2 = parseDocument(src, options);
if (!doc2)
return null;
doc2.warnings.forEach((warning) => log2.warn(doc2.options.logLevel, warning));
if (doc2.errors.length > 0) {
if (doc2.options.logLevel !== "silent")
throw doc2.errors[0];
else
doc2.errors = [];
}
return doc2.toJS(Object.assign({ reviver: _reviver }, options));
}
function stringify(value, replacer, options) {
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options === undefined && replacer) {
options = replacer;
}
if (typeof options === "string")
options = options.length;
if (typeof options === "number") {
const indent = Math.round(options);
options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
}
if (value === undefined) {
const { keepUndefined } = options ?? replacer ?? {};
if (!keepUndefined)
return;
}
if (identity4.isDocument(value) && !_replacer)
return value.toString(options);
return new Document.Document(value, _replacer, options).toString(options);
}
exports.parse = parse7;
exports.parseAllDocuments = parseAllDocuments;
exports.parseDocument = parseDocument;
exports.stringify = stringify;
});
// node_modules/yaml/dist/index.js
var require_dist4 = __commonJS((exports) => {
var composer = require_composer();
var Document = require_Document();
var Schema = require_Schema();
var errors3 = require_errors6();
var Alias = require_Alias();
var identity4 = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var cst = require_cst();
var lexer = require_lexer();
var lineCounter = require_line_counter();
var parser = require_parser();
var publicApi = require_public_api();
var visit2 = require_visit();
exports.Composer = composer.Composer;
exports.Document = Document.Document;
exports.Schema = Schema.Schema;
exports.YAMLError = errors3.YAMLError;
exports.YAMLParseError = errors3.YAMLParseError;
exports.YAMLWarning = errors3.YAMLWarning;
exports.Alias = Alias.Alias;
exports.isAlias = identity4.isAlias;
exports.isCollection = identity4.isCollection;
exports.isDocument = identity4.isDocument;
exports.isMap = identity4.isMap;
exports.isNode = identity4.isNode;
exports.isPair = identity4.isPair;
exports.isScalar = identity4.isScalar;
exports.isSeq = identity4.isSeq;
exports.Pair = Pair.Pair;
exports.Scalar = Scalar.Scalar;
exports.YAMLMap = YAMLMap.YAMLMap;
exports.YAMLSeq = YAMLSeq.YAMLSeq;
exports.CST = cst;
exports.Lexer = lexer.Lexer;
exports.LineCounter = lineCounter.LineCounter;
exports.Parser = parser.Parser;
exports.parse = publicApi.parse;
exports.parseAllDocuments = publicApi.parseAllDocuments;
exports.parseDocument = publicApi.parseDocument;
exports.stringify = publicApi.stringify;
exports.visit = visit2.visit;
exports.visitAsync = visit2.visitAsync;
});
// src/utils/yaml.ts
function parseYaml(input) {
if (typeof Bun !== "undefined") {
return Bun.YAML.parse(input);
}
return require_dist4().parse(input);
}
// src/utils/frontmatterParser.ts
function quoteProblematicValues(frontmatterText) {
const lines = frontmatterText.split(`
`);
const result = [];
for (const line of lines) {
const match = line.match(/^([a-zA-Z_-]+):\s+(.+)$/);
if (match) {
const [, key, value] = match;
if (!key || !value) {
result.push(line);
continue;
}
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
result.push(line);
continue;
}
if (YAML_SPECIAL_CHARS.test(value)) {
const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
result.push(`${key}: "${escaped}"`);
continue;
}
}
result.push(line);
}
return result.join(`
`);
}
function parseFrontmatter(markdown, sourcePath) {
const match = markdown.match(FRONTMATTER_REGEX);
if (!match) {
return {
frontmatter: {},
content: markdown
};
}
const frontmatterText = match[1] || "";
const content = markdown.slice(match[0].length);
let frontmatter = {};
try {
const parsed = parseYaml(frontmatterText);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
frontmatter = parsed;
}
} catch {
try {
const quotedText = quoteProblematicValues(frontmatterText);
const parsed = parseYaml(quotedText);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
frontmatter = parsed;
}
} catch (retryError) {
const location = sourcePath ? ` in ${sourcePath}` : "";
logForDebugging(`Failed to parse YAML frontmatter${location}: ${retryError instanceof Error ? retryError.message : retryError}`, { level: "warn" });
}
}
return {
frontmatter,
content
};
}
function splitPathInFrontmatter(input) {
if (Array.isArray(input)) {
return input.flatMap(splitPathInFrontmatter);
}
if (typeof input !== "string") {
return [];
}
const parts = [];
let current = "";
let braceDepth = 0;
for (let i2 = 0;i2 < input.length; i2++) {
const char = input[i2];
if (char === "{") {
braceDepth++;
current += char;
} else if (char === "}") {
braceDepth--;
current += char;
} else if (char === "," && braceDepth === 0) {
const trimmed2 = current.trim();
if (trimmed2) {
parts.push(trimmed2);
}
current = "";
} else {
current += char;
}
}
const trimmed = current.trim();
if (trimmed) {
parts.push(trimmed);
}
return parts.filter((p) => p.length > 0).flatMap((pattern) => expandBraces(pattern));
}
function expandBraces(pattern) {
const braceMatch = pattern.match(/^([^{]*)\{([^}]+)\}(.*)$/);
if (!braceMatch) {
return [pattern];
}
const prefix = braceMatch[1] || "";
const alternatives = braceMatch[2] || "";
const suffix = braceMatch[3] || "";
const parts = alternatives.split(",").map((alt) => alt.trim());
const expanded = [];
for (const part of parts) {
const combined = prefix + part + suffix;
const furtherExpanded = expandBraces(combined);
expanded.push(...furtherExpanded);
}
return expanded;
}
function parsePositiveIntFromFrontmatter(value) {
if (value === undefined || value === null) {
return;
}
const parsed = typeof value === "number" ? value : parseInt(String(value), 10);
if (Number.isInteger(parsed) && parsed > 0) {
return parsed;
}
return;
}
function coerceDescriptionToString(value, componentName, pluginName) {
if (value == null) {
return null;
}
if (typeof value === "string") {
return value.trim() || null;
}
if (typeof value === "number" || typeof value === "boolean") {
return String(value);
}
const source = pluginName ? `${pluginName}:${componentName}` : componentName ?? "unknown";
logForDebugging(`Description invalid for ${source} - omitting`, {
level: "warn"
});
return null;
}
function parseBooleanFrontmatter(value) {
return value === true || value === "true";
}
function parseShellFrontmatter(value, source) {
if (value == null) {
return;
}
const normalized = String(value).trim().toLowerCase();
if (normalized === "") {
return;
}
if (FRONTMATTER_SHELLS.includes(normalized)) {
return normalized;
}
logForDebugging(`Frontmatter 'shell: ${value}' in ${source} is not recognized. Valid values: ${FRONTMATTER_SHELLS.join(", ")}. Falling back to bash.`, { level: "warn" });
return;
}
var YAML_SPECIAL_CHARS, FRONTMATTER_REGEX, FRONTMATTER_SHELLS;
var init_frontmatterParser = __esm(() => {
init_debug();
YAML_SPECIAL_CHARS = /[{}[\]*!|>%@`]|: /;
FRONTMATTER_REGEX = /^---\s*\n([\s\S]*?)---\s*\n?/;
FRONTMATTER_SHELLS = ["bash", "powershell"];
});
// src/utils/ripgrep.ts
import { execFile as execFile3, spawn as spawn2 } from "child_process";
import { existsSync as existsSync4 } from "fs";
import { homedir as homedir11 } from "os";
import * as path10 from "path";
import { fileURLToPath as fileURLToPath3 } from "url";
function ripgrepCommand() {
const config2 = getRipgrepConfig();
return {
rgPath: config2.command,
rgArgs: config2.args,
argv0: config2.argv0
};
}
function isEagainError(stderr) {
return stderr.includes("os error 11") || stderr.includes("Resource temporarily unavailable");
}
function ripGrepRaw(args, target, abortSignal, callback, singleThread = false) {
const { rgPath, rgArgs, argv0 } = ripgrepCommand();
const threadArgs = singleThread ? ["-j", "1"] : [];
const fullArgs = [...rgArgs, ...threadArgs, ...args, target];
const defaultTimeout = getPlatform() === "wsl" ? 60000 : 20000;
const parsedSeconds = parseInt(process.env.CLAUDE_CODE_GLOB_TIMEOUT_SECONDS || "", 10) || 0;
const timeout = parsedSeconds > 0 ? parsedSeconds * 1000 : defaultTimeout;
if (argv0) {
const child = spawn2(rgPath, fullArgs, {
argv0,
signal: abortSignal,
windowsHide: true
});
let stdout = "";
let stderr = "";
let stdoutTruncated = false;
let stderrTruncated = false;
child.stdout?.on("data", (data) => {
if (!stdoutTruncated) {
stdout += data.toString();
if (stdout.length > MAX_BUFFER_SIZE) {
stdout = stdout.slice(0, MAX_BUFFER_SIZE);
stdoutTruncated = true;
}
}
});
child.stderr?.on("data", (data) => {
if (!stderrTruncated) {
stderr += data.toString();
if (stderr.length > MAX_BUFFER_SIZE) {
stderr = stderr.slice(0, MAX_BUFFER_SIZE);
stderrTruncated = true;
}
}
});
let killTimeoutId;
const timeoutId = setTimeout(() => {
if (process.platform === "win32") {
child.kill();
} else {
child.kill("SIGTERM");
killTimeoutId = setTimeout((c7) => c7.kill("SIGKILL"), 5000, child);
}
}, timeout);
let settled = false;
child.on("close", (code, signal) => {
if (settled)
return;
settled = true;
clearTimeout(timeoutId);
clearTimeout(killTimeoutId);
if (code === 0 || code === 1) {
callback(null, stdout, stderr);
} else {
const error44 = new Error(`ripgrep exited with code ${code}`);
error44.code = code ?? undefined;
error44.signal = signal ?? undefined;
callback(error44, stdout, stderr);
}
});
child.on("error", (err) => {
if (settled)
return;
settled = true;
clearTimeout(timeoutId);
clearTimeout(killTimeoutId);
const error44 = err;
callback(error44, stdout, stderr);
});
return child;
}
return execFile3(rgPath, fullArgs, {
maxBuffer: MAX_BUFFER_SIZE,
signal: abortSignal,
timeout,
killSignal: process.platform === "win32" ? undefined : "SIGKILL"
}, callback);
}
async function ripGrepFileCount(args, target, abortSignal) {
await codesignRipgrepIfNecessary();
const { rgPath, rgArgs, argv0 } = ripgrepCommand();
return new Promise((resolve13, reject) => {
const child = spawn2(rgPath, [...rgArgs, ...args, target], {
argv0,
signal: abortSignal,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"]
});
let lines = 0;
child.stdout?.on("data", (chunk) => {
lines += countCharInString(chunk, `
`);
});
let settled = false;
child.on("close", (code) => {
if (settled)
return;
settled = true;
if (code === 0 || code === 1)
resolve13(lines);
else
reject(new Error(`rg --files exited ${code}`));
});
child.on("error", (err) => {
if (settled)
return;
settled = true;
reject(err);
});
});
}
async function ripGrep(args, target, abortSignal) {
await codesignRipgrepIfNecessary();
testRipgrepOnFirstUse().catch((error44) => {
logError2(error44);
});
return new Promise((resolve13, reject) => {
const handleResult2 = (error44, stdout, stderr, isRetry) => {
if (!error44) {
resolve13(stdout.trim().split(`
`).map((line) => line.replace(/\r$/, "")).filter(Boolean));
return;
}
if (error44.code === 1) {
resolve13([]);
return;
}
const CRITICAL_ERROR_CODES = ["ENOENT", "EACCES", "EPERM"];
if (CRITICAL_ERROR_CODES.includes(error44.code)) {
reject(error44);
return;
}
if (!isRetry && isEagainError(stderr)) {
logForDebugging(`rg EAGAIN error detected, retrying with single-threaded mode (-j 1)`);
logEvent("tengu_ripgrep_eagain_retry", {});
ripGrepRaw(args, target, abortSignal, (retryError, retryStdout, retryStderr) => {
handleResult2(retryError, retryStdout, retryStderr, true);
}, true);
return;
}
const hasOutput = stdout && stdout.trim().length > 0;
const isTimeout = error44.signal === "SIGTERM" || error44.signal === "SIGKILL" || error44.code === "ABORT_ERR";
const isBufferOverflow = error44.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
let lines = [];
if (hasOutput) {
lines = stdout.trim().split(`
`).map((line) => line.replace(/\r$/, "")).filter(Boolean);
if (lines.length > 0 && (isTimeout || isBufferOverflow)) {
lines = lines.slice(0, -1);
}
}
logForDebugging(`rg error (signal=${error44.signal}, code=${error44.code}, stderr: ${stderr}), ${lines.length} results`);
if (error44.code !== 2 && error44.code !== "ABORT_ERR") {
logError2(error44);
}
if (isTimeout && lines.length === 0) {
reject(new RipgrepTimeoutError(`Ripgrep search timed out after ${getPlatform() === "wsl" ? 60 : 20} seconds. The search may have matched files but did not complete in time. Try searching a more specific path or pattern.`, lines));
return;
}
resolve13(lines);
};
ripGrepRaw(args, target, abortSignal, (error44, stdout, stderr) => {
handleResult2(error44, stdout, stderr, false);
});
});
}
function getRipgrepStatus() {
const config2 = getRipgrepConfig();
return {
mode: config2.mode,
path: config2.command,
working: ripgrepStatus?.working ?? null
};
}
async function codesignRipgrepIfNecessary() {
if (process.platform !== "darwin" || alreadyDoneSignCheck) {
return;
}
alreadyDoneSignCheck = true;
const config2 = getRipgrepConfig();
if (config2.mode !== "builtin") {
return;
}
const builtinPath = config2.command;
const lines = (await execFileNoThrow("codesign", ["-vv", "-d", builtinPath], {
preserveOutputOnError: false
})).stdout.split(`
`);
const needsSigned = lines.find((line) => line.includes("linker-signed"));
if (!needsSigned) {
return;
}
try {
const signResult = await execFileNoThrow("codesign", [
"--sign",
"-",
"--force",
"--preserve-metadata=entitlements,requirements,flags,runtime",
builtinPath
]);
if (signResult.code !== 0) {
logError2(new Error(`Failed to sign ripgrep: ${signResult.stdout} ${signResult.stderr}`));
}
const quarantineResult = await execFileNoThrow("xattr", [
"-d",
"com.apple.quarantine",
builtinPath
]);
if (quarantineResult.code !== 0) {
logError2(new Error(`Failed to remove quarantine: ${quarantineResult.stdout} ${quarantineResult.stderr}`));
}
} catch (e) {
logError2(e);
}
}
var __filename2, __dirname2, getRipgrepConfig, MAX_BUFFER_SIZE = 20000000, RipgrepTimeoutError, countFilesRoundedRg, ripgrepStatus = null, testRipgrepOnFirstUse, alreadyDoneSignCheck = false;
var init_ripgrep = __esm(() => {
init_memoize();
init_analytics();
init_debug();
init_envUtils();
init_execFileNoThrow();
init_findExecutable();
init_log3();
init_platform2();
init_stringUtils();
__filename2 = fileURLToPath3(import.meta.url);
__dirname2 = path10.join(__filename2, "../");
getRipgrepConfig = memoize_default(() => {
const userWantsSystemRipgrep = isEnvDefinedFalsy(process.env.USE_BUILTIN_RIPGREP);
if (userWantsSystemRipgrep) {
const { cmd: systemPath } = findExecutable2("rg", []);
if (systemPath !== "rg") {
return { mode: "system", command: "rg", args: [] };
}
}
if (isInBundledMode()) {
return {
mode: "embedded",
command: process.execPath,
args: ["--no-config"],
argv0: "rg"
};
}
const rgRoot = path10.resolve(__dirname2, "vendor", "ripgrep");
const command = process.platform === "win32" ? path10.resolve(rgRoot, `${process.arch}-win32`, "rg.exe") : path10.resolve(rgRoot, `${process.arch}-${process.platform}`, "rg");
if (!existsSync4(command)) {
return { mode: "system", command: "rg", args: [] };
}
return { mode: "builtin", command, args: [] };
});
RipgrepTimeoutError = class RipgrepTimeoutError extends Error {
partialResults;
constructor(message, partialResults) {
super(message);
this.partialResults = partialResults;
this.name = "RipgrepTimeoutError";
}
};
countFilesRoundedRg = memoize_default(async (dirPath, abortSignal, ignorePatterns = []) => {
if (path10.resolve(dirPath) === path10.resolve(homedir11())) {
return;
}
try {
const args = ["--files", "--hidden"];
ignorePatterns.forEach((pattern) => {
args.push("--glob", `!${pattern}`);
});
const count3 = await ripGrepFileCount(args, dirPath, abortSignal);
if (count3 === 0)
return 0;
const magnitude = Math.floor(Math.log10(count3));
const power = Math.pow(10, magnitude);
return Math.round(count3 / power) * power;
} catch (error44) {
if (error44?.name !== "AbortError")
logError2(error44);
}
}, (dirPath, _abortSignal, ignorePatterns = []) => `${dirPath}|${ignorePatterns.join(",")}`);
testRipgrepOnFirstUse = memoize_default(async () => {
if (ripgrepStatus !== null) {
return;
}
const config2 = getRipgrepConfig();
try {
let test2;
if (config2.argv0) {
const proc = Bun.spawn([config2.command, "--version"], {
argv0: config2.argv0,
stderr: "ignore",
stdout: "pipe"
});
const [stdout, code] = await Promise.all([
proc.stdout.text(),
proc.exited
]);
test2 = {
code,
stdout
};
} else {
test2 = await execFileNoThrow(config2.command, [...config2.args, "--version"], {
timeout: 5000
});
}
const working = test2.code === 0 && !!test2.stdout && test2.stdout.startsWith("ripgrep ");
ripgrepStatus = {
working,
lastTested: Date.now(),
config: config2
};
logForDebugging(`Ripgrep first use test: ${working ? "PASSED" : "FAILED"} (mode=${config2.mode}, path=${config2.command})`);
logEvent("tengu_ripgrep_availability", {
working: working ? 1 : 0,
using_system: config2.mode === "system" ? 1 : 0
});
} catch (error44) {
ripgrepStatus = {
working: false,
lastTested: Date.now(),
config: config2
};
logError2(error44);
}
});
});
// src/utils/settings/pluginOnlyPolicy.ts
function isRestrictedToPluginOnly(surface) {
const policy = getSettingsForSource("policySettings")?.strictPluginOnlyCustomization;
if (policy === true)
return true;
if (Array.isArray(policy))
return policy.includes(surface);
return false;
}
function isSourceAdminTrusted(source) {
return source !== undefined && ADMIN_TRUSTED_SOURCES.has(source);
}
var ADMIN_TRUSTED_SOURCES;
var init_pluginOnlyPolicy = __esm(() => {
init_settings2();
ADMIN_TRUSTED_SOURCES = new Set([
"plugin",
"policySettings",
"built-in",
"builtin",
"bundled"
]);
});
// src/utils/markdownConfigLoader.ts
import { statSync as statSync4 } from "fs";
import { lstat as lstat3, readdir as readdir6, readFile as readFile8, realpath as realpath5, stat as stat13 } from "fs/promises";
import { homedir as homedir12 } from "os";
import { dirname as dirname16, join as join28, resolve as resolve13, sep as sep6 } from "path";
function extractDescriptionFromMarkdown(content, defaultDescription = "Custom item") {
const lines = content.split(`
`);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed) {
const headerMatch = trimmed.match(/^#+\s+(.+)$/);
const text = headerMatch?.[1] ?? trimmed;
return text.length > 100 ? text.substring(0, 97) + "..." : text;
}
}
return defaultDescription;
}
function parseToolListString(toolsValue) {
if (toolsValue === undefined || toolsValue === null) {
return null;
}
if (!toolsValue) {
return [];
}
let toolsArray = [];
if (typeof toolsValue === "string") {
toolsArray = [toolsValue];
} else if (Array.isArray(toolsValue)) {
toolsArray = toolsValue.filter((item) => typeof item === "string");
}
if (toolsArray.length === 0) {
return [];
}
const parsedTools = parseToolListFromCLI(toolsArray);
if (parsedTools.includes("*")) {
return ["*"];
}
return parsedTools;
}
function parseAgentToolsFromFrontmatter(toolsValue) {
const parsed = parseToolListString(toolsValue);
if (parsed === null) {
return toolsValue === undefined ? undefined : [];
}
if (parsed.includes("*")) {
return;
}
return parsed;
}
function parseSlashCommandToolsFromFrontmatter(toolsValue) {
const parsed = parseToolListString(toolsValue);
if (parsed === null) {
return [];
}
return parsed;
}
async function getFileIdentity(filePath) {
try {
const stats = await lstat3(filePath, { bigint: true });
if (stats.dev === 0n && stats.ino === 0n) {
return null;
}
return `${stats.dev}:${stats.ino}`;
} catch {
return null;
}
}
function resolveStopBoundary(cwd2) {
const cwdGitRoot = findGitRoot(cwd2);
const sessionGitRoot = findGitRoot(getProjectRoot());
if (!cwdGitRoot || !sessionGitRoot) {
return cwdGitRoot;
}
const cwdCanonical = findCanonicalGitRoot(cwd2);
if (cwdCanonical && normalizePathForComparison(cwdCanonical) === normalizePathForComparison(sessionGitRoot)) {
return cwdGitRoot;
}
const nCwdGitRoot = normalizePathForComparison(cwdGitRoot);
const nSessionRoot = normalizePathForComparison(sessionGitRoot);
if (nCwdGitRoot !== nSessionRoot && nCwdGitRoot.startsWith(nSessionRoot + sep6)) {
return sessionGitRoot;
}
return cwdGitRoot;
}
function getProjectDirsUpToHome(subdir, cwd2) {
const home = resolve13(homedir12()).normalize("NFC");
const gitRoot = resolveStopBoundary(cwd2);
let current = resolve13(cwd2);
const dirs = [];
while (true) {
if (normalizePathForComparison(current) === normalizePathForComparison(home)) {
break;
}
const claudeSubdir = join28(current, ".claude", subdir);
try {
statSync4(claudeSubdir);
dirs.push(claudeSubdir);
} catch (e) {
if (!isFsInaccessible(e))
throw e;
}
if (gitRoot && normalizePathForComparison(current) === normalizePathForComparison(gitRoot)) {
break;
}
const parent = dirname16(current);
if (parent === current) {
break;
}
current = parent;
}
return dirs;
}
async function findMarkdownFilesNative(dir, signal) {
const files = [];
const visitedDirs = new Set;
async function walk(currentDir) {
if (signal.aborted) {
return;
}
try {
const stats = await stat13(currentDir, { bigint: true });
if (stats.isDirectory()) {
const dirKey = stats.dev !== undefined && stats.ino !== undefined ? `${stats.dev}:${stats.ino}` : await realpath5(currentDir);
if (visitedDirs.has(dirKey)) {
logForDebugging(`Skipping already visited directory (circular symlink): ${currentDir}`);
return;
}
visitedDirs.add(dirKey);
}
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Failed to stat directory ${currentDir}: ${errorMessage2}`);
return;
}
try {
const entries = await readdir6(currentDir, { withFileTypes: true });
for (const entry of entries) {
if (signal.aborted) {
break;
}
const fullPath = join28(currentDir, entry.name);
try {
if (entry.isSymbolicLink()) {
try {
const stats = await stat13(fullPath);
if (stats.isDirectory()) {
await walk(fullPath);
} else if (stats.isFile() && entry.name.endsWith(".md")) {
files.push(fullPath);
}
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Failed to follow symlink ${fullPath}: ${errorMessage2}`);
}
} else if (entry.isDirectory()) {
await walk(fullPath);
} else if (entry.isFile() && entry.name.endsWith(".md")) {
files.push(fullPath);
}
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Failed to access ${fullPath}: ${errorMessage2}`);
}
}
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Failed to read directory ${currentDir}: ${errorMessage2}`);
}
}
await walk(dir);
return files;
}
async function loadMarkdownFiles(dir) {
const useNative = isEnvTruthy(process.env.CLAUDE_CODE_USE_NATIVE_FILE_SEARCH);
const signal = AbortSignal.timeout(3000);
let files;
try {
files = useNative ? await findMarkdownFilesNative(dir, signal) : await ripGrep(["--files", "--hidden", "--follow", "--no-ignore", "--glob", "*.md"], dir, signal);
} catch (e) {
if (isFsInaccessible(e))
return [];
throw e;
}
const results = await Promise.all(files.map(async (filePath) => {
try {
const rawContent = await readFile8(filePath, { encoding: "utf-8" });
const { frontmatter, content } = parseFrontmatter(rawContent, filePath);
return {
filePath,
frontmatter,
content
};
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Failed to read/parse markdown file: ${filePath}: ${errorMessage2}`);
return null;
}
}));
return results.filter((_) => _ !== null);
}
var CLAUDE_CONFIG_DIRECTORIES, loadMarkdownFilesForSubdir;
var init_markdownConfigLoader = __esm(() => {
init_memoize();
init_analytics();
init_state();
init_debug();
init_envUtils();
init_errors();
init_file();
init_frontmatterParser();
init_git();
init_permissionSetup();
init_ripgrep();
init_constants2();
init_managedPath();
init_pluginOnlyPolicy();
CLAUDE_CONFIG_DIRECTORIES = [
"commands",
"agents",
"output-styles",
"skills",
"workflows",
...[]
];
loadMarkdownFilesForSubdir = memoize_default(async function(subdir, cwd2) {
const searchStartTime = Date.now();
const userDir = join28(getClaudeConfigHomeDir(), subdir);
const managedDir = join28(getManagedFilePath(), ".claude", subdir);
const projectDirs = getProjectDirsUpToHome(subdir, cwd2);
const gitRoot = findGitRoot(cwd2);
const canonicalRoot = findCanonicalGitRoot(cwd2);
if (gitRoot && canonicalRoot && canonicalRoot !== gitRoot) {
const worktreeSubdir = normalizePathForComparison(join28(gitRoot, ".claude", subdir));
const worktreeHasSubdir = projectDirs.some((dir) => normalizePathForComparison(dir) === worktreeSubdir);
if (!worktreeHasSubdir) {
const mainClaudeSubdir = join28(canonicalRoot, ".claude", subdir);
if (!projectDirs.includes(mainClaudeSubdir)) {
projectDirs.push(mainClaudeSubdir);
}
}
}
const [managedFiles, userFiles, projectFilesNested] = await Promise.all([
loadMarkdownFiles(managedDir).then((_) => _.map((file2) => ({
...file2,
baseDir: managedDir,
source: "policySettings"
}))),
isSettingSourceEnabled("userSettings") && !(subdir === "agents" && isRestrictedToPluginOnly("agents")) ? loadMarkdownFiles(userDir).then((_) => _.map((file2) => ({
...file2,
baseDir: userDir,
source: "userSettings"
}))) : Promise.resolve([]),
isSettingSourceEnabled("projectSettings") && !(subdir === "agents" && isRestrictedToPluginOnly("agents")) ? Promise.all(projectDirs.map((projectDir) => loadMarkdownFiles(projectDir).then((_) => _.map((file2) => ({
...file2,
baseDir: projectDir,
source: "projectSettings"
}))))) : Promise.resolve([])
]);
const projectFiles = projectFilesNested.flat();
const allFiles = [...managedFiles, ...userFiles, ...projectFiles];
const fileIdentities = await Promise.all(allFiles.map((file2) => getFileIdentity(file2.filePath)));
const seenFileIds = new Map;
const deduplicatedFiles = [];
for (const [i2, file2] of allFiles.entries()) {
const fileId = fileIdentities[i2] ?? null;
if (fileId === null) {
deduplicatedFiles.push(file2);
continue;
}
const existingSource = seenFileIds.get(fileId);
if (existingSource !== undefined) {
logForDebugging(`Skipping duplicate file '${file2.filePath}' from ${file2.source} (same inode already loaded from ${existingSource})`);
continue;
}
seenFileIds.set(fileId, file2.source);
deduplicatedFiles.push(file2);
}
const duplicatesRemoved = allFiles.length - deduplicatedFiles.length;
if (duplicatesRemoved > 0) {
logForDebugging(`Deduplicated ${duplicatesRemoved} files in ${subdir} (same inode via symlinks or hard links)`);
}
logEvent(`tengu_dir_search`, {
durationMs: Date.now() - searchStartTime,
managedFilesFound: managedFiles.length,
userFilesFound: userFiles.length,
projectFilesFound: projectFiles.length,
projectDirsSearched: projectDirs.length,
subdir
});
return deduplicatedFiles;
}, (subdir, cwd2) => `${subdir}:${cwd2}`);
});
// src/types/plugin.ts
function getPluginErrorMessage(error44) {
switch (error44.type) {
case "generic-error":
return error44.error;
case "path-not-found":
return `Path not found: ${error44.path} (${error44.component})`;
case "git-auth-failed":
return `Git authentication failed (${error44.authType}): ${error44.gitUrl}`;
case "git-timeout":
return `Git ${error44.operation} timeout: ${error44.gitUrl}`;
case "network-error":
return `Network error: ${error44.url}${error44.details ? ` - ${error44.details}` : ""}`;
case "manifest-parse-error":
return `Manifest parse error: ${error44.parseError}`;
case "manifest-validation-error":
return `Manifest validation failed: ${error44.validationErrors.join(", ")}`;
case "plugin-not-found":
return `Plugin ${error44.pluginId} not found in marketplace ${error44.marketplace}`;
case "marketplace-not-found":
return `Marketplace ${error44.marketplace} not found`;
case "marketplace-load-failed":
return `Marketplace ${error44.marketplace} failed to load: ${error44.reason}`;
case "mcp-config-invalid":
return `MCP server ${error44.serverName} invalid: ${error44.validationError}`;
case "mcp-server-suppressed-duplicate": {
const dup = error44.duplicateOf.startsWith("plugin:") ? `server provided by plugin "${error44.duplicateOf.split(":")[1] ?? "?"}"` : `already-configured "${error44.duplicateOf}"`;
return `MCP server "${error44.serverName}" skipped — same command/URL as ${dup}`;
}
case "hook-load-failed":
return `Hook load failed: ${error44.reason}`;
case "component-load-failed":
return `${error44.component} load failed from ${error44.path}: ${error44.reason}`;
case "mcpb-download-failed":
return `Failed to download MCPB from ${error44.url}: ${error44.reason}`;
case "mcpb-extract-failed":
return `Failed to extract MCPB ${error44.mcpbPath}: ${error44.reason}`;
case "mcpb-invalid-manifest":
return `MCPB manifest invalid at ${error44.mcpbPath}: ${error44.validationError}`;
case "lsp-config-invalid":
return `Plugin "${error44.plugin}" has invalid LSP server config for "${error44.serverName}": ${error44.validationError}`;
case "lsp-server-start-failed":
return `Plugin "${error44.plugin}" failed to start LSP server "${error44.serverName}": ${error44.reason}`;
case "lsp-server-crashed":
if (error44.signal) {
return `Plugin "${error44.plugin}" LSP server "${error44.serverName}" crashed with signal ${error44.signal}`;
}
return `Plugin "${error44.plugin}" LSP server "${error44.serverName}" crashed with exit code ${error44.exitCode ?? "unknown"}`;
case "lsp-request-timeout":
return `Plugin "${error44.plugin}" LSP server "${error44.serverName}" timed out on ${error44.method} request after ${error44.timeoutMs}ms`;
case "lsp-request-failed":
return `Plugin "${error44.plugin}" LSP server "${error44.serverName}" ${error44.method} request failed: ${error44.error}`;
case "marketplace-blocked-by-policy":
if (error44.blockedByBlocklist) {
return `Marketplace '${error44.marketplace}' is blocked by enterprise policy`;
}
return `Marketplace '${error44.marketplace}' is not in the allowed marketplace list`;
case "dependency-unsatisfied": {
const hint = error44.reason === "not-enabled" ? "disabled — enable it or remove the dependency" : "not found in any configured marketplace";
return `Dependency "${error44.dependency}" is ${hint}`;
}
case "plugin-cache-miss":
return `Plugin "${error44.plugin}" not cached at ${error44.installPath} — run /plugins to refresh`;
}
}
// src/plugins/builtinPlugins.ts
function isBuiltinPluginId(pluginId) {
return pluginId.endsWith(`@${BUILTIN_MARKETPLACE_NAME}`);
}
function getBuiltinPluginDefinition(name) {
return BUILTIN_PLUGINS.get(name);
}
function getBuiltinPlugins() {
const settings = getSettings_DEPRECATED();
const enabled = [];
const disabled = [];
for (const [name, definition] of BUILTIN_PLUGINS) {
if (definition.isAvailable && !definition.isAvailable()) {
continue;
}
const pluginId = `${name}@${BUILTIN_MARKETPLACE_NAME}`;
const userSetting = settings?.enabledPlugins?.[pluginId];
const isEnabled = userSetting !== undefined ? userSetting === true : definition.defaultEnabled ?? true;
const plugin = {
name,
manifest: {
name,
description: definition.description,
version: definition.version
},
path: BUILTIN_MARKETPLACE_NAME,
source: pluginId,
repository: pluginId,
enabled: isEnabled,
isBuiltin: true,
hooksConfig: definition.hooks,
mcpServers: definition.mcpServers
};
if (isEnabled) {
enabled.push(plugin);
} else {
disabled.push(plugin);
}
}
return { enabled, disabled };
}
function getBuiltinPluginSkillCommands() {
const { enabled } = getBuiltinPlugins();
const commands = [];
for (const plugin of enabled) {
const definition = BUILTIN_PLUGINS.get(plugin.name);
if (!definition?.skills)
continue;
for (const skill of definition.skills) {
commands.push(skillDefinitionToCommand(skill));
}
}
return commands;
}
function skillDefinitionToCommand(definition) {
return {
type: "prompt",
name: definition.name,
description: definition.description,
hasUserSpecifiedDescription: true,
allowedTools: definition.allowedTools ?? [],
argumentHint: definition.argumentHint,
whenToUse: definition.whenToUse,
model: definition.model,
disableModelInvocation: definition.disableModelInvocation ?? false,
userInvocable: definition.userInvocable ?? true,
contentLength: 0,
source: "bundled",
loadedFrom: "bundled",
hooks: definition.hooks,
context: definition.context,
agent: definition.agent,
isEnabled: definition.isEnabled ?? (() => true),
isHidden: !(definition.userInvocable ?? true),
progressMessage: "running",
getPromptForCommand: definition.getPromptForCommand
};
}
var BUILTIN_PLUGINS, BUILTIN_MARKETPLACE_NAME = "builtin";
var init_builtinPlugins = __esm(() => {
init_settings2();
BUILTIN_PLUGINS = new Map;
});
// src/utils/plugins/addDirPluginSettings.ts
import { join as join29 } from "path";
function getAddDirEnabledPlugins() {
const result = {};
for (const dir of getAdditionalDirectoriesForClaudeMd()) {
for (const file2 of SETTINGS_FILES) {
const { settings } = parseSettingsFile(join29(dir, ".claude", file2));
if (!settings?.enabledPlugins) {
continue;
}
Object.assign(result, settings.enabledPlugins);
}
}
return result;
}
function getAddDirExtraMarketplaces() {
const result = {};
for (const dir of getAdditionalDirectoriesForClaudeMd()) {
for (const file2 of SETTINGS_FILES) {
const { settings } = parseSettingsFile(join29(dir, ".claude", file2));
if (!settings?.extraKnownMarketplaces) {
continue;
}
Object.assign(result, settings.extraKnownMarketplaces);
}
}
return result;
}
var SETTINGS_FILES;
var init_addDirPluginSettings = __esm(() => {
init_state();
init_settings2();
SETTINGS_FILES = ["settings.json", "settings.local.json"];
});
// src/utils/plugins/pluginIdentifier.ts
function parsePluginIdentifier(plugin) {
if (plugin.includes("@")) {
const parts = plugin.split("@");
return { name: parts[0] || "", marketplace: parts[1] };
}
return { name: plugin };
}
function isOfficialMarketplaceName(marketplace) {
return marketplace !== undefined && ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(marketplace.toLowerCase());
}
function scopeToSettingSource(scope) {
if (scope === "managed") {
throw new Error("Cannot install plugins to managed scope");
}
return SCOPE_TO_EDITABLE_SOURCE[scope];
}
function settingSourceToScope(source) {
return SETTING_SOURCE_TO_SCOPE[source];
}
var SETTING_SOURCE_TO_SCOPE, SCOPE_TO_EDITABLE_SOURCE;
var init_pluginIdentifier = __esm(() => {
init_schemas3();
SETTING_SOURCE_TO_SCOPE = {
policySettings: "managed",
userSettings: "user",
projectSettings: "project",
localSettings: "local",
flagSettings: "flag"
};
SCOPE_TO_EDITABLE_SOURCE = {
user: "userSettings",
project: "projectSettings",
local: "localSettings"
};
});
// src/utils/plugins/dependencyResolver.ts
function qualifyDependency(dep, declaringPluginId) {
if (parsePluginIdentifier(dep).marketplace)
return dep;
const mkt = parsePluginIdentifier(declaringPluginId).marketplace;
if (!mkt || mkt === INLINE_MARKETPLACE)
return dep;
return `${dep}@${mkt}`;
}
async function resolveDependencyClosure(rootId, lookup, alreadyEnabled, allowedCrossMarketplaces = new Set) {
const rootMarketplace = parsePluginIdentifier(rootId).marketplace;
const closure = [];
const visited = new Set;
const stack = [];
async function walk(id, requiredBy) {
if (id !== rootId && alreadyEnabled.has(id))
return null;
const idMarketplace = parsePluginIdentifier(id).marketplace;
if (idMarketplace !== rootMarketplace && !(idMarketplace && allowedCrossMarketplaces.has(idMarketplace))) {
return {
ok: false,
reason: "cross-marketplace",
dependency: id,
requiredBy
};
}
if (stack.includes(id)) {
return { ok: false, reason: "cycle", chain: [...stack, id] };
}
if (visited.has(id))
return null;
visited.add(id);
const entry = await lookup(id);
if (!entry) {
return { ok: false, reason: "not-found", missing: id, requiredBy };
}
stack.push(id);
for (const rawDep of entry.dependencies ?? []) {
const dep = qualifyDependency(rawDep, id);
const err2 = await walk(dep, id);
if (err2)
return err2;
}
stack.pop();
closure.push(id);
return null;
}
const err = await walk(rootId, rootId);
if (err)
return err;
return { ok: true, closure };
}
function verifyAndDemote(plugins) {
const known = new Set(plugins.map((p) => p.source));
const enabled = new Set(plugins.filter((p) => p.enabled).map((p) => p.source));
const knownByName = new Set(plugins.map((p) => parsePluginIdentifier(p.source).name));
const enabledByName = new Map;
for (const id of enabled) {
const n2 = parsePluginIdentifier(id).name;
enabledByName.set(n2, (enabledByName.get(n2) ?? 0) + 1);
}
const errors3 = [];
let changed = true;
while (changed) {
changed = false;
for (const p of plugins) {
if (!enabled.has(p.source))
continue;
for (const rawDep of p.manifest.dependencies ?? []) {
const dep = qualifyDependency(rawDep, p.source);
const isBare = !parsePluginIdentifier(dep).marketplace;
const satisfied = isBare ? (enabledByName.get(dep) ?? 0) > 0 : enabled.has(dep);
if (!satisfied) {
enabled.delete(p.source);
const count3 = enabledByName.get(p.name) ?? 0;
if (count3 <= 1)
enabledByName.delete(p.name);
else
enabledByName.set(p.name, count3 - 1);
errors3.push({
type: "dependency-unsatisfied",
source: p.source,
plugin: p.name,
dependency: dep,
reason: (isBare ? knownByName.has(dep) : known.has(dep)) ? "not-enabled" : "not-found"
});
changed = true;
break;
}
}
}
}
const demoted = new Set(plugins.filter((p) => p.enabled && !enabled.has(p.source)).map((p) => p.source));
return { demoted, errors: errors3 };
}
function findReverseDependents(pluginId, plugins) {
const { name: targetName } = parsePluginIdentifier(pluginId);
return plugins.filter((p) => p.enabled && p.source !== pluginId && (p.manifest.dependencies ?? []).some((d) => {
const qualified = qualifyDependency(d, p.source);
return parsePluginIdentifier(qualified).marketplace ? qualified === pluginId : qualified === targetName;
})).map((p) => p.name);
}
function getEnabledPluginIdsForScope(settingSource) {
return new Set(Object.entries(getSettingsForSource(settingSource)?.enabledPlugins ?? {}).filter(([, v]) => v === true || Array.isArray(v)).map(([k]) => k));
}
function formatDependencyCountSuffix(installedDeps) {
if (installedDeps.length === 0)
return "";
const n2 = installedDeps.length;
return ` (+ ${n2} ${n2 === 1 ? "dependency" : "dependencies"})`;
}
function formatReverseDependentsSuffix(rdeps) {
if (!rdeps || rdeps.length === 0)
return "";
return ` — warning: required by ${rdeps.join(", ")}`;
}
var INLINE_MARKETPLACE = "inline";
var init_dependencyResolver = __esm(() => {
init_settings2();
init_pluginIdentifier();
});
// src/utils/plugins/officialMarketplace.ts
var OFFICIAL_MARKETPLACE_SOURCE, OFFICIAL_MARKETPLACE_NAME = "claude-plugins-official";
var init_officialMarketplace = __esm(() => {
OFFICIAL_MARKETPLACE_SOURCE = {
source: "github",
repo: "anthropics/claude-plugins-official"
};
});
// src/utils/plugins/fetchTelemetry.ts
function extractHost(urlOrSpec) {
let host;
const scpMatch = /^[^@/]+@([^:/]+):/.exec(urlOrSpec);
if (scpMatch) {
host = scpMatch[1];
} else {
try {
host = new URL(urlOrSpec).hostname;
} catch {
return "unknown";
}
}
const normalized = host.toLowerCase();
return KNOWN_PUBLIC_HOSTS.has(normalized) ? normalized : "other";
}
function isOfficialRepo(urlOrSpec) {
return urlOrSpec.includes(`anthropics/${OFFICIAL_MARKETPLACE_NAME}`);
}
function logPluginFetch(source, urlOrSpec, outcome, durationMs, errorKind) {
logEvent("tengu_plugin_remote_fetch", {
source,
host: urlOrSpec ? extractHost(urlOrSpec) : "unknown",
is_official: urlOrSpec ? isOfficialRepo(urlOrSpec) : false,
outcome,
duration_ms: Math.round(durationMs),
...errorKind && { error_kind: errorKind }
});
}
function classifyFetchError(error44) {
const msg = String(error44?.message ?? error44);
if (/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|Could not resolve host|Connection refused/i.test(msg)) {
return "dns_or_refused";
}
if (/ETIMEDOUT|timed out|timeout/i.test(msg))
return "timeout";
if (/ECONNRESET|socket hang up|Connection reset by peer|remote end hung up/i.test(msg)) {
return "conn_reset";
}
if (/403|401|authentication|permission denied/i.test(msg))
return "auth";
if (/404|not found|repository not found/i.test(msg))
return "not_found";
if (/certificate|SSL|TLS|unable to get local issuer/i.test(msg))
return "tls";
if (/Invalid response format|Invalid marketplace schema/i.test(msg)) {
return "invalid_schema";
}
return "other";
}
var KNOWN_PUBLIC_HOSTS;
var init_fetchTelemetry = __esm(() => {
init_analytics();
init_officialMarketplace();
KNOWN_PUBLIC_HOSTS = new Set([
"github.com",
"raw.githubusercontent.com",
"objects.githubusercontent.com",
"gist.githubusercontent.com",
"gitlab.com",
"bitbucket.org",
"codeberg.org",
"dev.azure.com",
"ssh.dev.azure.com",
"storage.googleapis.com"
]);
});
// src/utils/plugins/gitAvailability.ts
async function isCommandAvailable2(command) {
try {
return !!await which(command);
} catch {
return false;
}
}
function markGitUnavailable() {
checkGitAvailable.cache?.set?.(undefined, Promise.resolve(false));
}
var checkGitAvailable;
var init_gitAvailability = __esm(() => {
init_memoize();
init_which();
checkGitAvailable = memoize_default(async () => {
return isCommandAvailable2("git");
});
});
// native-stub:@anthropic-ai/sandbox-runtime
var noop11 = () => null, handler4, stub4, SandboxViolationStore2 = null, SandboxManager4, SandboxRuntimeConfigSchema2;
var init_sandbox_runtime = __esm(() => {
handler4 = {
get(_, prop) {
if (prop === "__esModule")
return true;
if (prop === "default")
return new Proxy({}, handler4);
if (prop === "ExportResultCode")
return { SUCCESS: 0, FAILED: 1 };
if (prop === "resourceFromAttributes")
return () => ({});
if (prop === "SandboxRuntimeConfigSchema")
return { parse: () => ({}) };
return noop11;
}
};
stub4 = new Proxy(noop11, handler4);
SandboxManager4 = new Proxy({}, { get: () => noop11 });
SandboxRuntimeConfigSchema2 = { parse: () => ({}) };
});
// src/tools/WebFetchTool/prompt.ts
function makeSecondaryModelPrompt(markdownContent, prompt, isPreapprovedDomain) {
const guidelines = isPreapprovedDomain ? `Provide a concise response based on the content above. Include relevant details, code examples, and documentation excerpts as needed.` : `Provide a concise response based only on the content above. In your response:
- Enforce a strict 125-character maximum for quotes from any source document. Open Source Software is ok as long as we respect the license.
- Use quotation marks for exact language from articles; any language outside of the quotation should never be word-for-word the same.
- You are not a lawyer and never comment on the legality of your own prompts and responses.
- Never produce or reproduce exact song lyrics.`;
return `
Web page content:
---
${markdownContent}
---
${prompt}
${guidelines}
`;
}
var WEB_FETCH_TOOL_NAME = "WebFetch", DESCRIPTION4 = `
- Fetches content from a specified URL and processes it using an AI model
- Takes a URL and a prompt as input
- Fetches the URL content, converts HTML to markdown
- Processes the content with the prompt using a small, fast model
- Returns the model's response about the content
- Use this tool when you need to retrieve and analyze web content
Usage notes:
- IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions.
- The URL must be a fully-formed valid URL
- HTTP URLs will be automatically upgraded to HTTPS
- The prompt should describe what information you want to extract from the page
- This tool is read-only and does not modify any files
- Results may be summarized if the content is very large
- Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
- When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.
- For GitHub URLs, prefer using the gh CLI via Bash instead (e.g., gh pr view, gh issue view, gh api).
`;
// src/utils/sandbox/sandbox-adapter.ts
var exports_sandbox_adapter = {};
__export(exports_sandbox_adapter, {
shouldAllowManagedSandboxDomainsOnly: () => shouldAllowManagedSandboxDomainsOnly,
resolveSandboxFilesystemPath: () => resolveSandboxFilesystemPath,
resolvePathPatternForSandbox: () => resolvePathPatternForSandbox,
convertToSandboxRuntimeConfig: () => convertToSandboxRuntimeConfig,
addToExcludedCommands: () => addToExcludedCommands,
SandboxViolationStore: () => SandboxViolationStore2,
SandboxRuntimeConfigSchema: () => SandboxRuntimeConfigSchema2,
SandboxManager: () => SandboxManager5
});
import { rmSync as rmSync2, statSync as statSync5 } from "fs";
import { readFile as readFile9 } from "fs/promises";
import { join as join30, resolve as resolve14, sep as sep7 } from "path";
function permissionRuleValueFromString2(ruleString) {
const matches = ruleString.match(/^([^(]+)\(([^)]+)\)$/);
if (!matches) {
return { toolName: ruleString };
}
const toolName = matches[1];
const ruleContent = matches[2];
if (!toolName || !ruleContent) {
return { toolName: ruleString };
}
return { toolName, ruleContent };
}
function permissionRuleExtractPrefix(permissionRule) {
const match = permissionRule.match(/^(.+):\*$/);
return match?.[1] ?? null;
}
function resolvePathPatternForSandbox(pattern, source) {
if (pattern.startsWith("//")) {
return pattern.slice(1);
}
if (pattern.startsWith("/") && !pattern.startsWith("//")) {
const root2 = getSettingsRootPathForSource(source);
return resolve14(root2, pattern.slice(1));
}
return pattern;
}
function resolveSandboxFilesystemPath(pattern, source) {
if (pattern.startsWith("//"))
return pattern.slice(1);
return expandPath(pattern, getSettingsRootPathForSource(source));
}
function shouldAllowManagedSandboxDomainsOnly() {
return getSettingsForSource("policySettings")?.sandbox?.network?.allowManagedDomainsOnly === true;
}
function shouldAllowManagedReadPathsOnly() {
return getSettingsForSource("policySettings")?.sandbox?.filesystem?.allowManagedReadPathsOnly === true;
}
function convertToSandboxRuntimeConfig(settings) {
const permissions = settings.permissions || {};
const allowedDomains = [];
const deniedDomains = [];
if (shouldAllowManagedSandboxDomainsOnly()) {
const policySettings = getSettingsForSource("policySettings");
for (const domain2 of policySettings?.sandbox?.network?.allowedDomains || []) {
allowedDomains.push(domain2);
}
for (const ruleString of policySettings?.permissions?.allow || []) {
const rule = permissionRuleValueFromString2(ruleString);
if (rule.toolName === WEB_FETCH_TOOL_NAME && rule.ruleContent?.startsWith("domain:")) {
allowedDomains.push(rule.ruleContent.substring("domain:".length));
}
}
} else {
for (const domain2 of settings.sandbox?.network?.allowedDomains || []) {
allowedDomains.push(domain2);
}
for (const ruleString of permissions.allow || []) {
const rule = permissionRuleValueFromString2(ruleString);
if (rule.toolName === WEB_FETCH_TOOL_NAME && rule.ruleContent?.startsWith("domain:")) {
allowedDomains.push(rule.ruleContent.substring("domain:".length));
}
}
}
for (const ruleString of permissions.deny || []) {
const rule = permissionRuleValueFromString2(ruleString);
if (rule.toolName === WEB_FETCH_TOOL_NAME && rule.ruleContent?.startsWith("domain:")) {
deniedDomains.push(rule.ruleContent.substring("domain:".length));
}
}
const allowWrite = [".", getClaudeTempDir()];
const denyWrite = [];
const denyRead = [];
const allowRead = [];
const settingsPaths = SETTING_SOURCES.map((source) => getSettingsFilePathForSource(source)).filter((p) => p !== undefined);
denyWrite.push(...settingsPaths);
denyWrite.push(getManagedSettingsDropInDir());
const cwd2 = getCwdState();
const originalCwd = getOriginalCwd();
if (cwd2 !== originalCwd) {
denyWrite.push(resolve14(cwd2, ".claude", "settings.json"));
denyWrite.push(resolve14(cwd2, ".claude", "settings.local.json"));
}
denyWrite.push(resolve14(originalCwd, ".claude", "skills"));
if (cwd2 !== originalCwd) {
denyWrite.push(resolve14(cwd2, ".claude", "skills"));
}
bareGitRepoScrubPaths.length = 0;
const bareGitRepoFiles = ["HEAD", "objects", "refs", "hooks", "config"];
for (const dir of cwd2 === originalCwd ? [originalCwd] : [originalCwd, cwd2]) {
for (const gitFile of bareGitRepoFiles) {
const p = resolve14(dir, gitFile);
try {
statSync5(p);
denyWrite.push(p);
} catch {
bareGitRepoScrubPaths.push(p);
}
}
}
if (worktreeMainRepoPath && worktreeMainRepoPath !== cwd2) {
allowWrite.push(worktreeMainRepoPath);
}
const additionalDirs = new Set([
...settings.permissions?.additionalDirectories || [],
...getAdditionalDirectoriesForClaudeMd()
]);
allowWrite.push(...additionalDirs);
for (const source of SETTING_SOURCES) {
const sourceSettings = getSettingsForSource(source);
if (sourceSettings?.permissions) {
for (const ruleString of sourceSettings.permissions.allow || []) {
const rule = permissionRuleValueFromString2(ruleString);
if (rule.toolName === FILE_EDIT_TOOL_NAME && rule.ruleContent) {
allowWrite.push(resolvePathPatternForSandbox(rule.ruleContent, source));
}
}
for (const ruleString of sourceSettings.permissions.deny || []) {
const rule = permissionRuleValueFromString2(ruleString);
if (rule.toolName === FILE_EDIT_TOOL_NAME && rule.ruleContent) {
denyWrite.push(resolvePathPatternForSandbox(rule.ruleContent, source));
}
if (rule.toolName === FILE_READ_TOOL_NAME && rule.ruleContent) {
denyRead.push(resolvePathPatternForSandbox(rule.ruleContent, source));
}
}
}
const fs2 = sourceSettings?.sandbox?.filesystem;
if (fs2) {
for (const p of fs2.allowWrite || []) {
allowWrite.push(resolveSandboxFilesystemPath(p, source));
}
for (const p of fs2.denyWrite || []) {
denyWrite.push(resolveSandboxFilesystemPath(p, source));
}
for (const p of fs2.denyRead || []) {
denyRead.push(resolveSandboxFilesystemPath(p, source));
}
if (!shouldAllowManagedReadPathsOnly() || source === "policySettings") {
for (const p of fs2.allowRead || []) {
allowRead.push(resolveSandboxFilesystemPath(p, source));
}
}
}
}
const { rgPath, rgArgs, argv0 } = ripgrepCommand();
const ripgrepConfig = settings.sandbox?.ripgrep ?? {
command: rgPath,
args: rgArgs,
argv0
};
return {
network: {
allowedDomains,
deniedDomains,
allowUnixSockets: settings.sandbox?.network?.allowUnixSockets,
allowAllUnixSockets: settings.sandbox?.network?.allowAllUnixSockets,
allowLocalBinding: settings.sandbox?.network?.allowLocalBinding,
httpProxyPort: settings.sandbox?.network?.httpProxyPort,
socksProxyPort: settings.sandbox?.network?.socksProxyPort
},
filesystem: {
denyRead,
allowRead,
allowWrite,
denyWrite
},
ignoreViolations: settings.sandbox?.ignoreViolations,
enableWeakerNestedSandbox: settings.sandbox?.enableWeakerNestedSandbox,
enableWeakerNetworkIsolation: settings.sandbox?.enableWeakerNetworkIsolation,
ripgrep: ripgrepConfig
};
}
function scrubBareGitRepoFiles() {
for (const p of bareGitRepoScrubPaths) {
try {
rmSync2(p, { recursive: true });
logForDebugging(`[Sandbox] scrubbed planted bare-repo file: ${p}`);
} catch {}
}
}
async function detectWorktreeMainRepoPath(cwd2) {
const gitPath = join30(cwd2, ".git");
try {
const gitContent = await readFile9(gitPath, { encoding: "utf8" });
const gitdirMatch = gitContent.match(/^gitdir:\s*(.+)$/m);
if (!gitdirMatch?.[1]) {
return null;
}
const gitdir = resolve14(cwd2, gitdirMatch[1].trim());
const marker = `${sep7}.git${sep7}worktrees${sep7}`;
const markerIndex = gitdir.lastIndexOf(marker);
if (markerIndex > 0) {
return gitdir.substring(0, markerIndex);
}
return null;
} catch {
return null;
}
}
function getSandboxEnabledSetting() {
try {
const settings = getSettings_DEPRECATED();
return settings?.sandbox?.enabled ?? false;
} catch (error44) {
logForDebugging(`Failed to get settings for sandbox check: ${error44}`);
return false;
}
}
function isAutoAllowBashIfSandboxedEnabled() {
const settings = getSettings_DEPRECATED();
return settings?.sandbox?.autoAllowBashIfSandboxed ?? true;
}
function areUnsandboxedCommandsAllowed() {
const settings = getSettings_DEPRECATED();
return settings?.sandbox?.allowUnsandboxedCommands ?? true;
}
function isSandboxRequired() {
const settings = getSettings_DEPRECATED();
return getSandboxEnabledSetting() && (settings?.sandbox?.failIfUnavailable ?? false);
}
function isPlatformInEnabledList() {
try {
const settings = getInitialSettings();
const enabledPlatforms = settings?.sandbox?.enabledPlatforms;
if (enabledPlatforms === undefined) {
return true;
}
if (enabledPlatforms.length === 0) {
return false;
}
const currentPlatform = getPlatform();
return enabledPlatforms.includes(currentPlatform);
} catch (error44) {
logForDebugging(`Failed to check enabledPlatforms: ${error44}`);
return true;
}
}
function isSandboxingEnabled() {
if (!isSupportedPlatform()) {
return false;
}
if (checkDependencies().errors.length > 0) {
return false;
}
if (!isPlatformInEnabledList()) {
return false;
}
return getSandboxEnabledSetting();
}
function getSandboxUnavailableReason() {
if (!getSandboxEnabledSetting()) {
return;
}
if (!isSupportedPlatform()) {
const platform2 = getPlatform();
if (platform2 === "wsl") {
return "sandbox.enabled is set but WSL1 is not supported (requires WSL2)";
}
return `sandbox.enabled is set but ${platform2} is not supported (requires macOS, Linux, or WSL2)`;
}
if (!isPlatformInEnabledList()) {
return `sandbox.enabled is set but ${getPlatform()} is not in sandbox.enabledPlatforms`;
}
const deps = checkDependencies();
if (deps.errors.length > 0) {
const platform2 = getPlatform();
const hint = platform2 === "macos" ? "run /sandbox or /doctor for details" : "install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details";
return `sandbox.enabled is set but dependencies are missing: ${deps.errors.join(", ")} · ${hint}`;
}
return;
}
function getLinuxGlobPatternWarnings() {
const platform2 = getPlatform();
if (platform2 !== "linux" && platform2 !== "wsl") {
return [];
}
try {
const settings = getSettings_DEPRECATED();
if (!settings?.sandbox?.enabled) {
return [];
}
const permissions = settings?.permissions || {};
const warnings = [];
const hasGlobs = (path11) => {
const stripped = path11.replace(/\/\*\*$/, "");
return /[*?[\]]/.test(stripped);
};
for (const ruleString of [
...permissions.allow || [],
...permissions.deny || []
]) {
const rule = permissionRuleValueFromString2(ruleString);
if ((rule.toolName === FILE_EDIT_TOOL_NAME || rule.toolName === FILE_READ_TOOL_NAME) && rule.ruleContent && hasGlobs(rule.ruleContent)) {
warnings.push(ruleString);
}
}
return warnings;
} catch (error44) {
logForDebugging(`Failed to get Linux glob pattern warnings: ${error44}`);
return [];
}
}
function areSandboxSettingsLockedByPolicy() {
const overridingSources = ["flagSettings", "policySettings"];
for (const source of overridingSources) {
const settings = getSettingsForSource(source);
if (settings?.sandbox?.enabled !== undefined || settings?.sandbox?.autoAllowBashIfSandboxed !== undefined || settings?.sandbox?.allowUnsandboxedCommands !== undefined) {
return true;
}
}
return false;
}
async function setSandboxSettings(options) {
const existingSettings = getSettingsForSource("localSettings");
updateSettingsForSource("localSettings", {
sandbox: {
...existingSettings?.sandbox,
...options.enabled !== undefined && { enabled: options.enabled },
...options.autoAllowBashIfSandboxed !== undefined && {
autoAllowBashIfSandboxed: options.autoAllowBashIfSandboxed
},
...options.allowUnsandboxedCommands !== undefined && {
allowUnsandboxedCommands: options.allowUnsandboxedCommands
}
}
});
}
function getExcludedCommands() {
const settings = getSettings_DEPRECATED();
return settings?.sandbox?.excludedCommands ?? [];
}
async function wrapWithSandbox(command, binShell, customConfig, abortSignal) {
if (isSandboxingEnabled()) {
if (initializationPromise) {
await initializationPromise;
} else {
throw new Error("Sandbox failed to initialize. ");
}
}
return SandboxManager4.wrapWithSandbox(command, binShell, customConfig, abortSignal);
}
async function initialize2(sandboxAskCallback) {
if (initializationPromise) {
return initializationPromise;
}
if (!isSandboxingEnabled()) {
return;
}
const wrappedCallback = sandboxAskCallback ? async (hostPattern) => {
if (shouldAllowManagedSandboxDomainsOnly()) {
logForDebugging(`[sandbox] Blocked network request to ${hostPattern.host} (allowManagedDomainsOnly)`);
return false;
}
return sandboxAskCallback(hostPattern);
} : undefined;
initializationPromise = (async () => {
try {
if (worktreeMainRepoPath === undefined) {
worktreeMainRepoPath = await detectWorktreeMainRepoPath(getCwdState());
}
const settings = getSettings_DEPRECATED();
const runtimeConfig = convertToSandboxRuntimeConfig(settings);
await SandboxManager4.initialize(runtimeConfig, wrappedCallback);
settingsSubscriptionCleanup = settingsChangeDetector.subscribe(() => {
const settings2 = getSettings_DEPRECATED();
const newConfig = convertToSandboxRuntimeConfig(settings2);
SandboxManager4.updateConfig(newConfig);
logForDebugging("Sandbox configuration updated from settings change");
});
} catch (error44) {
initializationPromise = undefined;
logForDebugging(`Failed to initialize sandbox: ${errorMessage(error44)}`);
}
})();
return initializationPromise;
}
function refreshConfig() {
if (!isSandboxingEnabled())
return;
const settings = getSettings_DEPRECATED();
const newConfig = convertToSandboxRuntimeConfig(settings);
SandboxManager4.updateConfig(newConfig);
}
async function reset2() {
settingsSubscriptionCleanup?.();
settingsSubscriptionCleanup = undefined;
worktreeMainRepoPath = undefined;
bareGitRepoScrubPaths.length = 0;
checkDependencies.cache.clear?.();
isSupportedPlatform.cache.clear?.();
initializationPromise = undefined;
return SandboxManager4.reset();
}
function addToExcludedCommands(command, permissionUpdates) {
const existingSettings = getSettingsForSource("localSettings");
const existingExcludedCommands = existingSettings?.sandbox?.excludedCommands || [];
let commandPattern = command;
if (permissionUpdates) {
const bashSuggestions = permissionUpdates.filter((update) => update.type === "addRules" && update.rules.some((rule) => rule.toolName === BASH_TOOL_NAME));
if (bashSuggestions.length > 0 && bashSuggestions[0].type === "addRules") {
const firstBashRule = bashSuggestions[0].rules.find((rule) => rule.toolName === BASH_TOOL_NAME);
if (firstBashRule?.ruleContent) {
const prefix = permissionRuleExtractPrefix(firstBashRule.ruleContent);
commandPattern = prefix || firstBashRule.ruleContent;
}
}
}
if (!existingExcludedCommands.includes(commandPattern)) {
updateSettingsForSource("localSettings", {
sandbox: {
...existingSettings?.sandbox,
excludedCommands: [...existingExcludedCommands, commandPattern]
}
});
}
return commandPattern;
}
var initializationPromise, settingsSubscriptionCleanup, worktreeMainRepoPath, bareGitRepoScrubPaths, checkDependencies, isSupportedPlatform, SandboxManager5;
var init_sandbox_adapter = __esm(() => {
init_sandbox_runtime();
init_lodash();
init_state();
init_debug();
init_path2();
init_platform2();
init_changeDetector();
init_constants2();
init_managedPath();
init_settings2();
init_prompt2();
init_errors();
init_filesystem();
init_ripgrep();
bareGitRepoScrubPaths = [];
checkDependencies = memoize_default(() => {
const { rgPath, rgArgs } = ripgrepCommand();
return SandboxManager4.checkDependencies({
command: rgPath,
args: rgArgs
});
});
isSupportedPlatform = memoize_default(() => {
return SandboxManager4.isSupportedPlatform();
});
SandboxManager5 = {
initialize: initialize2,
isSandboxingEnabled,
isSandboxEnabledInSettings: getSandboxEnabledSetting,
isPlatformInEnabledList,
getSandboxUnavailableReason,
isAutoAllowBashIfSandboxedEnabled,
areUnsandboxedCommandsAllowed,
isSandboxRequired,
areSandboxSettingsLockedByPolicy,
setSandboxSettings,
getExcludedCommands,
wrapWithSandbox,
refreshConfig,
reset: reset2,
checkDependencies,
getFsReadConfig: SandboxManager4.getFsReadConfig,
getFsWriteConfig: SandboxManager4.getFsWriteConfig,
getNetworkRestrictionConfig: SandboxManager4.getNetworkRestrictionConfig,
getIgnoreViolations: SandboxManager4.getIgnoreViolations,
getLinuxGlobPatternWarnings,
isSupportedPlatform,
getAllowUnixSockets: SandboxManager4.getAllowUnixSockets,
getAllowLocalBinding: SandboxManager4.getAllowLocalBinding,
getEnableWeakerNestedSandbox: SandboxManager4.getEnableWeakerNestedSandbox,
getProxyPort: SandboxManager4.getProxyPort,
getSocksProxyPort: SandboxManager4.getSocksProxyPort,
getLinuxHttpSocketPath: SandboxManager4.getLinuxHttpSocketPath,
getLinuxSocksSocketPath: SandboxManager4.getLinuxSocksSocketPath,
waitForNetworkInitialization: SandboxManager4.waitForNetworkInitialization,
getSandboxViolationStore: SandboxManager4.getSandboxViolationStore,
annotateStderrWithSandboxFailures: SandboxManager4.annotateStderrWithSandboxFailures,
cleanupAfterCommand: () => {
SandboxManager4.cleanupAfterCommand();
scrubBareGitRepoFiles();
}
};
});
// src/utils/shell/readOnlyCommandValidation.ts
function ghIsDangerousCallback(_rawCommand, args) {
for (const token of args) {
if (!token)
continue;
let value = token;
if (token.startsWith("-")) {
const eqIdx = token.indexOf("=");
if (eqIdx === -1)
continue;
value = token.slice(eqIdx + 1);
if (!value)
continue;
}
if (!value.includes("/") && !value.includes("://") && !value.includes("@")) {
continue;
}
if (value.includes("://")) {
return true;
}
if (value.includes("@")) {
return true;
}
const slashCount = (value.match(/\//g) || []).length;
if (slashCount >= 2) {
return true;
}
}
return false;
}
function containsVulnerableUncPath(pathOrCommand) {
if (getPlatform() !== "windows") {
return false;
}
const backslashUncPattern = /\\\\[^\s\\/]+(?:@(?:\d+|ssl))?(?:[\\/]|$|\s)/i;
if (backslashUncPattern.test(pathOrCommand)) {
return true;
}
const forwardSlashUncPattern = /(? 1 && FLAG_PATTERN.test(token)) {
const hasEquals = token.includes("=");
const [flag, ...valueParts] = token.split("=");
const inlineValue = valueParts.join("=");
if (!flag) {
return false;
}
const flagArgType = config2.safeFlags[flag];
if (!flagArgType) {
if (options?.commandName === "git" && flag.match(/^-\d+$/)) {
i2++;
continue;
}
if ((options?.commandName === "grep" || options?.commandName === "rg") && flag.startsWith("-") && !flag.startsWith("--") && flag.length > 2) {
const potentialFlag = flag.substring(0, 2);
const potentialValue = flag.substring(2);
if (config2.safeFlags[potentialFlag] && /^\d+$/.test(potentialValue)) {
const flagArgType2 = config2.safeFlags[potentialFlag];
if (flagArgType2 === "number" || flagArgType2 === "string") {
if (validateFlagArgument(potentialValue, flagArgType2)) {
i2++;
continue;
} else {
return false;
}
}
}
}
if (flag.startsWith("-") && !flag.startsWith("--") && flag.length > 2) {
for (let j = 1;j < flag.length; j++) {
const singleFlag = "-" + flag[j];
const flagType = config2.safeFlags[singleFlag];
if (!flagType) {
return false;
}
if (flagType !== "none") {
return false;
}
}
i2++;
continue;
} else {
return false;
}
}
if (flagArgType === "none") {
if (hasEquals) {
return false;
}
i2++;
} else {
let argValue;
if (hasEquals) {
argValue = inlineValue;
i2++;
} else {
if (i2 + 1 >= tokens.length || tokens[i2 + 1] && tokens[i2 + 1].startsWith("-") && tokens[i2 + 1].length > 1 && FLAG_PATTERN.test(tokens[i2 + 1])) {
return false;
}
argValue = tokens[i2 + 1] || "";
i2 += 2;
}
if (flagArgType === "string" && argValue.startsWith("-")) {
if (flag === "--sort" && options?.commandName === "git" && argValue.match(/^-[a-zA-Z]/)) {} else {
return false;
}
}
if (!validateFlagArgument(argValue, flagArgType)) {
return false;
}
}
} else {
i2++;
}
}
return true;
}
var GIT_REF_SELECTION_FLAGS, GIT_DATE_FILTER_FLAGS, GIT_LOG_DISPLAY_FLAGS, GIT_COUNT_FLAGS, GIT_STAT_FLAGS, GIT_COLOR_FLAGS, GIT_PATCH_FLAGS, GIT_AUTHOR_FILTER_FLAGS, GIT_READ_ONLY_COMMANDS, GH_READ_ONLY_COMMANDS, DOCKER_READ_ONLY_COMMANDS, RIPGREP_READ_ONLY_COMMANDS, PYRIGHT_READ_ONLY_COMMANDS, EXTERNAL_READONLY_COMMANDS, FLAG_PATTERN;
var init_readOnlyCommandValidation = __esm(() => {
init_platform2();
GIT_REF_SELECTION_FLAGS = {
"--all": "none",
"--branches": "none",
"--tags": "none",
"--remotes": "none"
};
GIT_DATE_FILTER_FLAGS = {
"--since": "string",
"--after": "string",
"--until": "string",
"--before": "string"
};
GIT_LOG_DISPLAY_FLAGS = {
"--oneline": "none",
"--graph": "none",
"--decorate": "none",
"--no-decorate": "none",
"--date": "string",
"--relative-date": "none"
};
GIT_COUNT_FLAGS = {
"--max-count": "number",
"-n": "number"
};
GIT_STAT_FLAGS = {
"--stat": "none",
"--numstat": "none",
"--shortstat": "none",
"--name-only": "none",
"--name-status": "none"
};
GIT_COLOR_FLAGS = {
"--color": "none",
"--no-color": "none"
};
GIT_PATCH_FLAGS = {
"--patch": "none",
"-p": "none",
"--no-patch": "none",
"--no-ext-diff": "none",
"-s": "none"
};
GIT_AUTHOR_FILTER_FLAGS = {
"--author": "string",
"--committer": "string",
"--grep": "string"
};
GIT_READ_ONLY_COMMANDS = {
"git diff": {
safeFlags: {
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
"--dirstat": "none",
"--summary": "none",
"--patch-with-stat": "none",
"--word-diff": "none",
"--word-diff-regex": "string",
"--color-words": "none",
"--no-renames": "none",
"--no-ext-diff": "none",
"--check": "none",
"--ws-error-highlight": "string",
"--full-index": "none",
"--binary": "none",
"--abbrev": "number",
"--break-rewrites": "none",
"--find-renames": "none",
"--find-copies": "none",
"--find-copies-harder": "none",
"--irreversible-delete": "none",
"--diff-algorithm": "string",
"--histogram": "none",
"--patience": "none",
"--minimal": "none",
"--ignore-space-at-eol": "none",
"--ignore-space-change": "none",
"--ignore-all-space": "none",
"--ignore-blank-lines": "none",
"--inter-hunk-context": "number",
"--function-context": "none",
"--exit-code": "none",
"--quiet": "none",
"--cached": "none",
"--staged": "none",
"--pickaxe-regex": "none",
"--pickaxe-all": "none",
"--no-index": "none",
"--relative": "string",
"--diff-filter": "string",
"-p": "none",
"-u": "none",
"-s": "none",
"-M": "none",
"-C": "none",
"-B": "none",
"-D": "none",
"-l": "none",
"-S": "string",
"-G": "string",
"-O": "string",
"-R": "none"
}
},
"git log": {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
...GIT_COUNT_FLAGS,
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
...GIT_PATCH_FLAGS,
...GIT_AUTHOR_FILTER_FLAGS,
"--abbrev-commit": "none",
"--full-history": "none",
"--dense": "none",
"--sparse": "none",
"--simplify-merges": "none",
"--ancestry-path": "none",
"--source": "none",
"--first-parent": "none",
"--merges": "none",
"--no-merges": "none",
"--reverse": "none",
"--walk-reflogs": "none",
"--skip": "number",
"--max-age": "number",
"--min-age": "number",
"--no-min-parents": "none",
"--no-max-parents": "none",
"--follow": "none",
"--no-walk": "none",
"--left-right": "none",
"--cherry-mark": "none",
"--cherry-pick": "none",
"--boundary": "none",
"--topo-order": "none",
"--date-order": "none",
"--author-date-order": "none",
"--pretty": "string",
"--format": "string",
"--diff-filter": "string",
"-S": "string",
"-G": "string",
"--pickaxe-regex": "none",
"--pickaxe-all": "none"
}
},
"git show": {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
...GIT_PATCH_FLAGS,
"--abbrev-commit": "none",
"--word-diff": "none",
"--word-diff-regex": "string",
"--color-words": "none",
"--pretty": "string",
"--format": "string",
"--first-parent": "none",
"--raw": "none",
"--diff-filter": "string",
"-m": "none",
"--quiet": "none"
}
},
"git shortlog": {
safeFlags: {
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
"-s": "none",
"--summary": "none",
"-n": "none",
"--numbered": "none",
"-e": "none",
"--email": "none",
"-c": "none",
"--committer": "none",
"--group": "string",
"--format": "string",
"--no-merges": "none",
"--author": "string"
}
},
"git reflog": {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
...GIT_COUNT_FLAGS,
...GIT_AUTHOR_FILTER_FLAGS
},
additionalCommandIsDangerousCallback: (_rawCommand, args) => {
const DANGEROUS_SUBCOMMANDS = new Set(["expire", "delete", "exists"]);
for (const token of args) {
if (!token || token.startsWith("-"))
continue;
if (DANGEROUS_SUBCOMMANDS.has(token)) {
return true;
}
return false;
}
return false;
}
},
"git stash list": {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_REF_SELECTION_FLAGS,
...GIT_COUNT_FLAGS
}
},
"git ls-remote": {
safeFlags: {
"--branches": "none",
"-b": "none",
"--tags": "none",
"-t": "none",
"--heads": "none",
"-h": "none",
"--refs": "none",
"--quiet": "none",
"-q": "none",
"--exit-code": "none",
"--get-url": "none",
"--symref": "none",
"--sort": "string"
}
},
"git status": {
safeFlags: {
"--short": "none",
"-s": "none",
"--branch": "none",
"-b": "none",
"--porcelain": "none",
"--long": "none",
"--verbose": "none",
"-v": "none",
"--untracked-files": "string",
"-u": "string",
"--ignored": "none",
"--ignore-submodules": "string",
"--column": "none",
"--no-column": "none",
"--ahead-behind": "none",
"--no-ahead-behind": "none",
"--renames": "none",
"--no-renames": "none",
"--find-renames": "string",
"-M": "string"
}
},
"git blame": {
safeFlags: {
...GIT_COLOR_FLAGS,
"-L": "string",
"--porcelain": "none",
"-p": "none",
"--line-porcelain": "none",
"--incremental": "none",
"--root": "none",
"--show-stats": "none",
"--show-name": "none",
"--show-number": "none",
"-n": "none",
"--show-email": "none",
"-e": "none",
"-f": "none",
"--date": "string",
"-w": "none",
"--ignore-rev": "string",
"--ignore-revs-file": "string",
"-M": "none",
"-C": "none",
"--score-debug": "none",
"--abbrev": "number",
"-s": "none",
"-l": "none",
"-t": "none"
}
},
"git ls-files": {
safeFlags: {
"--cached": "none",
"-c": "none",
"--deleted": "none",
"-d": "none",
"--modified": "none",
"-m": "none",
"--others": "none",
"-o": "none",
"--ignored": "none",
"-i": "none",
"--stage": "none",
"-s": "none",
"--killed": "none",
"-k": "none",
"--unmerged": "none",
"-u": "none",
"--directory": "none",
"--no-empty-directory": "none",
"--eol": "none",
"--full-name": "none",
"--abbrev": "number",
"--debug": "none",
"-z": "none",
"-t": "none",
"-v": "none",
"-f": "none",
"--exclude": "string",
"-x": "string",
"--exclude-from": "string",
"-X": "string",
"--exclude-per-directory": "string",
"--exclude-standard": "none",
"--error-unmatch": "none",
"--recurse-submodules": "none"
}
},
"git config --get": {
safeFlags: {
"--local": "none",
"--global": "none",
"--system": "none",
"--worktree": "none",
"--default": "string",
"--type": "string",
"--bool": "none",
"--int": "none",
"--bool-or-int": "none",
"--path": "none",
"--expiry-date": "none",
"-z": "none",
"--null": "none",
"--name-only": "none",
"--show-origin": "none",
"--show-scope": "none"
}
},
"git remote show": {
safeFlags: {
"-n": "none"
},
additionalCommandIsDangerousCallback: (_rawCommand, args) => {
const positional = args.filter((a2) => a2 !== "-n");
if (positional.length !== 1)
return true;
return !/^[a-zA-Z0-9_-]+$/.test(positional[0]);
}
},
"git remote": {
safeFlags: {
"-v": "none",
"--verbose": "none"
},
additionalCommandIsDangerousCallback: (_rawCommand, args) => {
return args.some((a2) => a2 !== "-v" && a2 !== "--verbose");
}
},
"git merge-base": {
safeFlags: {
"--is-ancestor": "none",
"--fork-point": "none",
"--octopus": "none",
"--independent": "none",
"--all": "none"
}
},
"git rev-parse": {
safeFlags: {
"--verify": "none",
"--short": "string",
"--abbrev-ref": "none",
"--symbolic": "none",
"--symbolic-full-name": "none",
"--show-toplevel": "none",
"--show-cdup": "none",
"--show-prefix": "none",
"--git-dir": "none",
"--git-common-dir": "none",
"--absolute-git-dir": "none",
"--show-superproject-working-tree": "none",
"--is-inside-work-tree": "none",
"--is-inside-git-dir": "none",
"--is-bare-repository": "none",
"--is-shallow-repository": "none",
"--is-shallow-update": "none",
"--path-prefix": "none"
}
},
"git rev-list": {
safeFlags: {
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
...GIT_COUNT_FLAGS,
...GIT_AUTHOR_FILTER_FLAGS,
"--count": "none",
"--reverse": "none",
"--first-parent": "none",
"--ancestry-path": "none",
"--merges": "none",
"--no-merges": "none",
"--min-parents": "number",
"--max-parents": "number",
"--no-min-parents": "none",
"--no-max-parents": "none",
"--skip": "number",
"--max-age": "number",
"--min-age": "number",
"--walk-reflogs": "none",
"--oneline": "none",
"--abbrev-commit": "none",
"--pretty": "string",
"--format": "string",
"--abbrev": "number",
"--full-history": "none",
"--dense": "none",
"--sparse": "none",
"--source": "none",
"--graph": "none"
}
},
"git describe": {
safeFlags: {
"--tags": "none",
"--match": "string",
"--exclude": "string",
"--long": "none",
"--abbrev": "number",
"--always": "none",
"--contains": "none",
"--first-match": "none",
"--exact-match": "none",
"--candidates": "number",
"--dirty": "none",
"--broken": "none"
}
},
"git cat-file": {
safeFlags: {
"-t": "none",
"-s": "none",
"-p": "none",
"-e": "none",
"--batch-check": "none",
"--allow-undetermined-type": "none"
}
},
"git for-each-ref": {
safeFlags: {
"--format": "string",
"--sort": "string",
"--count": "number",
"--contains": "string",
"--no-contains": "string",
"--merged": "string",
"--no-merged": "string",
"--points-at": "string"
}
},
"git grep": {
safeFlags: {
"-e": "string",
"-E": "none",
"--extended-regexp": "none",
"-G": "none",
"--basic-regexp": "none",
"-F": "none",
"--fixed-strings": "none",
"-P": "none",
"--perl-regexp": "none",
"-i": "none",
"--ignore-case": "none",
"-v": "none",
"--invert-match": "none",
"-w": "none",
"--word-regexp": "none",
"-n": "none",
"--line-number": "none",
"-c": "none",
"--count": "none",
"-l": "none",
"--files-with-matches": "none",
"-L": "none",
"--files-without-match": "none",
"-h": "none",
"-H": "none",
"--heading": "none",
"--break": "none",
"--full-name": "none",
"--color": "none",
"--no-color": "none",
"-o": "none",
"--only-matching": "none",
"-A": "number",
"--after-context": "number",
"-B": "number",
"--before-context": "number",
"-C": "number",
"--context": "number",
"--and": "none",
"--or": "none",
"--not": "none",
"--max-depth": "number",
"--untracked": "none",
"--no-index": "none",
"--recurse-submodules": "none",
"--cached": "none",
"--threads": "number",
"-q": "none",
"--quiet": "none"
}
},
"git stash show": {
safeFlags: {
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
...GIT_PATCH_FLAGS,
"--word-diff": "none",
"--word-diff-regex": "string",
"--diff-filter": "string",
"--abbrev": "number"
}
},
"git worktree list": {
safeFlags: {
"--porcelain": "none",
"-v": "none",
"--verbose": "none",
"--expire": "string"
}
},
"git tag": {
safeFlags: {
"-l": "none",
"--list": "none",
"-n": "number",
"--contains": "string",
"--no-contains": "string",
"--merged": "string",
"--no-merged": "string",
"--sort": "string",
"--format": "string",
"--points-at": "string",
"--column": "none",
"--no-column": "none",
"-i": "none",
"--ignore-case": "none"
},
additionalCommandIsDangerousCallback: (_rawCommand, args) => {
const flagsWithArgs = new Set([
"--contains",
"--no-contains",
"--merged",
"--no-merged",
"--points-at",
"--sort",
"--format",
"-n"
]);
let i2 = 0;
let seenListFlag = false;
let seenDashDash = false;
while (i2 < args.length) {
const token = args[i2];
if (!token) {
i2++;
continue;
}
if (token === "--" && !seenDashDash) {
seenDashDash = true;
i2++;
continue;
}
if (!seenDashDash && token.startsWith("-")) {
if (token === "--list" || token === "-l") {
seenListFlag = true;
} else if (token[0] === "-" && token[1] !== "-" && token.length > 2 && !token.includes("=") && token.slice(1).includes("l")) {
seenListFlag = true;
}
if (token.includes("=")) {
i2++;
} else if (flagsWithArgs.has(token)) {
i2 += 2;
} else {
i2++;
}
} else {
if (!seenListFlag) {
return true;
}
i2++;
}
}
return false;
}
},
"git branch": {
safeFlags: {
"-l": "none",
"--list": "none",
"-a": "none",
"--all": "none",
"-r": "none",
"--remotes": "none",
"-v": "none",
"-vv": "none",
"--verbose": "none",
"--color": "none",
"--no-color": "none",
"--column": "none",
"--no-column": "none",
"--abbrev": "number",
"--no-abbrev": "none",
"--contains": "string",
"--no-contains": "string",
"--merged": "none",
"--no-merged": "none",
"--points-at": "string",
"--sort": "string",
"--show-current": "none",
"-i": "none",
"--ignore-case": "none"
},
additionalCommandIsDangerousCallback: (_rawCommand, args) => {
const flagsWithArgs = new Set([
"--contains",
"--no-contains",
"--points-at",
"--sort"
]);
const flagsWithOptionalArgs = new Set(["--merged", "--no-merged"]);
let i2 = 0;
let lastFlag = "";
let seenListFlag = false;
let seenDashDash = false;
while (i2 < args.length) {
const token = args[i2];
if (!token) {
i2++;
continue;
}
if (token === "--" && !seenDashDash) {
seenDashDash = true;
lastFlag = "";
i2++;
continue;
}
if (!seenDashDash && token.startsWith("-")) {
if (token === "--list" || token === "-l") {
seenListFlag = true;
} else if (token[0] === "-" && token[1] !== "-" && token.length > 2 && !token.includes("=") && token.slice(1).includes("l")) {
seenListFlag = true;
}
if (token.includes("=")) {
lastFlag = token.split("=")[0] || "";
i2++;
} else if (flagsWithArgs.has(token)) {
lastFlag = token;
i2 += 2;
} else {
lastFlag = token;
i2++;
}
} else {
const lastFlagHasOptionalArg = flagsWithOptionalArgs.has(lastFlag);
if (!seenListFlag && !lastFlagHasOptionalArg) {
return true;
}
i2++;
}
}
return false;
}
}
};
GH_READ_ONLY_COMMANDS = {
"gh pr view": {
safeFlags: {
"--json": "string",
"--comments": "none",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh pr list": {
safeFlags: {
"--state": "string",
"-s": "string",
"--author": "string",
"--assignee": "string",
"--label": "string",
"--limit": "number",
"-L": "number",
"--base": "string",
"--head": "string",
"--search": "string",
"--json": "string",
"--draft": "none",
"--app": "string",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh pr diff": {
safeFlags: {
"--color": "string",
"--name-only": "none",
"--patch": "none",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh pr checks": {
safeFlags: {
"--watch": "none",
"--required": "none",
"--fail-fast": "none",
"--json": "string",
"--interval": "number",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh issue view": {
safeFlags: {
"--json": "string",
"--comments": "none",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh issue list": {
safeFlags: {
"--state": "string",
"-s": "string",
"--assignee": "string",
"--author": "string",
"--label": "string",
"--limit": "number",
"-L": "number",
"--milestone": "string",
"--search": "string",
"--json": "string",
"--app": "string",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh repo view": {
safeFlags: {
"--json": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh run list": {
safeFlags: {
"--branch": "string",
"-b": "string",
"--status": "string",
"-s": "string",
"--workflow": "string",
"-w": "string",
"--limit": "number",
"-L": "number",
"--json": "string",
"--repo": "string",
"-R": "string",
"--event": "string",
"-e": "string",
"--user": "string",
"-u": "string",
"--created": "string",
"--commit": "string",
"-c": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh run view": {
safeFlags: {
"--log": "none",
"--log-failed": "none",
"--exit-status": "none",
"--verbose": "none",
"-v": "none",
"--json": "string",
"--repo": "string",
"-R": "string",
"--job": "string",
"-j": "string",
"--attempt": "number",
"-a": "number"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh auth status": {
safeFlags: {
"--active": "none",
"-a": "none",
"--hostname": "string",
"-h": "string",
"--json": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh pr status": {
safeFlags: {
"--conflict-status": "none",
"-c": "none",
"--json": "string",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh issue status": {
safeFlags: {
"--json": "string",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh release list": {
safeFlags: {
"--exclude-drafts": "none",
"--exclude-pre-releases": "none",
"--json": "string",
"--limit": "number",
"-L": "number",
"--order": "string",
"-O": "string",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh release view": {
safeFlags: {
"--json": "string",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh workflow list": {
safeFlags: {
"--all": "none",
"-a": "none",
"--json": "string",
"--limit": "number",
"-L": "number",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh workflow view": {
safeFlags: {
"--ref": "string",
"-r": "string",
"--yaml": "none",
"-y": "none",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh label list": {
safeFlags: {
"--json": "string",
"--limit": "number",
"-L": "number",
"--order": "string",
"--search": "string",
"-S": "string",
"--sort": "string",
"--repo": "string",
"-R": "string"
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback
},
"gh search repos": {
safeFlags: {
"--archived": "none",
"--created": "string",
"--followers": "string",
"--forks": "string",
"--good-first-issues": "string",
"--help-wanted-issues": "string",
"--include-forks": "string",
"--json": "string",
"--language": "string",
"--license": "string",
"--limit": "number",
"-L": "number",
"--match": "string",
"--number-topics": "string",
"--order": "string",
"--owner": "string",
"--size": "string",
"--sort": "string",
"--stars": "string",
"--topic": "string",
"--updated": "string",
"--visibility": "string"
}
},
"gh search issues": {
safeFlags: {
"--app": "string",
"--assignee": "string",
"--author": "string",
"--closed": "string",
"--commenter": "string",
"--comments": "string",
"--created": "string",
"--include-prs": "none",
"--interactions": "string",
"--involves": "string",
"--json": "string",
"--label": "string",
"--language": "string",
"--limit": "number",
"-L": "number",
"--locked": "none",
"--match": "string",
"--mentions": "string",
"--milestone": "string",
"--no-assignee": "none",
"--no-label": "none",
"--no-milestone": "none",
"--no-project": "none",
"--order": "string",
"--owner": "string",
"--project": "string",
"--reactions": "string",
"--repo": "string",
"-R": "string",
"--sort": "string",
"--state": "string",
"--team-mentions": "string",
"--updated": "string",
"--visibility": "string"
}
},
"gh search prs": {
safeFlags: {
"--app": "string",
"--assignee": "string",
"--author": "string",
"--base": "string",
"-B": "string",
"--checks": "string",
"--closed": "string",
"--commenter": "string",
"--comments": "string",
"--created": "string",
"--draft": "none",
"--head": "string",
"-H": "string",
"--interactions": "string",
"--involves": "string",
"--json": "string",
"--label": "string",
"--language": "string",
"--limit": "number",
"-L": "number",
"--locked": "none",
"--match": "string",
"--mentions": "string",
"--merged": "none",
"--merged-at": "string",
"--milestone": "string",
"--no-assignee": "none",
"--no-label": "none",
"--no-milestone": "none",
"--no-project": "none",
"--order": "string",
"--owner": "string",
"--project": "string",
"--reactions": "string",
"--repo": "string",
"-R": "string",
"--review": "string",
"--review-requested": "string",
"--reviewed-by": "string",
"--sort": "string",
"--state": "string",
"--team-mentions": "string",
"--updated": "string",
"--visibility": "string"
}
},
"gh search commits": {
safeFlags: {
"--author": "string",
"--author-date": "string",
"--author-email": "string",
"--author-name": "string",
"--committer": "string",
"--committer-date": "string",
"--committer-email": "string",
"--committer-name": "string",
"--hash": "string",
"--json": "string",
"--limit": "number",
"-L": "number",
"--merge": "none",
"--order": "string",
"--owner": "string",
"--parent": "string",
"--repo": "string",
"-R": "string",
"--sort": "string",
"--tree": "string",
"--visibility": "string"
}
},
"gh search code": {
safeFlags: {
"--extension": "string",
"--filename": "string",
"--json": "string",
"--language": "string",
"--limit": "number",
"-L": "number",
"--match": "string",
"--owner": "string",
"--repo": "string",
"-R": "string",
"--size": "string"
}
}
};
DOCKER_READ_ONLY_COMMANDS = {
"docker logs": {
safeFlags: {
"--follow": "none",
"-f": "none",
"--tail": "string",
"-n": "string",
"--timestamps": "none",
"-t": "none",
"--since": "string",
"--until": "string",
"--details": "none"
}
},
"docker inspect": {
safeFlags: {
"--format": "string",
"-f": "string",
"--type": "string",
"--size": "none",
"-s": "none"
}
}
};
RIPGREP_READ_ONLY_COMMANDS = {
rg: {
safeFlags: {
"-e": "string",
"--regexp": "string",
"-f": "string",
"-i": "none",
"--ignore-case": "none",
"-S": "none",
"--smart-case": "none",
"-F": "none",
"--fixed-strings": "none",
"-w": "none",
"--word-regexp": "none",
"-v": "none",
"--invert-match": "none",
"-c": "none",
"--count": "none",
"-l": "none",
"--files-with-matches": "none",
"--files-without-match": "none",
"-n": "none",
"--line-number": "none",
"-o": "none",
"--only-matching": "none",
"-A": "number",
"--after-context": "number",
"-B": "number",
"--before-context": "number",
"-C": "number",
"--context": "number",
"-H": "none",
"-h": "none",
"--heading": "none",
"--no-heading": "none",
"-q": "none",
"--quiet": "none",
"--column": "none",
"-g": "string",
"--glob": "string",
"-t": "string",
"--type": "string",
"-T": "string",
"--type-not": "string",
"--type-list": "none",
"--hidden": "none",
"--no-ignore": "none",
"-u": "none",
"-m": "number",
"--max-count": "number",
"-d": "number",
"--max-depth": "number",
"-a": "none",
"--text": "none",
"-z": "none",
"-L": "none",
"--follow": "none",
"--color": "string",
"--json": "none",
"--stats": "none",
"--help": "none",
"--version": "none",
"--debug": "none",
"--": "none"
}
}
};
PYRIGHT_READ_ONLY_COMMANDS = {
pyright: {
respectsDoubleDash: false,
safeFlags: {
"--outputjson": "none",
"--project": "string",
"-p": "string",
"--pythonversion": "string",
"--pythonplatform": "string",
"--typeshedpath": "string",
"--venvpath": "string",
"--level": "string",
"--stats": "none",
"--verbose": "none",
"--version": "none",
"--dependencies": "none",
"--warnings": "none"
},
additionalCommandIsDangerousCallback: (_rawCommand, args) => {
return args.some((t) => t === "--watch" || t === "-w");
}
}
};
EXTERNAL_READONLY_COMMANDS = [
"docker ps",
"docker images"
];
FLAG_PATTERN = /^-[a-zA-Z0-9_-]/;
});
// src/utils/permissions/pathValidation.ts
import { homedir as homedir13 } from "os";
import { dirname as dirname17, isAbsolute as isAbsolute6, resolve as resolve15 } from "path";
function formatDirectoryList(directories) {
const dirCount = directories.length;
if (dirCount <= MAX_DIRS_TO_LIST) {
return directories.map((dir) => `'${dir}'`).join(", ");
}
const firstDirs = directories.slice(0, MAX_DIRS_TO_LIST).map((dir) => `'${dir}'`).join(", ");
return `${firstDirs}, and ${dirCount - MAX_DIRS_TO_LIST} more`;
}
function getGlobBaseDirectory(path11) {
const globMatch = path11.match(GLOB_PATTERN_REGEX);
if (!globMatch || globMatch.index === undefined) {
return path11;
}
const beforeGlob = path11.substring(0, globMatch.index);
const lastSepIndex = getPlatform() === "windows" ? Math.max(beforeGlob.lastIndexOf("/"), beforeGlob.lastIndexOf("\\")) : beforeGlob.lastIndexOf("/");
if (lastSepIndex === -1)
return ".";
return beforeGlob.substring(0, lastSepIndex) || "/";
}
function expandTilde(path11) {
if (path11 === "~" || path11.startsWith("~/") || process.platform === "win32" && path11.startsWith("~\\")) {
return homedir13() + path11.slice(1);
}
return path11;
}
function isPathInSandboxWriteAllowlist(resolvedPath) {
if (!SandboxManager5.isSandboxingEnabled()) {
return false;
}
const { allowOnly, denyWithinAllow } = SandboxManager5.getFsWriteConfig();
const pathsToCheck = getPathsForPermissionCheck(resolvedPath);
const resolvedAllow = allowOnly.flatMap(getResolvedSandboxConfigPath);
const resolvedDeny = denyWithinAllow.flatMap(getResolvedSandboxConfigPath);
return pathsToCheck.every((p) => {
for (const denyPath of resolvedDeny) {
if (pathInWorkingPath(p, denyPath))
return false;
}
return resolvedAllow.some((allowPath) => pathInWorkingPath(p, allowPath));
});
}
function isPathAllowed(resolvedPath, context2, operationType, precomputedPathsToCheck) {
const permissionType = operationType === "read" ? "read" : "edit";
const denyRule = matchingRuleForInput(resolvedPath, context2, permissionType, "deny");
if (denyRule !== null) {
return {
allowed: false,
decisionReason: { type: "rule", rule: denyRule }
};
}
if (operationType !== "read") {
const internalEditResult = checkEditableInternalPath(resolvedPath, {});
if (internalEditResult.behavior === "allow") {
return {
allowed: true,
decisionReason: internalEditResult.decisionReason
};
}
}
if (operationType !== "read") {
const safetyCheck = checkPathSafetyForAutoEdit(resolvedPath, precomputedPathsToCheck);
if (!safetyCheck.safe) {
return {
allowed: false,
decisionReason: {
type: "safetyCheck",
reason: safetyCheck.message,
classifierApprovable: safetyCheck.classifierApprovable
}
};
}
}
const isInWorkingDir = pathInAllowedWorkingPath(resolvedPath, context2, precomputedPathsToCheck);
if (isInWorkingDir) {
if (operationType === "read" || context2.mode === "acceptEdits") {
return { allowed: true };
}
}
if (operationType === "read") {
const internalReadResult = checkReadableInternalPath(resolvedPath, {});
if (internalReadResult.behavior === "allow") {
return {
allowed: true,
decisionReason: internalReadResult.decisionReason
};
}
}
if (operationType !== "read" && !isInWorkingDir && isPathInSandboxWriteAllowlist(resolvedPath)) {
return {
allowed: true,
decisionReason: {
type: "other",
reason: "Path is in sandbox write allowlist"
}
};
}
const allowRule = matchingRuleForInput(resolvedPath, context2, permissionType, "allow");
if (allowRule !== null) {
return {
allowed: true,
decisionReason: { type: "rule", rule: allowRule }
};
}
return { allowed: false };
}
function validateGlobPattern(cleanPath, cwd2, toolPermissionContext, operationType) {
if (containsPathTraversal(cleanPath)) {
const absolutePath = isAbsolute6(cleanPath) ? cleanPath : resolve15(cwd2, cleanPath);
const { resolvedPath: resolvedPath2, isCanonical: isCanonical2 } = safeResolvePath(getFsImplementation(), absolutePath);
const result2 = isPathAllowed(resolvedPath2, toolPermissionContext, operationType, isCanonical2 ? [resolvedPath2] : undefined);
return {
allowed: result2.allowed,
resolvedPath: resolvedPath2,
decisionReason: result2.decisionReason
};
}
const basePath = getGlobBaseDirectory(cleanPath);
const absoluteBasePath = isAbsolute6(basePath) ? basePath : resolve15(cwd2, basePath);
const { resolvedPath, isCanonical } = safeResolvePath(getFsImplementation(), absoluteBasePath);
const result = isPathAllowed(resolvedPath, toolPermissionContext, operationType, isCanonical ? [resolvedPath] : undefined);
return {
allowed: result.allowed,
resolvedPath,
decisionReason: result.decisionReason
};
}
function isDangerousRemovalPath(resolvedPath) {
const forwardSlashed = resolvedPath.replace(/[\\/]+/g, "/");
if (forwardSlashed === "*" || forwardSlashed.endsWith("/*")) {
return true;
}
const normalizedPath = forwardSlashed === "/" ? forwardSlashed : forwardSlashed.replace(/\/$/, "");
if (normalizedPath === "/") {
return true;
}
if (WINDOWS_DRIVE_ROOT_REGEX.test(normalizedPath)) {
return true;
}
const normalizedHome = homedir13().replace(/[\\/]+/g, "/");
if (normalizedPath === normalizedHome) {
return true;
}
const parentDir = dirname17(normalizedPath);
if (parentDir === "/") {
return true;
}
if (WINDOWS_DRIVE_CHILD_REGEX.test(normalizedPath)) {
return true;
}
return false;
}
function validatePath(path11, cwd2, toolPermissionContext, operationType) {
const cleanPath = expandTilde(path11.replace(/^['"]|['"]$/g, ""));
if (containsVulnerableUncPath(cleanPath)) {
return {
allowed: false,
resolvedPath: cleanPath,
decisionReason: {
type: "other",
reason: "UNC network paths require manual approval"
}
};
}
if (cleanPath.startsWith("~")) {
return {
allowed: false,
resolvedPath: cleanPath,
decisionReason: {
type: "other",
reason: "Tilde expansion variants (~user, ~+, ~-) in paths require manual approval"
}
};
}
if (cleanPath.includes("$") || cleanPath.includes("%") || cleanPath.startsWith("=")) {
return {
allowed: false,
resolvedPath: cleanPath,
decisionReason: {
type: "other",
reason: "Shell expansion syntax in paths requires manual approval"
}
};
}
if (GLOB_PATTERN_REGEX.test(cleanPath)) {
if (operationType === "write" || operationType === "create") {
return {
allowed: false,
resolvedPath: cleanPath,
decisionReason: {
type: "other",
reason: "Glob patterns are not allowed in write operations. Please specify an exact file path."
}
};
}
return validateGlobPattern(cleanPath, cwd2, toolPermissionContext, operationType);
}
const absolutePath = isAbsolute6(cleanPath) ? cleanPath : resolve15(cwd2, cleanPath);
const { resolvedPath, isCanonical } = safeResolvePath(getFsImplementation(), absolutePath);
const result = isPathAllowed(resolvedPath, toolPermissionContext, operationType, isCanonical ? [resolvedPath] : undefined);
return {
allowed: result.allowed,
resolvedPath,
decisionReason: result.decisionReason
};
}
var MAX_DIRS_TO_LIST = 5, GLOB_PATTERN_REGEX, getResolvedSandboxConfigPath, WINDOWS_DRIVE_ROOT_REGEX, WINDOWS_DRIVE_CHILD_REGEX;
var init_pathValidation = __esm(() => {
init_memoize();
init_platform2();
init_fsOperations();
init_path2();
init_sandbox_adapter();
init_readOnlyCommandValidation();
init_filesystem();
GLOB_PATTERN_REGEX = /[*?[\]{}]/;
getResolvedSandboxConfigPath = memoize_default(getPathsForPermissionCheck);
WINDOWS_DRIVE_ROOT_REGEX = /^[A-Za-z]:\/?$/;
WINDOWS_DRIVE_CHILD_REGEX = /^[A-Za-z]:\/[^/]+$/;
});
// src/utils/plugins/pluginDirectories.ts
import { mkdirSync as mkdirSync3 } from "fs";
import { readdir as readdir7, rm, stat as stat14 } from "fs/promises";
import { delimiter, join as join31 } from "path";
function getPluginsDirectoryName() {
if (getUseCoworkPlugins()) {
return COWORK_PLUGINS_DIR;
}
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS)) {
return COWORK_PLUGINS_DIR;
}
return PLUGINS_DIR;
}
function getPluginsDirectory() {
const envOverride = process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR;
if (envOverride) {
return expandTilde(envOverride);
}
return join31(getClaudeConfigHomeDir(), getPluginsDirectoryName());
}
function getPluginSeedDirs() {
const raw = process.env.CLAUDE_CODE_PLUGIN_SEED_DIR;
if (!raw)
return [];
return raw.split(delimiter).filter(Boolean).map(expandTilde);
}
function sanitizePluginId(pluginId) {
return pluginId.replace(/[^a-zA-Z0-9\-_]/g, "-");
}
function pluginDataDirPath(pluginId) {
return join31(getPluginsDirectory(), "data", sanitizePluginId(pluginId));
}
function getPluginDataDir(pluginId) {
const dir = pluginDataDirPath(pluginId);
mkdirSync3(dir, { recursive: true });
return dir;
}
async function getPluginDataDirSize(pluginId) {
const dir = pluginDataDirPath(pluginId);
let bytes = 0;
const walk = async (p) => {
for (const entry of await readdir7(p, { withFileTypes: true })) {
const full = join31(p, entry.name);
if (entry.isDirectory()) {
await walk(full);
} else {
try {
bytes += (await stat14(full)).size;
} catch {}
}
}
};
try {
await walk(dir);
} catch (e) {
if (isFsInaccessible(e))
return null;
throw e;
}
if (bytes === 0)
return null;
return { bytes, human: formatFileSize(bytes) };
}
async function deletePluginDataDir(pluginId) {
const dir = pluginDataDirPath(pluginId);
try {
await rm(dir, { recursive: true, force: true });
} catch (e) {
logForDebugging(`Failed to delete plugin data dir ${dir}: ${errorMessage(e)}`, { level: "warn" });
}
}
var PLUGINS_DIR = "plugins", COWORK_PLUGINS_DIR = "cowork_plugins";
var init_pluginDirectories = __esm(() => {
init_state();
init_debug();
init_envUtils();
init_errors();
init_format();
init_pathValidation();
});
// src/utils/thinking.ts
function isUltrathinkEnabled() {
if (true) {
return false;
}
return getFeatureValue_CACHED_MAY_BE_STALE("tengu_turtle_carbon", true);
}
function hasUltrathinkKeyword(text) {
return /\bultrathink\b/i.test(text);
}
function findThinkingTriggerPositions(text) {
const positions = [];
const matches = text.matchAll(/\bultrathink\b/gi);
for (const match of matches) {
if (match.index !== undefined) {
positions.push({
word: match[0],
start: match.index,
end: match.index + match[0].length
});
}
}
return positions;
}
function getRainbowColor(charIndex, shimmer = false) {
const colors = shimmer ? RAINBOW_SHIMMER_COLORS : RAINBOW_COLORS;
return colors[charIndex % colors.length];
}
function modelSupportsThinking(model) {
const supported3P = get3PModelCapabilityOverride(model, "thinking");
if (supported3P !== undefined) {
return supported3P;
}
if (process.env.USER_TYPE === "ant") {
if (resolveAntModel(model.toLowerCase())) {
return true;
}
}
const canonical = getCanonicalName(model);
const provider = getAPIProvider();
if (provider === "foundry" || provider === "firstParty") {
return !canonical.includes("claude-3-");
}
return canonical.includes("sonnet-4") || canonical.includes("opus-4");
}
function modelSupportsAdaptiveThinking(model) {
const supported3P = get3PModelCapabilityOverride(model, "adaptive_thinking");
if (supported3P !== undefined) {
return supported3P;
}
const canonical = getCanonicalName(model);
if (canonical.includes("opus-4-6") || canonical.includes("sonnet-4-6")) {
return true;
}
if (canonical.includes("opus") || canonical.includes("sonnet") || canonical.includes("haiku")) {
return false;
}
const provider = getAPIProvider();
return provider === "firstParty" || provider === "foundry";
}
function shouldEnableThinkingByDefault() {
if (process.env.MAX_THINKING_TOKENS) {
return parseInt(process.env.MAX_THINKING_TOKENS, 10) > 0;
}
const { settings } = getSettingsWithErrors();
if (settings.alwaysThinkingEnabled === false) {
return false;
}
return true;
}
var RAINBOW_COLORS, RAINBOW_SHIMMER_COLORS;
var init_thinking = __esm(() => {
init_growthbook();
init_model();
init_modelSupportOverrides();
init_providers();
init_settings2();
RAINBOW_COLORS = [
"rainbow_red",
"rainbow_orange",
"rainbow_yellow",
"rainbow_green",
"rainbow_blue",
"rainbow_indigo",
"rainbow_violet"
];
RAINBOW_SHIMMER_COLORS = [
"rainbow_red_shimmer",
"rainbow_orange_shimmer",
"rainbow_yellow_shimmer",
"rainbow_green_shimmer",
"rainbow_blue_shimmer",
"rainbow_indigo_shimmer",
"rainbow_violet_shimmer"
];
});
// src/utils/effort.ts
function modelSupportsEffort(model) {
const m = model.toLowerCase();
if (isEnvTruthy(process.env.CLAUDE_CODE_ALWAYS_ENABLE_EFFORT)) {
return true;
}
const supported3P = get3PModelCapabilityOverride(model, "effort");
if (supported3P !== undefined) {
return supported3P;
}
if (m.includes("opus-4-6") || m.includes("sonnet-4-6")) {
return true;
}
if (m.includes("haiku") || m.includes("sonnet") || m.includes("opus")) {
return false;
}
return getAPIProvider() === "firstParty";
}
function modelSupportsMaxEffort(model) {
const supported3P = get3PModelCapabilityOverride(model, "max_effort");
if (supported3P !== undefined) {
return supported3P;
}
if (model.toLowerCase().includes("opus-4-6")) {
return true;
}
if (process.env.USER_TYPE === "ant" && resolveAntModel(model)) {
return true;
}
return false;
}
function isEffortLevel(value) {
return EFFORT_LEVELS.includes(value);
}
function parseEffortValue(value) {
if (value === undefined || value === null || value === "") {
return;
}
if (typeof value === "number" && isValidNumericEffort(value)) {
return value;
}
const str = String(value).toLowerCase();
if (isEffortLevel(str)) {
return str;
}
const numericValue = parseInt(str, 10);
if (!isNaN(numericValue) && isValidNumericEffort(numericValue)) {
return numericValue;
}
return;
}
function toPersistableEffort(value) {
if (value === "low" || value === "medium" || value === "high") {
return value;
}
if (value === "max" && process.env.USER_TYPE === "ant") {
return value;
}
return;
}
function getInitialEffortSetting() {
return toPersistableEffort(getInitialSettings().effortLevel);
}
function resolvePickerEffortPersistence(picked, modelDefault, priorPersisted, toggledInPicker) {
const hadExplicit = priorPersisted !== undefined || toggledInPicker;
return hadExplicit || picked !== modelDefault ? picked : undefined;
}
function getEffortEnvOverride() {
const envOverride = process.env.CLAUDE_CODE_EFFORT_LEVEL;
return envOverride?.toLowerCase() === "unset" || envOverride?.toLowerCase() === "auto" ? null : parseEffortValue(envOverride);
}
function resolveAppliedEffort(model, appStateEffortValue) {
const envOverride = getEffortEnvOverride();
if (envOverride === null) {
return;
}
const resolved = envOverride ?? appStateEffortValue ?? getDefaultEffortForModel(model);
if (resolved === "max" && !modelSupportsMaxEffort(model)) {
return "high";
}
return resolved;
}
function getDisplayedEffortLevel(model, appStateEffort) {
const resolved = resolveAppliedEffort(model, appStateEffort) ?? "high";
return convertEffortValueToLevel(resolved);
}
function getEffortSuffix(model, effortValue) {
if (effortValue === undefined)
return "";
const resolved = resolveAppliedEffort(model, effortValue);
if (resolved === undefined)
return "";
return ` with ${convertEffortValueToLevel(resolved)} effort`;
}
function isValidNumericEffort(value) {
return Number.isInteger(value);
}
function convertEffortValueToLevel(value) {
if (typeof value === "string") {
return isEffortLevel(value) ? value : "high";
}
if (process.env.USER_TYPE === "ant" && typeof value === "number") {
if (value <= 50)
return "low";
if (value <= 85)
return "medium";
if (value <= 100)
return "high";
return "max";
}
return "high";
}
function getEffortLevelDescription(level) {
switch (level) {
case "low":
return "Quick, straightforward implementation with minimal overhead";
case "medium":
return "Balanced approach with standard implementation and testing";
case "high":
return "Comprehensive implementation with extensive testing and documentation";
case "max":
return "Maximum capability with deepest reasoning (Opus 4.6 only)";
}
}
function getEffortValueDescription(value) {
if (process.env.USER_TYPE === "ant" && typeof value === "number") {
return `[ANT-ONLY] Numeric effort value of ${value}`;
}
if (typeof value === "string") {
return getEffortLevelDescription(value);
}
return "Balanced approach with standard implementation and testing";
}
function getOpusDefaultEffortConfig() {
const config2 = getFeatureValue_CACHED_MAY_BE_STALE("tengu_grey_step2", OPUS_DEFAULT_EFFORT_CONFIG_DEFAULT);
return {
...OPUS_DEFAULT_EFFORT_CONFIG_DEFAULT,
...config2
};
}
function getDefaultEffortForModel(model) {
if (process.env.USER_TYPE === "ant") {
const config2 = getAntModelOverrideConfig();
const isDefaultModel = config2?.defaultModel !== undefined && model.toLowerCase() === config2.defaultModel.toLowerCase();
if (isDefaultModel && config2?.defaultModelEffortLevel) {
return config2.defaultModelEffortLevel;
}
const antModel = resolveAntModel(model);
if (antModel) {
if (antModel.defaultEffortLevel) {
return antModel.defaultEffortLevel;
}
if (antModel.defaultEffortValue !== undefined) {
return antModel.defaultEffortValue;
}
}
return;
}
if (model.toLowerCase().includes("opus-4-6")) {
if (isProSubscriber()) {
return "medium";
}
if (getOpusDefaultEffortConfig().enabled && (isMaxSubscriber() || isTeamSubscriber())) {
return "medium";
}
}
if (isUltrathinkEnabled() && modelSupportsEffort(model)) {
return "medium";
}
return;
}
var EFFORT_LEVELS, OPUS_DEFAULT_EFFORT_CONFIG_DEFAULT;
var init_effort = __esm(() => {
init_thinking();
init_settings2();
init_auth2();
init_growthbook();
init_providers();
init_modelSupportOverrides();
init_envUtils();
EFFORT_LEVELS = [
"low",
"medium",
"high",
"max"
];
OPUS_DEFAULT_EFFORT_CONFIG_DEFAULT = {
enabled: true,
dialogTitle: "We recommend medium effort for Opus",
dialogDescription: "Effort determines how long Claude thinks for when completing your task. We recommend medium effort for most tasks to balance speed and intelligence and maximize rate limits. Use ultrathink to trigger high effort when needed."
};
});
// native-stub:@anthropic-ai/mcpb
var exports_mcpb = {};
__export(exports_mcpb, {
trace: () => trace2,
resourceFromAttributes: () => resourceFromAttributes2,
plot: () => plot2,
getSyntaxTheme: () => getSyntaxTheme2,
getMcpConfigForManifest: () => getMcpConfigForManifest2,
default: () => mcpb_default,
createComputerUseMcpServer: () => createComputerUseMcpServer2,
createClaudeForChromeMcpServer: () => createClaudeForChromeMcpServer2,
context: () => context2,
__stub: () => __stub2,
SpanStatusCode: () => SpanStatusCode2,
SimpleSpanProcessor: () => SimpleSpanProcessor2,
SimpleLogRecordProcessor: () => SimpleLogRecordProcessor2,
SeverityNumber: () => SeverityNumber2,
SandboxViolationStore: () => SandboxViolationStore3,
SandboxRuntimeConfigSchema: () => SandboxRuntimeConfigSchema3,
SandboxManager: () => SandboxManager6,
SEMRESATTRS_SERVICE_VERSION: () => SEMRESATTRS_SERVICE_VERSION2,
SEMRESATTRS_SERVICE_NAME: () => SEMRESATTRS_SERVICE_NAME2,
Resource: () => Resource2,
PushMetricExporter: () => PushMetricExporter2,
PrometheusExporter: () => PrometheusExporter2,
PeriodicExportingMetricReader: () => PeriodicExportingMetricReader2,
OTLPTraceExporter: () => OTLPTraceExporter2,
OTLPMetricExporter: () => OTLPMetricExporter2,
OTLPLogExporter: () => OTLPLogExporter2,
NodeTracerProvider: () => NodeTracerProvider2,
MeterProvider: () => MeterProvider2,
LoggerProvider: () => LoggerProvider2,
InstrumentType: () => InstrumentType2,
ExportResultCode: () => ExportResultCode2,
DataPointType: () => DataPointType2,
ColorFile: () => ColorFile2,
ColorDiff: () => ColorDiff2,
BatchSpanProcessor: () => BatchSpanProcessor2,
BatchLogRecordProcessor: () => BatchLogRecordProcessor2,
BasicTracerProvider: () => BasicTracerProvider2,
BROWSER_TOOLS: () => BROWSER_TOOLS2,
AggregationTemporality: () => AggregationTemporality2,
ATTR_SERVICE_VERSION: () => ATTR_SERVICE_VERSION2,
ATTR_SERVICE_NAME: () => ATTR_SERVICE_NAME2
});
var noop12 = () => null, noopClass2 = class {
}, handler5, stub5, mcpb_default, __stub2 = true, SandboxViolationStore3 = null, SandboxManager6, SandboxRuntimeConfigSchema3, BROWSER_TOOLS2, getMcpConfigForManifest2, ColorDiff2 = null, ColorFile2 = null, getSyntaxTheme2, plot2, createClaudeForChromeMcpServer2, createComputerUseMcpServer2, ExportResultCode2, resourceFromAttributes2, Resource2, SimpleSpanProcessor2, BatchSpanProcessor2, NodeTracerProvider2, BasicTracerProvider2, OTLPTraceExporter2, OTLPLogExporter2, OTLPMetricExporter2, PrometheusExporter2, LoggerProvider2, SimpleLogRecordProcessor2, BatchLogRecordProcessor2, MeterProvider2, PeriodicExportingMetricReader2, trace2, context2, SpanStatusCode2, ATTR_SERVICE_NAME2 = "service.name", ATTR_SERVICE_VERSION2 = "service.version", SEMRESATTRS_SERVICE_NAME2 = "service.name", SEMRESATTRS_SERVICE_VERSION2 = "service.version", AggregationTemporality2, DataPointType2, InstrumentType2, PushMetricExporter2, SeverityNumber2;
var init_mcpb = __esm(() => {
handler5 = {
get(_, prop) {
if (prop === "__esModule")
return true;
if (prop === "default")
return new Proxy({}, handler5);
if (prop === "ExportResultCode")
return { SUCCESS: 0, FAILED: 1 };
if (prop === "resourceFromAttributes")
return () => ({});
if (prop === "SandboxRuntimeConfigSchema")
return { parse: () => ({}) };
return noop12;
}
};
stub5 = new Proxy(noop12, handler5);
mcpb_default = stub5;
SandboxManager6 = new Proxy({}, { get: () => noop12 });
SandboxRuntimeConfigSchema3 = { parse: () => ({}) };
BROWSER_TOOLS2 = [];
getMcpConfigForManifest2 = noop12;
getSyntaxTheme2 = noop12;
plot2 = noop12;
createClaudeForChromeMcpServer2 = noop12;
createComputerUseMcpServer2 = noop12;
ExportResultCode2 = { SUCCESS: 0, FAILED: 1 };
resourceFromAttributes2 = noop12;
Resource2 = noopClass2;
SimpleSpanProcessor2 = noopClass2;
BatchSpanProcessor2 = noopClass2;
NodeTracerProvider2 = noopClass2;
BasicTracerProvider2 = noopClass2;
OTLPTraceExporter2 = noopClass2;
OTLPLogExporter2 = noopClass2;
OTLPMetricExporter2 = noopClass2;
PrometheusExporter2 = noopClass2;
LoggerProvider2 = noopClass2;
SimpleLogRecordProcessor2 = noopClass2;
BatchLogRecordProcessor2 = noopClass2;
MeterProvider2 = noopClass2;
PeriodicExportingMetricReader2 = noopClass2;
trace2 = { getTracer: () => ({ startSpan: () => ({ end: noop12, setAttribute: noop12, setStatus: noop12, recordException: noop12 }) }) };
context2 = { active: noop12, with: (_, fn) => fn() };
SpanStatusCode2 = { OK: 0, ERROR: 1, UNSET: 2 };
AggregationTemporality2 = { CUMULATIVE: 0, DELTA: 1 };
DataPointType2 = { HISTOGRAM: 0, SUM: 1, GAUGE: 2 };
InstrumentType2 = { COUNTER: 0, HISTOGRAM: 1, UP_DOWN_COUNTER: 2 };
PushMetricExporter2 = noopClass2;
SeverityNumber2 = {};
});
// src/utils/dxt/helpers.ts
async function validateManifest(manifestJson) {
const { McpbManifestSchema } = await Promise.resolve().then(() => (init_mcpb(), exports_mcpb));
const parseResult = McpbManifestSchema.safeParse(manifestJson);
if (!parseResult.success) {
const errors3 = parseResult.error.flatten();
const errorMessages = [
...Object.entries(errors3.fieldErrors).map(([field, errs]) => `${field}: ${errs?.join(", ")}`),
...errors3.formErrors || []
].filter(Boolean).join("; ");
throw new Error(`Invalid manifest: ${errorMessages}`);
}
return parseResult.data;
}
async function parseAndValidateManifestFromText(manifestText) {
let manifestJson;
try {
manifestJson = jsonParse(manifestText);
} catch (error44) {
throw new Error(`Invalid JSON in manifest.json: ${errorMessage(error44)}`);
}
return validateManifest(manifestJson);
}
async function parseAndValidateManifestFromBytes(manifestData) {
const manifestText = new TextDecoder().decode(manifestData);
return parseAndValidateManifestFromText(manifestText);
}
var init_helpers = __esm(() => {
init_errors();
init_slowOperations();
});
// node_modules/fflate/esm/index.mjs
var exports_esm = {};
__export(exports_esm, {
zlibSync: () => zlibSync,
zlib: () => zlib2,
zipSync: () => zipSync,
zip: () => zip,
unzlibSync: () => unzlibSync,
unzlib: () => unzlib,
unzipSync: () => unzipSync,
unzip: () => unzip,
strToU8: () => strToU8,
strFromU8: () => strFromU8,
inflateSync: () => inflateSync,
inflate: () => inflate,
gzipSync: () => gzipSync,
gzip: () => gzip,
gunzipSync: () => gunzipSync,
gunzip: () => gunzip,
deflateSync: () => deflateSync,
deflate: () => deflate,
decompressSync: () => decompressSync,
decompress: () => decompress,
compressSync: () => gzipSync,
compress: () => gzip,
Zlib: () => Zlib,
ZipPassThrough: () => ZipPassThrough,
ZipDeflate: () => ZipDeflate,
Zip: () => Zip,
Unzlib: () => Unzlib,
UnzipPassThrough: () => UnzipPassThrough,
UnzipInflate: () => UnzipInflate,
Unzip: () => Unzip,
Inflate: () => Inflate,
Gzip: () => Gzip,
Gunzip: () => Gunzip,
FlateErrorCode: () => FlateErrorCode,
EncodeUTF8: () => EncodeUTF8,
Deflate: () => Deflate,
Decompress: () => Decompress,
DecodeUTF8: () => DecodeUTF8,
Compress: () => Gzip,
AsyncZlib: () => AsyncZlib,
AsyncZipDeflate: () => AsyncZipDeflate,
AsyncUnzlib: () => AsyncUnzlib,
AsyncUnzipInflate: () => AsyncUnzipInflate,
AsyncInflate: () => AsyncInflate,
AsyncGzip: () => AsyncGzip,
AsyncGunzip: () => AsyncGunzip,
AsyncDeflate: () => AsyncDeflate,
AsyncDecompress: () => AsyncDecompress,
AsyncCompress: () => AsyncGzip
});
import { createRequire as createRequire2 } from "module";
function StrmOpt(opts, cb) {
if (typeof opts == "function")
cb = opts, opts = {};
this.ondata = cb;
return opts;
}
function deflate(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
return cbify(data, opts, [
bDflt
], function(ev) {
return pbf(deflateSync(ev.data[0], ev.data[1]));
}, 0, cb);
}
function deflateSync(data, opts) {
return dopt(data, opts || {}, 0, 0);
}
function inflate(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
return cbify(data, opts, [
bInflt
], function(ev) {
return pbf(inflateSync(ev.data[0], gopt(ev.data[1])));
}, 1, cb);
}
function inflateSync(data, opts) {
return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
function gzip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
return cbify(data, opts, [
bDflt,
gze,
function() {
return [gzipSync];
}
], function(ev) {
return pbf(gzipSync(ev.data[0], ev.data[1]));
}, 2, cb);
}
function gzipSync(data, opts) {
if (!opts)
opts = {};
var c7 = crc(), l = data.length;
c7.p(data);
var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
return gzh(d, opts), wbytes(d, s - 8, c7.d()), wbytes(d, s - 4, l), d;
}
function gunzip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
return cbify(data, opts, [
bInflt,
guze,
function() {
return [gunzipSync];
}
], function(ev) {
return pbf(gunzipSync(ev.data[0], ev.data[1]));
}, 3, cb);
}
function gunzipSync(data, opts) {
var st = gzs(data);
if (st + 8 > data.length)
err(6, "invalid gzip data");
return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
}
function zlib2(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
return cbify(data, opts, [
bDflt,
zle,
function() {
return [zlibSync];
}
], function(ev) {
return pbf(zlibSync(ev.data[0], ev.data[1]));
}, 4, cb);
}
function zlibSync(data, opts) {
if (!opts)
opts = {};
var a2 = adler();
a2.p(data);
var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
return zlh(d, opts), wbytes(d, d.length - 4, a2.d()), d;
}
function unzlib(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
return cbify(data, opts, [
bInflt,
zule,
function() {
return [unzlibSync];
}
], function(ev) {
return pbf(unzlibSync(ev.data[0], gopt(ev.data[1])));
}, 5, cb);
}
function unzlibSync(data, opts) {
return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
function decompress(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzip(data, opts, cb) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflate(data, opts, cb) : unzlib(data, opts, cb);
}
function decompressSync(data, opts) {
return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
}
function strToU8(str, latin1) {
if (latin1) {
var ar_1 = new u8(str.length);
for (var i3 = 0;i3 < str.length; ++i3)
ar_1[i3] = str.charCodeAt(i3);
return ar_1;
}
if (te)
return te.encode(str);
var l = str.length;
var ar = new u8(str.length + (str.length >> 1));
var ai = 0;
var w = function(v) {
ar[ai++] = v;
};
for (var i3 = 0;i3 < l; ++i3) {
if (ai + 5 > ar.length) {
var n2 = new u8(ai + 8 + (l - i3 << 1));
n2.set(ar);
ar = n2;
}
var c7 = str.charCodeAt(i3);
if (c7 < 128 || latin1)
w(c7);
else if (c7 < 2048)
w(192 | c7 >> 6), w(128 | c7 & 63);
else if (c7 > 55295 && c7 < 57344)
c7 = 65536 + (c7 & 1023 << 10) | str.charCodeAt(++i3) & 1023, w(240 | c7 >> 18), w(128 | c7 >> 12 & 63), w(128 | c7 >> 6 & 63), w(128 | c7 & 63);
else
w(224 | c7 >> 12), w(128 | c7 >> 6 & 63), w(128 | c7 & 63);
}
return slc(ar, 0, ai);
}
function strFromU8(dat, latin1) {
if (latin1) {
var r = "";
for (var i3 = 0;i3 < dat.length; i3 += 16384)
r += String.fromCharCode.apply(null, dat.subarray(i3, i3 + 16384));
return r;
} else if (td) {
return td.decode(dat);
} else {
var _a3 = dutf8(dat), s = _a3.s, r = _a3.r;
if (r.length)
err(8);
return s;
}
}
function zip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
var r = {};
fltn(data, "", r, opts);
var k = Object.keys(r);
var lft = k.length, o2 = 0, tot = 0;
var slft = lft, files = new Array(lft);
var term = [];
var tAll = function() {
for (var i4 = 0;i4 < term.length; ++i4)
term[i4]();
};
var cbd = function(a2, b) {
mt(function() {
cb(a2, b);
});
};
mt(function() {
cbd = cb;
});
var cbf = function() {
var out = new u8(tot + 22), oe = o2, cdl = tot - o2;
tot = 0;
for (var i4 = 0;i4 < slft; ++i4) {
var f = files[i4];
try {
var l = f.c.length;
wzh(out, tot, f, f.f, f.u, l);
var badd = 30 + f.f.length + exfl(f.extra);
var loc = tot + badd;
out.set(f.c, loc);
wzh(out, o2, f, f.f, f.u, l, tot, f.m), o2 += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
} catch (e) {
return cbd(e, null);
}
}
wzf(out, o2, files.length, cdl, oe);
cbd(null, out);
};
if (!lft)
cbf();
var _loop_1 = function(i4) {
var fn = k[i4];
var _a3 = r[fn], file2 = _a3[0], p = _a3[1];
var c7 = crc(), size = file2.length;
c7.p(file2);
var f = strToU8(fn), s = f.length;
var com = p.comment, m = com && strToU8(com), ms = m && m.length;
var exl = exfl(p.extra);
var compression = p.level == 0 ? 0 : 8;
var cbl = function(e, d) {
if (e) {
tAll();
cbd(e, null);
} else {
var l = d.length;
files[i4] = mrg(p, {
size,
crc: c7.d(),
c: d,
f,
m,
u: s != fn.length || m && com.length != ms,
compression
});
o2 += 30 + s + exl + l;
tot += 76 + 2 * (s + exl) + (ms || 0) + l;
if (!--lft)
cbf();
}
};
if (s > 65535)
cbl(err(11, 0, 1), null);
if (!compression)
cbl(null, file2);
else if (size < 160000) {
try {
cbl(null, deflateSync(file2, p));
} catch (e) {
cbl(e, null);
}
} else
term.push(deflate(file2, p, cbl));
};
for (var i3 = 0;i3 < slft; ++i3) {
_loop_1(i3);
}
return tAll;
}
function zipSync(data, opts) {
if (!opts)
opts = {};
var r = {};
var files = [];
fltn(data, "", r, opts);
var o2 = 0;
var tot = 0;
for (var fn in r) {
var _a3 = r[fn], file2 = _a3[0], p = _a3[1];
var compression = p.level == 0 ? 0 : 8;
var f = strToU8(fn), s = f.length;
var com = p.comment, m = com && strToU8(com), ms = m && m.length;
var exl = exfl(p.extra);
if (s > 65535)
err(11);
var d = compression ? deflateSync(file2, p) : file2, l = d.length;
var c7 = crc();
c7.p(file2);
files.push(mrg(p, {
size: file2.length,
crc: c7.d(),
c: d,
f,
m,
u: s != fn.length || m && com.length != ms,
o: o2,
compression
}));
o2 += 30 + s + exl + l;
tot += 76 + 2 * (s + exl) + (ms || 0) + l;
}
var out = new u8(tot + 22), oe = o2, cdl = tot - o2;
for (var i3 = 0;i3 < files.length; ++i3) {
var f = files[i3];
wzh(out, f.o, f, f.f, f.u, f.c.length);
var badd = 30 + f.f.length + exfl(f.extra);
out.set(f.c, f.o + badd);
wzh(out, o2, f, f.f, f.u, f.c.length, f.o, f.m), o2 += 16 + badd + (f.m ? f.m.length : 0);
}
wzf(out, o2, files.length, cdl, oe);
return out;
}
function unzip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != "function")
err(7);
var term = [];
var tAll = function() {
for (var i4 = 0;i4 < term.length; ++i4)
term[i4]();
};
var files = {};
var cbd = function(a2, b) {
mt(function() {
cb(a2, b);
});
};
mt(function() {
cbd = cb;
});
var e = data.length - 22;
for (;b4(data, e) != 101010256; --e) {
if (!e || data.length - e > 65558) {
cbd(err(13, 0, 1), null);
return tAll;
}
}
var lft = b2(data, e + 8);
if (lft) {
var c7 = lft;
var o2 = b4(data, e + 16);
var z2 = o2 == 4294967295 || c7 == 65535;
if (z2) {
var ze = b4(data, e - 12);
z2 = b4(data, ze) == 101075792;
if (z2) {
c7 = lft = b4(data, ze + 32);
o2 = b4(data, ze + 48);
}
}
var fltr = opts && opts.filter;
var _loop_3 = function(i4) {
var _a3 = zh(data, o2, z2), c_1 = _a3[0], sc = _a3[1], su = _a3[2], fn = _a3[3], no = _a3[4], off = _a3[5], b = slzh(data, off);
o2 = no;
var cbl = function(e2, d) {
if (e2) {
tAll();
cbd(e2, null);
} else {
if (d)
files[fn] = d;
if (!--lft)
cbd(null, files);
}
};
if (!fltr || fltr({
name: fn,
size: sc,
originalSize: su,
compression: c_1
})) {
if (!c_1)
cbl(null, slc(data, b, b + sc));
else if (c_1 == 8) {
var infl = data.subarray(b, b + sc);
if (su < 524288 || sc > 0.8 * su) {
try {
cbl(null, inflateSync(infl, { out: new u8(su) }));
} catch (e2) {
cbl(e2, null);
}
} else
term.push(inflate(infl, { size: su }, cbl));
} else
cbl(err(14, "unknown compression type " + c_1, 1), null);
} else
cbl(null, null);
};
for (var i3 = 0;i3 < c7; ++i3) {
_loop_3(i3);
}
} else
cbd(null, {});
return tAll;
}
function unzipSync(data, opts) {
var files = {};
var e = data.length - 22;
for (;b4(data, e) != 101010256; --e) {
if (!e || data.length - e > 65558)
err(13);
}
var c7 = b2(data, e + 8);
if (!c7)
return {};
var o2 = b4(data, e + 16);
var z2 = o2 == 4294967295 || c7 == 65535;
if (z2) {
var ze = b4(data, e - 12);
z2 = b4(data, ze) == 101075792;
if (z2) {
c7 = b4(data, ze + 32);
o2 = b4(data, ze + 48);
}
}
var fltr = opts && opts.filter;
for (var i3 = 0;i3 < c7; ++i3) {
var _a3 = zh(data, o2, z2), c_2 = _a3[0], sc = _a3[1], su = _a3[2], fn = _a3[3], no = _a3[4], off = _a3[5], b = slzh(data, off);
o2 = no;
if (!fltr || fltr({
name: fn,
size: sc,
originalSize: su,
compression: c_2
})) {
if (!c_2)
files[fn] = slc(data, b, b + sc);
else if (c_2 == 8)
files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
else
err(14, "unknown compression type " + c_2);
}
}
return files;
}
var require2, Worker, workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global", wk, u8, u16, i32, fleb, fdeb, clim, freb = function(eb, start) {
var b = new u16(31);
for (var i2 = 0;i2 < 31; ++i2) {
b[i2] = start += 1 << eb[i2 - 1];
}
var r = new i32(b[30]);
for (var i2 = 1;i2 < 30; ++i2) {
for (var j = b[i2];j < b[i2 + 1]; ++j) {
r[j] = j - b[i2] << 5 | i2;
}
}
return { b, r };
}, _a2, fl, revfl, _b, fd, revfd, rev, x2, i2, hMap = function(cd, mb, r) {
var s = cd.length;
var i3 = 0;
var l = new u16(mb);
for (;i3 < s; ++i3) {
if (cd[i3])
++l[cd[i3] - 1];
}
var le = new u16(mb);
for (i3 = 1;i3 < mb; ++i3) {
le[i3] = le[i3 - 1] + l[i3 - 1] << 1;
}
var co;
if (r) {
co = new u16(1 << mb);
var rvb = 15 - mb;
for (i3 = 0;i3 < s; ++i3) {
if (cd[i3]) {
var sv = i3 << 4 | cd[i3];
var r_1 = mb - cd[i3];
var v = le[cd[i3] - 1]++ << r_1;
for (var m = v | (1 << r_1) - 1;v <= m; ++v) {
co[rev[v] >> rvb] = sv;
}
}
}
} else {
co = new u16(s);
for (i3 = 0;i3 < s; ++i3) {
if (cd[i3]) {
co[i3] = rev[le[cd[i3] - 1]++] >> 15 - cd[i3];
}
}
}
return co;
}, flt, i2, i2, i2, i2, fdt, i2, flm, flrm, fdm, fdrm, max = function(a2) {
var m = a2[0];
for (var i3 = 1;i3 < a2.length; ++i3) {
if (a2[i3] > m)
m = a2[i3];
}
return m;
}, bits = function(d, p, m) {
var o2 = p / 8 | 0;
return (d[o2] | d[o2 + 1] << 8) >> (p & 7) & m;
}, bits16 = function(d, p) {
var o2 = p / 8 | 0;
return (d[o2] | d[o2 + 1] << 8 | d[o2 + 2] << 16) >> (p & 7);
}, shft = function(p) {
return (p + 7) / 8 | 0;
}, slc = function(v, s, e) {
if (s == null || s < 0)
s = 0;
if (e == null || e > v.length)
e = v.length;
return new u8(v.subarray(s, e));
}, FlateErrorCode, ec, err = function(ind, msg, nt) {
var e = new Error(msg || ec[ind]);
e.code = ind;
if (Error.captureStackTrace)
Error.captureStackTrace(e, err);
if (!nt)
throw e;
return e;
}, inflt = function(dat, st, buf, dict) {
var sl = dat.length, dl = dict ? dict.length : 0;
if (!sl || st.f && !st.l)
return buf || new u8(0);
var noBuf = !buf;
var resize = noBuf || st.i != 2;
var noSt = st.i;
if (noBuf)
buf = new u8(sl * 3);
var cbuf = function(l2) {
var bl = buf.length;
if (l2 > bl) {
var nbuf = new u8(Math.max(bl * 2, l2));
nbuf.set(buf);
buf = nbuf;
}
};
var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
var tbts = sl * 8;
do {
if (!lm) {
final = bits(dat, pos, 1);
var type = bits(dat, pos + 1, 3);
pos += 3;
if (!type) {
var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
if (t > sl) {
if (noSt)
err(0);
break;
}
if (resize)
cbuf(bt + l);
buf.set(dat.subarray(s, t), bt);
st.b = bt += l, st.p = pos = t * 8, st.f = final;
continue;
} else if (type == 1)
lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
else if (type == 2) {
var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
var tl = hLit + bits(dat, pos + 5, 31) + 1;
pos += 14;
var ldt = new u8(tl);
var clt = new u8(19);
for (var i3 = 0;i3 < hcLen; ++i3) {
clt[clim[i3]] = bits(dat, pos + i3 * 3, 7);
}
pos += hcLen * 3;
var clb = max(clt), clbmsk = (1 << clb) - 1;
var clm = hMap(clt, clb, 1);
for (var i3 = 0;i3 < tl; ) {
var r = clm[bits(dat, pos, clbmsk)];
pos += r & 15;
var s = r >> 4;
if (s < 16) {
ldt[i3++] = s;
} else {
var c7 = 0, n2 = 0;
if (s == 16)
n2 = 3 + bits(dat, pos, 3), pos += 2, c7 = ldt[i3 - 1];
else if (s == 17)
n2 = 3 + bits(dat, pos, 7), pos += 3;
else if (s == 18)
n2 = 11 + bits(dat, pos, 127), pos += 7;
while (n2--)
ldt[i3++] = c7;
}
}
var lt2 = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
lbt = max(lt2);
dbt = max(dt);
lm = hMap(lt2, lbt, 1);
dm = hMap(dt, dbt, 1);
} else
err(1);
if (pos > tbts) {
if (noSt)
err(0);
break;
}
}
if (resize)
cbuf(bt + 131072);
var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
var lpos = pos;
for (;; lpos = pos) {
var c7 = lm[bits16(dat, pos) & lms], sym = c7 >> 4;
pos += c7 & 15;
if (pos > tbts) {
if (noSt)
err(0);
break;
}
if (!c7)
err(2);
if (sym < 256)
buf[bt++] = sym;
else if (sym == 256) {
lpos = pos, lm = null;
break;
} else {
var add = sym - 254;
if (sym > 264) {
var i3 = sym - 257, b = fleb[i3];
add = bits(dat, pos, (1 << b) - 1) + fl[i3];
pos += b;
}
var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
if (!d)
err(3);
pos += d & 15;
var dt = fd[dsym];
if (dsym > 3) {
var b = fdeb[dsym];
dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
}
if (pos > tbts) {
if (noSt)
err(0);
break;
}
if (resize)
cbuf(bt + 131072);
var end = bt + add;
if (bt < dt) {
var shift = dl - dt, dend = Math.min(dt, end);
if (shift + bt < 0)
err(3);
for (;bt < dend; ++bt)
buf[bt] = dict[shift + bt];
}
for (;bt < end; ++bt)
buf[bt] = buf[bt - dt];
}
}
st.l = lm, st.p = lpos, st.b = bt, st.f = final;
if (lm)
final = 1, st.m = lbt, st.d = dm, st.n = dbt;
} while (!final);
return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
}, wbits = function(d, p, v) {
v <<= p & 7;
var o2 = p / 8 | 0;
d[o2] |= v;
d[o2 + 1] |= v >> 8;
}, wbits16 = function(d, p, v) {
v <<= p & 7;
var o2 = p / 8 | 0;
d[o2] |= v;
d[o2 + 1] |= v >> 8;
d[o2 + 2] |= v >> 16;
}, hTree = function(d, mb) {
var t = [];
for (var i3 = 0;i3 < d.length; ++i3) {
if (d[i3])
t.push({ s: i3, f: d[i3] });
}
var s = t.length;
var t2 = t.slice();
if (!s)
return { t: et, l: 0 };
if (s == 1) {
var v = new u8(t[0].s + 1);
v[t[0].s] = 1;
return { t: v, l: 1 };
}
t.sort(function(a2, b) {
return a2.f - b.f;
});
t.push({ s: -1, f: 25001 });
var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
t[0] = { s: -1, f: l.f + r.f, l, r };
while (i1 != s - 1) {
l = t[t[i0].f < t[i22].f ? i0++ : i22++];
r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
t[i1++] = { s: -1, f: l.f + r.f, l, r };
}
var maxSym = t2[0].s;
for (var i3 = 1;i3 < s; ++i3) {
if (t2[i3].s > maxSym)
maxSym = t2[i3].s;
}
var tr = new u16(maxSym + 1);
var mbt = ln(t[i1 - 1], tr, 0);
if (mbt > mb) {
var i3 = 0, dt = 0;
var lft = mbt - mb, cst = 1 << lft;
t2.sort(function(a2, b) {
return tr[b.s] - tr[a2.s] || a2.f - b.f;
});
for (;i3 < s; ++i3) {
var i2_1 = t2[i3].s;
if (tr[i2_1] > mb) {
dt += cst - (1 << mbt - tr[i2_1]);
tr[i2_1] = mb;
} else
break;
}
dt >>= lft;
while (dt > 0) {
var i2_2 = t2[i3].s;
if (tr[i2_2] < mb)
dt -= 1 << mb - tr[i2_2]++ - 1;
else
++i3;
}
for (;i3 >= 0 && dt; --i3) {
var i2_3 = t2[i3].s;
if (tr[i2_3] == mb) {
--tr[i2_3];
++dt;
}
}
mbt = mb;
}
return { t: new u8(tr), l: mbt };
}, ln = function(n2, l, d) {
return n2.s == -1 ? Math.max(ln(n2.l, l, d + 1), ln(n2.r, l, d + 1)) : l[n2.s] = d;
}, lc = function(c7) {
var s = c7.length;
while (s && !c7[--s])
;
var cl = new u16(++s);
var cli = 0, cln = c7[0], cls = 1;
var w = function(v) {
cl[cli++] = v;
};
for (var i3 = 1;i3 <= s; ++i3) {
if (c7[i3] == cln && i3 != s)
++cls;
else {
if (!cln && cls > 2) {
for (;cls > 138; cls -= 138)
w(32754);
if (cls > 2) {
w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
cls = 0;
}
} else if (cls > 3) {
w(cln), --cls;
for (;cls > 6; cls -= 6)
w(8304);
if (cls > 2)
w(cls - 3 << 5 | 8208), cls = 0;
}
while (cls--)
w(cln);
cls = 1;
cln = c7[i3];
}
}
return { c: cl.subarray(0, cli), n: s };
}, clen = function(cf, cl) {
var l = 0;
for (var i3 = 0;i3 < cl.length; ++i3)
l += cf[i3] * cl[i3];
return l;
}, wfblk = function(out, pos, dat) {
var s = dat.length;
var o2 = shft(pos + 2);
out[o2] = s & 255;
out[o2 + 1] = s >> 8;
out[o2 + 2] = out[o2] ^ 255;
out[o2 + 3] = out[o2 + 1] ^ 255;
for (var i3 = 0;i3 < s; ++i3)
out[o2 + i3 + 4] = dat[i3];
return (o2 + 4 + s) * 8;
}, wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
wbits(out, p++, final);
++lf[256];
var _a3 = hTree(lf, 15), dlt = _a3.t, mlb = _a3.l;
var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
var lcfreq = new u16(19);
for (var i3 = 0;i3 < lclt.length; ++i3)
++lcfreq[lclt[i3] & 31];
for (var i3 = 0;i3 < lcdt.length; ++i3)
++lcfreq[lcdt[i3] & 31];
var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
var nlcc = 19;
for (;nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
;
var flen = bl + 5 << 3;
var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
if (bs >= 0 && flen <= ftlen && flen <= dtlen)
return wfblk(out, p, dat.subarray(bs, bs + bl));
var lm, ll, dm, dl;
wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
if (dtlen < ftlen) {
lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
var llm = hMap(lct, mlcb, 0);
wbits(out, p, nlc - 257);
wbits(out, p + 5, ndc - 1);
wbits(out, p + 10, nlcc - 4);
p += 14;
for (var i3 = 0;i3 < nlcc; ++i3)
wbits(out, p + 3 * i3, lct[clim[i3]]);
p += 3 * nlcc;
var lcts = [lclt, lcdt];
for (var it = 0;it < 2; ++it) {
var clct = lcts[it];
for (var i3 = 0;i3 < clct.length; ++i3) {
var len = clct[i3] & 31;
wbits(out, p, llm[len]), p += lct[len];
if (len > 15)
wbits(out, p, clct[i3] >> 5 & 127), p += clct[i3] >> 12;
}
}
} else {
lm = flm, ll = flt, dm = fdm, dl = fdt;
}
for (var i3 = 0;i3 < li; ++i3) {
var sym = syms[i3];
if (sym > 255) {
var len = sym >> 18 & 31;
wbits16(out, p, lm[len + 257]), p += ll[len + 257];
if (len > 7)
wbits(out, p, sym >> 23 & 31), p += fleb[len];
var dst = sym & 31;
wbits16(out, p, dm[dst]), p += dl[dst];
if (dst > 3)
wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
} else {
wbits16(out, p, lm[sym]), p += ll[sym];
}
}
wbits16(out, p, lm[256]);
return p + ll[256];
}, deo, et, dflt = function(dat, lvl, plvl, pre, post, st) {
var s = st.z || dat.length;
var o2 = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
var w = o2.subarray(pre, o2.length - post);
var lst = st.l;
var pos = (st.r || 0) & 7;
if (lvl) {
if (pos)
w[0] = st.r >> 3;
var opt = deo[lvl - 1];
var n2 = opt >> 13, c7 = opt & 8191;
var msk_1 = (1 << plvl) - 1;
var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
var hsh = function(i4) {
return (dat[i4] ^ dat[i4 + 1] << bs1_1 ^ dat[i4 + 2] << bs2_1) & msk_1;
};
var syms = new i32(25000);
var lf = new u16(288), df = new u16(32);
var lc_1 = 0, eb = 0, i3 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
for (;i3 + 2 < s; ++i3) {
var hv = hsh(i3);
var imod = i3 & 32767, pimod = head[hv];
prev[imod] = pimod;
head[hv] = imod;
if (wi <= i3) {
var rem = s - i3;
if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i3 - bs, pos);
li = lc_1 = eb = 0, bs = i3;
for (var j = 0;j < 286; ++j)
lf[j] = 0;
for (var j = 0;j < 30; ++j)
df[j] = 0;
}
var l = 2, d = 0, ch_1 = c7, dif = imod - pimod & 32767;
if (rem > 2 && hv == hsh(i3 - dif)) {
var maxn = Math.min(n2, rem) - 1;
var maxd = Math.min(32767, i3);
var ml = Math.min(258, rem);
while (dif <= maxd && --ch_1 && imod != pimod) {
if (dat[i3 + l] == dat[i3 + l - dif]) {
var nl = 0;
for (;nl < ml && dat[i3 + nl] == dat[i3 + nl - dif]; ++nl)
;
if (nl > l) {
l = nl, d = dif;
if (nl > maxn)
break;
var mmd = Math.min(dif, nl - 2);
var md = 0;
for (var j = 0;j < mmd; ++j) {
var ti = i3 - dif + j & 32767;
var pti = prev[ti];
var cd = ti - pti & 32767;
if (cd > md)
md = cd, pimod = ti;
}
}
}
imod = pimod, pimod = prev[imod];
dif += imod - pimod & 32767;
}
}
if (d) {
syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
var lin = revfl[l] & 31, din = revfd[d] & 31;
eb += fleb[lin] + fdeb[din];
++lf[257 + lin];
++df[din];
wi = i3 + l;
++lc_1;
} else {
syms[li++] = dat[i3];
++lf[dat[i3]];
}
}
}
for (i3 = Math.max(i3, wi);i3 < s; ++i3) {
syms[li++] = dat[i3];
++lf[dat[i3]];
}
pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i3 - bs, pos);
if (!lst) {
st.r = pos & 7 | w[pos / 8 | 0] << 3;
pos -= 7;
st.h = head, st.p = prev, st.i = i3, st.w = wi;
}
} else {
for (var i3 = st.w || 0;i3 < s + lst; i3 += 65535) {
var e = i3 + 65535;
if (e >= s) {
w[pos / 8 | 0] = lst;
e = s;
}
pos = wfblk(w, pos + 1, dat.subarray(i3, e));
}
st.i = s;
}
return slc(o2, 0, pre + shft(pos) + post);
}, crct, crc = function() {
var c7 = -1;
return {
p: function(d) {
var cr = c7;
for (var i3 = 0;i3 < d.length; ++i3)
cr = crct[cr & 255 ^ d[i3]] ^ cr >>> 8;
c7 = cr;
},
d: function() {
return ~c7;
}
};
}, adler = function() {
var a2 = 1, b = 0;
return {
p: function(d) {
var n2 = a2, m = b;
var l = d.length | 0;
for (var i3 = 0;i3 != l; ) {
var e = Math.min(i3 + 2655, l);
for (;i3 < e; ++i3)
m += n2 += d[i3];
n2 = (n2 & 65535) + 15 * (n2 >> 16), m = (m & 65535) + 15 * (m >> 16);
}
a2 = n2, b = m;
},
d: function() {
a2 %= 65521, b %= 65521;
return (a2 & 255) << 24 | (a2 & 65280) << 8 | (b & 255) << 8 | b >> 8;
}
};
}, dopt = function(dat, opt, pre, post, st) {
if (!st) {
st = { l: 1 };
if (opt.dictionary) {
var dict = opt.dictionary.subarray(-32768);
var newDat = new u8(dict.length + dat.length);
newDat.set(dict);
newDat.set(dat, dict.length);
dat = newDat;
st.w = dict.length;
}
}
return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
}, mrg = function(a2, b) {
var o2 = {};
for (var k in a2)
o2[k] = a2[k];
for (var k in b)
o2[k] = b[k];
return o2;
}, wcln = function(fn, fnStr, td) {
var dt = fn();
var st = fn.toString();
var ks = st.slice(st.indexOf("[") + 1, st.lastIndexOf("]")).replace(/\s+/g, "").split(",");
for (var i3 = 0;i3 < dt.length; ++i3) {
var v = dt[i3], k = ks[i3];
if (typeof v == "function") {
fnStr += ";" + k + "=";
var st_1 = v.toString();
if (v.prototype) {
if (st_1.indexOf("[native code]") != -1) {
var spInd = st_1.indexOf(" ", 8) + 1;
fnStr += st_1.slice(spInd, st_1.indexOf("(", spInd));
} else {
fnStr += st_1;
for (var t in v.prototype)
fnStr += ";" + k + ".prototype." + t + "=" + v.prototype[t].toString();
}
} else
fnStr += st_1;
} else
td[k] = v;
}
return fnStr;
}, ch, cbfs = function(v) {
var tl = [];
for (var k in v) {
if (v[k].buffer) {
tl.push((v[k] = new v[k].constructor(v[k])).buffer);
}
}
return tl;
}, wrkr = function(fns, init, id, cb) {
if (!ch[id]) {
var fnStr = "", td_1 = {}, m = fns.length - 1;
for (var i3 = 0;i3 < m; ++i3)
fnStr = wcln(fns[i3], fnStr, td_1);
ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };
}
var td = mrg({}, ch[id].e);
return wk(ch[id].c + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + init.toString() + "}", id, td, cbfs(td), cb);
}, bInflt = function() {
return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt];
}, bDflt = function() {
return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf];
}, gze = function() {
return [gzh, gzhl, wbytes, crc, crct];
}, guze = function() {
return [gzs, gzl];
}, zle = function() {
return [zlh, wbytes, adler];
}, zule = function() {
return [zls];
}, pbf = function(msg) {
return postMessage(msg, [msg.buffer]);
}, gopt = function(o2) {
return o2 && {
out: o2.size && new u8(o2.size),
dictionary: o2.dictionary
};
}, cbify = function(dat, opts, fns, init, id, cb) {
var w = wrkr(fns, init, id, function(err2, dat2) {
w.terminate();
cb(err2, dat2);
});
w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
return function() {
w.terminate();
};
}, astrm = function(strm) {
strm.ondata = function(dat, final) {
return postMessage([dat, final], [dat.buffer]);
};
return function(ev) {
if (ev.data.length) {
strm.push(ev.data[0], ev.data[1]);
postMessage([ev.data[0].length]);
} else
strm.flush();
};
}, astrmify = function(fns, strm, opts, init, id, flush, ext) {
var t;
var w = wrkr(fns, init, id, function(err2, dat) {
if (err2)
w.terminate(), strm.ondata.call(strm, err2);
else if (!Array.isArray(dat))
ext(dat);
else if (dat.length == 1) {
strm.queuedSize -= dat[0];
if (strm.ondrain)
strm.ondrain(dat[0]);
} else {
if (dat[1])
w.terminate();
strm.ondata.call(strm, err2, dat[0], dat[1]);
}
});
w.postMessage(opts);
strm.queuedSize = 0;
strm.push = function(d, f) {
if (!strm.ondata)
err(5);
if (t)
strm.ondata(err(4, 0, 1), null, !!f);
strm.queuedSize += d.length;
w.postMessage([d, t = f], [d.buffer]);
};
strm.terminate = function() {
w.terminate();
};
if (flush) {
strm.flush = function() {
w.postMessage([]);
};
}
}, b2 = function(d, b) {
return d[b] | d[b + 1] << 8;
}, b4 = function(d, b) {
return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
}, b8 = function(d, b) {
return b4(d, b) + b4(d, b + 4) * 4294967296;
}, wbytes = function(d, b, v) {
for (;v; ++b)
d[b] = v, v >>>= 8;
}, gzh = function(c7, o2) {
var fn = o2.filename;
c7[0] = 31, c7[1] = 139, c7[2] = 8, c7[8] = o2.level < 2 ? 4 : o2.level == 9 ? 2 : 0, c7[9] = 3;
if (o2.mtime != 0)
wbytes(c7, 4, Math.floor(new Date(o2.mtime || Date.now()) / 1000));
if (fn) {
c7[3] = 8;
for (var i3 = 0;i3 <= fn.length; ++i3)
c7[i3 + 10] = fn.charCodeAt(i3);
}
}, gzs = function(d) {
if (d[0] != 31 || d[1] != 139 || d[2] != 8)
err(6, "invalid gzip data");
var flg = d[3];
var st = 10;
if (flg & 4)
st += (d[10] | d[11] << 8) + 2;
for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1);zs > 0; zs -= !d[st++])
;
return st + (flg & 2);
}, gzl = function(d) {
var l = d.length;
return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
}, gzhl = function(o2) {
return 10 + (o2.filename ? o2.filename.length + 1 : 0);
}, zlh = function(c7, o2) {
var lv = o2.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
c7[0] = 120, c7[1] = fl2 << 6 | (o2.dictionary && 32);
c7[1] |= 31 - (c7[0] << 8 | c7[1]) % 31;
if (o2.dictionary) {
var h2 = adler();
h2.p(o2.dictionary);
wbytes(c7, 2, h2.d());
}
}, zls = function(d, dict) {
if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31)
err(6, "invalid zlib data");
if ((d[1] >> 5 & 1) == +!dict)
err(6, "invalid zlib data: " + (d[1] & 32 ? "need" : "unexpected") + " dictionary");
return (d[1] >> 3 & 4) + 2;
}, Deflate, AsyncDeflate, Inflate, AsyncInflate, Gzip, AsyncGzip, Gunzip, AsyncGunzip, Zlib, AsyncZlib, Unzlib, AsyncUnzlib, Decompress, AsyncDecompress, fltn = function(d, p, t, o2) {
for (var k in d) {
var val = d[k], n2 = p + k, op = o2;
if (Array.isArray(val))
op = mrg(o2, val[1]), val = val[0];
if (val instanceof u8)
t[n2] = [val, op];
else {
t[n2 += "/"] = [new u8(0), op];
fltn(val, n2, t, o2);
}
}
}, te, td, tds = 0, dutf8 = function(d) {
for (var r = "", i3 = 0;; ) {
var c7 = d[i3++];
var eb = (c7 > 127) + (c7 > 223) + (c7 > 239);
if (i3 + eb > d.length)
return { s: r, r: slc(d, i3 - 1) };
if (!eb)
r += String.fromCharCode(c7);
else if (eb == 3) {
c7 = ((c7 & 15) << 18 | (d[i3++] & 63) << 12 | (d[i3++] & 63) << 6 | d[i3++] & 63) - 65536, r += String.fromCharCode(55296 | c7 >> 10, 56320 | c7 & 1023);
} else if (eb & 1)
r += String.fromCharCode((c7 & 31) << 6 | d[i3++] & 63);
else
r += String.fromCharCode((c7 & 15) << 12 | (d[i3++] & 63) << 6 | d[i3++] & 63);
}
}, DecodeUTF8, EncodeUTF8, dbf = function(l) {
return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0;
}, slzh = function(d, b) {
return b + 30 + b2(d, b + 26) + b2(d, b + 28);
}, zh = function(d, b, z2) {
var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
var _a3 = z2 && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a3[0], su = _a3[1], off = _a3[2];
return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
}, z64e = function(d, b) {
for (;b2(d, b) != 1; b += 4 + b2(d, b + 2))
;
return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
}, exfl = function(ex) {
var le = 0;
if (ex) {
for (var k in ex) {
var l = ex[k].length;
if (l > 65535)
err(9);
le += l + 4;
}
}
return le;
}, wzh = function(d, b, f, fn, u2, c7, ce, co) {
var fl2 = fn.length, ex = f.extra, col = co && co.length;
var exl = exfl(ex);
wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
if (ce != null)
d[b++] = 20, d[b++] = f.os;
d[b] = 20, b += 2;
d[b++] = f.flag << 1 | (c7 < 0 && 8), d[b++] = u2 && 8;
d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y2 = dt.getFullYear() - 1980;
if (y2 < 0 || y2 > 119)
err(10);
wbytes(d, b, y2 << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
if (c7 != -1) {
wbytes(d, b, f.crc);
wbytes(d, b + 4, c7 < 0 ? -c7 - 2 : c7);
wbytes(d, b + 8, f.size);
}
wbytes(d, b + 12, fl2);
wbytes(d, b + 14, exl), b += 16;
if (ce != null) {
wbytes(d, b, col);
wbytes(d, b + 6, f.attrs);
wbytes(d, b + 10, ce), b += 14;
}
d.set(fn, b);
b += fl2;
if (exl) {
for (var k in ex) {
var exf = ex[k], l = exf.length;
wbytes(d, b, +k);
wbytes(d, b + 2, l);
d.set(exf, b + 4), b += 4 + l;
}
}
if (col)
d.set(co, b), b += col;
return b;
}, wzf = function(o2, b, c7, d, e) {
wbytes(o2, b, 101010256);
wbytes(o2, b + 8, c7);
wbytes(o2, b + 10, c7);
wbytes(o2, b + 12, d);
wbytes(o2, b + 16, e);
}, ZipPassThrough, ZipDeflate, AsyncZipDeflate, Zip, UnzipPassThrough, UnzipInflate, AsyncUnzipInflate, Unzip, mt;
var init_esm4 = __esm(() => {
require2 = createRequire2("/");
try {
Worker = require2("worker_threads").Worker;
} catch (e) {}
wk = Worker ? function(c7, _, msg, transfer, cb) {
var done = false;
var w = new Worker(c7 + workerAdd, { eval: true }).on("error", function(e) {
return cb(e, null);
}).on("message", function(m) {
return cb(null, m);
}).on("exit", function(c8) {
if (c8 && !done)
cb(new Error("exited with code " + c8), null);
});
w.postMessage(msg, transfer);
w.terminate = function() {
done = true;
return Worker.prototype.terminate.call(w);
};
return w;
} : function(_, __, ___, ____, cb) {
setImmediate(function() {
return cb(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"), null);
});
var NOP = function() {};
return {
terminate: NOP,
postMessage: NOP
};
};
u8 = Uint8Array;
u16 = Uint16Array;
i32 = Int32Array;
fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0]);
fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0]);
clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
_a2 = freb(fleb, 2);
fl = _a2.b;
revfl = _a2.r;
fl[28] = 258, revfl[258] = 28;
_b = freb(fdeb, 0);
fd = _b.b;
revfd = _b.r;
rev = new u16(32768);
for (i2 = 0;i2 < 32768; ++i2) {
x2 = (i2 & 43690) >> 1 | (i2 & 21845) << 1;
x2 = (x2 & 52428) >> 2 | (x2 & 13107) << 2;
x2 = (x2 & 61680) >> 4 | (x2 & 3855) << 4;
rev[i2] = ((x2 & 65280) >> 8 | (x2 & 255) << 8) >> 1;
}
flt = new u8(288);
for (i2 = 0;i2 < 144; ++i2)
flt[i2] = 8;
for (i2 = 144;i2 < 256; ++i2)
flt[i2] = 9;
for (i2 = 256;i2 < 280; ++i2)
flt[i2] = 7;
for (i2 = 280;i2 < 288; ++i2)
flt[i2] = 8;
fdt = new u8(32);
for (i2 = 0;i2 < 32; ++i2)
fdt[i2] = 5;
flm = /* @__PURE__ */ hMap(flt, 9, 0);
flrm = /* @__PURE__ */ hMap(flt, 9, 1);
fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
FlateErrorCode = {
UnexpectedEOF: 0,
InvalidBlockType: 1,
InvalidLengthLiteral: 2,
InvalidDistance: 3,
StreamFinished: 4,
NoStreamHandler: 5,
InvalidHeader: 6,
NoCallback: 7,
InvalidUTF8: 8,
ExtraFieldTooLong: 9,
InvalidDate: 10,
FilenameTooLong: 11,
StreamFinishing: 12,
InvalidZipData: 13,
UnknownCompressionMethod: 14
};
ec = [
"unexpected EOF",
"invalid block type",
"invalid length/literal",
"invalid distance",
"stream finished",
"no stream handler",
,
"no callback",
"invalid UTF-8 data",
"extra field too long",
"date not in range 1980-2099",
"filename too long",
"stream finishing",
"invalid zip data"
];
deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
et = /* @__PURE__ */ new u8(0);
crct = /* @__PURE__ */ function() {
var t = new Int32Array(256);
for (var i3 = 0;i3 < 256; ++i3) {
var c7 = i3, k = 9;
while (--k)
c7 = (c7 & 1 && -306674912) ^ c7 >>> 1;
t[i3] = c7;
}
return t;
}();
ch = [];
Deflate = /* @__PURE__ */ function() {
function Deflate2(opts, cb) {
if (typeof opts == "function")
cb = opts, opts = {};
this.ondata = cb;
this.o = opts || {};
this.s = { l: 0, i: 32768, w: 32768, z: 32768 };
this.b = new u8(98304);
if (this.o.dictionary) {
var dict = this.o.dictionary.subarray(-32768);
this.b.set(dict, 32768 - dict.length);
this.s.i = 32768 - dict.length;
}
}
Deflate2.prototype.p = function(c7, f) {
this.ondata(dopt(c7, this.o, 0, 0, this.s), f);
};
Deflate2.prototype.push = function(chunk, final) {
if (!this.ondata)
err(5);
if (this.s.l)
err(4);
var endLen = chunk.length + this.s.z;
if (endLen > this.b.length) {
if (endLen > 2 * this.b.length - 32768) {
var newBuf = new u8(endLen & -32768);
newBuf.set(this.b.subarray(0, this.s.z));
this.b = newBuf;
}
var split = this.b.length - this.s.z;
this.b.set(chunk.subarray(0, split), this.s.z);
this.s.z = this.b.length;
this.p(this.b, false);
this.b.set(this.b.subarray(-32768));
this.b.set(chunk.subarray(split), 32768);
this.s.z = chunk.length - split + 32768;
this.s.i = 32766, this.s.w = 32768;
} else {
this.b.set(chunk, this.s.z);
this.s.z += chunk.length;
}
this.s.l = final & 1;
if (this.s.z > this.s.w + 8191 || final) {
this.p(this.b, final || false);
this.s.w = this.s.i, this.s.i -= 2;
}
};
Deflate2.prototype.flush = function() {
if (!this.ondata)
err(5);
if (this.s.l)
err(4);
this.p(this.b, false);
this.s.w = this.s.i, this.s.i -= 2;
};
return Deflate2;
}();
AsyncDeflate = /* @__PURE__ */ function() {
function AsyncDeflate2(opts, cb) {
astrmify([
bDflt,
function() {
return [astrm, Deflate];
}
], this, StrmOpt.call(this, opts, cb), function(ev) {
var strm = new Deflate(ev.data);
onmessage = astrm(strm);
}, 6, 1);
}
return AsyncDeflate2;
}();
Inflate = /* @__PURE__ */ function() {
function Inflate2(opts, cb) {
if (typeof opts == "function")
cb = opts, opts = {};
this.ondata = cb;
var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
this.s = { i: 0, b: dict ? dict.length : 0 };
this.o = new u8(32768);
this.p = new u8(0);
if (dict)
this.o.set(dict);
}
Inflate2.prototype.e = function(c7) {
if (!this.ondata)
err(5);
if (this.d)
err(4);
if (!this.p.length)
this.p = c7;
else if (c7.length) {
var n2 = new u8(this.p.length + c7.length);
n2.set(this.p), n2.set(c7, this.p.length), this.p = n2;
}
};
Inflate2.prototype.c = function(final) {
this.s.i = +(this.d = final || false);
var bts = this.s.b;
var dt = inflt(this.p, this.s, this.o);
this.ondata(slc(dt, bts, this.s.b), this.d);
this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7;
};
Inflate2.prototype.push = function(chunk, final) {
this.e(chunk), this.c(final);
};
return Inflate2;
}();
AsyncInflate = /* @__PURE__ */ function() {
function AsyncInflate2(opts, cb) {
astrmify([
bInflt,
function() {
return [astrm, Inflate];
}
], this, StrmOpt.call(this, opts, cb), function(ev) {
var strm = new Inflate(ev.data);
onmessage = astrm(strm);
}, 7, 0);
}
return AsyncInflate2;
}();
Gzip = /* @__PURE__ */ function() {
function Gzip2(opts, cb) {
this.c = crc();
this.l = 0;
this.v = 1;
Deflate.call(this, opts, cb);
}
Gzip2.prototype.push = function(chunk, final) {
this.c.p(chunk);
this.l += chunk.length;
Deflate.prototype.push.call(this, chunk, final);
};
Gzip2.prototype.p = function(c7, f) {
var raw = dopt(c7, this.o, this.v && gzhl(this.o), f && 8, this.s);
if (this.v)
gzh(raw, this.o), this.v = 0;
if (f)
wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
this.ondata(raw, f);
};
Gzip2.prototype.flush = function() {
Deflate.prototype.flush.call(this);
};
return Gzip2;
}();
AsyncGzip = /* @__PURE__ */ function() {
function AsyncGzip2(opts, cb) {
astrmify([
bDflt,
gze,
function() {
return [astrm, Deflate, Gzip];
}
], this, StrmOpt.call(this, opts, cb), function(ev) {
var strm = new Gzip(ev.data);
onmessage = astrm(strm);
}, 8, 1);
}
return AsyncGzip2;
}();
Gunzip = /* @__PURE__ */ function() {
function Gunzip2(opts, cb) {
this.v = 1;
this.r = 0;
Inflate.call(this, opts, cb);
}
Gunzip2.prototype.push = function(chunk, final) {
Inflate.prototype.e.call(this, chunk);
this.r += chunk.length;
if (this.v) {
var p = this.p.subarray(this.v - 1);
var s = p.length > 3 ? gzs(p) : 4;
if (s > p.length) {
if (!final)
return;
} else if (this.v > 1 && this.onmember) {
this.onmember(this.r - p.length);
}
this.p = p.subarray(s), this.v = 0;
}
Inflate.prototype.c.call(this, final);
if (this.s.f && !this.s.l && !final) {
this.v = shft(this.s.p) + 9;
this.s = { i: 0 };
this.o = new u8(0);
this.push(new u8(0), final);
}
};
return Gunzip2;
}();
AsyncGunzip = /* @__PURE__ */ function() {
function AsyncGunzip2(opts, cb) {
var _this = this;
astrmify([
bInflt,
guze,
function() {
return [astrm, Inflate, Gunzip];
}
], this, StrmOpt.call(this, opts, cb), function(ev) {
var strm = new Gunzip(ev.data);
strm.onmember = function(offset) {
return postMessage(offset);
};
onmessage = astrm(strm);
}, 9, 0, function(offset) {
return _this.onmember && _this.onmember(offset);
});
}
return AsyncGunzip2;
}();
Zlib = /* @__PURE__ */ function() {
function Zlib2(opts, cb) {
this.c = adler();
this.v = 1;
Deflate.call(this, opts, cb);
}
Zlib2.prototype.push = function(chunk, final) {
this.c.p(chunk);
Deflate.prototype.push.call(this, chunk, final);
};
Zlib2.prototype.p = function(c7, f) {
var raw = dopt(c7, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);
if (this.v)
zlh(raw, this.o), this.v = 0;
if (f)
wbytes(raw, raw.length - 4, this.c.d());
this.ondata(raw, f);
};
Zlib2.prototype.flush = function() {
Deflate.prototype.flush.call(this);
};
return Zlib2;
}();
AsyncZlib = /* @__PURE__ */ function() {
function AsyncZlib2(opts, cb) {
astrmify([
bDflt,
zle,
function() {
return [astrm, Deflate, Zlib];
}
], this, StrmOpt.call(this, opts, cb), function(ev) {
var strm = new Zlib(ev.data);
onmessage = astrm(strm);
}, 10, 1);
}
return AsyncZlib2;
}();
Unzlib = /* @__PURE__ */ function() {
function Unzlib2(opts, cb) {
Inflate.call(this, opts, cb);
this.v = opts && opts.dictionary ? 2 : 1;
}
Unzlib2.prototype.push = function(chunk, final) {
Inflate.prototype.e.call(this, chunk);
if (this.v) {
if (this.p.length < 6 && !final)
return;
this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
}
if (final) {
if (this.p.length < 4)
err(6, "invalid zlib data");
this.p = this.p.subarray(0, -4);
}
Inflate.prototype.c.call(this, final);
};
return Unzlib2;
}();
AsyncUnzlib = /* @__PURE__ */ function() {
function AsyncUnzlib2(opts, cb) {
astrmify([
bInflt,
zule,
function() {
return [astrm, Inflate, Unzlib];
}
], this, StrmOpt.call(this, opts, cb), function(ev) {
var strm = new Unzlib(ev.data);
onmessage = astrm(strm);
}, 11, 0);
}
return AsyncUnzlib2;
}();
Decompress = /* @__PURE__ */ function() {
function Decompress2(opts, cb) {
this.o = StrmOpt.call(this, opts, cb) || {};
this.G = Gunzip;
this.I = Inflate;
this.Z = Unzlib;
}
Decompress2.prototype.i = function() {
var _this = this;
this.s.ondata = function(dat, final) {
_this.ondata(dat, final);
};
};
Decompress2.prototype.push = function(chunk, final) {
if (!this.ondata)
err(5);
if (!this.s) {
if (this.p && this.p.length) {
var n2 = new u8(this.p.length + chunk.length);
n2.set(this.p), n2.set(chunk, this.p.length);
} else
this.p = chunk;
if (this.p.length > 2) {
this.s = this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8 ? new this.G(this.o) : (this.p[0] & 15) != 8 || this.p[0] >> 4 > 7 || (this.p[0] << 8 | this.p[1]) % 31 ? new this.I(this.o) : new this.Z(this.o);
this.i();
this.s.push(this.p, final);
this.p = null;
}
} else
this.s.push(chunk, final);
};
return Decompress2;
}();
AsyncDecompress = /* @__PURE__ */ function() {
function AsyncDecompress2(opts, cb) {
Decompress.call(this, opts, cb);
this.queuedSize = 0;
this.G = AsyncGunzip;
this.I = AsyncInflate;
this.Z = AsyncUnzlib;
}
AsyncDecompress2.prototype.i = function() {
var _this = this;
this.s.ondata = function(err2, dat, final) {
_this.ondata(err2, dat, final);
};
this.s.ondrain = function(size) {
_this.queuedSize -= size;
if (_this.ondrain)
_this.ondrain(size);
};
};
AsyncDecompress2.prototype.push = function(chunk, final) {
this.queuedSize += chunk.length;
Decompress.prototype.push.call(this, chunk, final);
};
return AsyncDecompress2;
}();
te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder;
td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder;
try {
td.decode(et, { stream: true });
tds = 1;
} catch (e) {}
DecodeUTF8 = /* @__PURE__ */ function() {
function DecodeUTF82(cb) {
this.ondata = cb;
if (tds)
this.t = new TextDecoder;
else
this.p = et;
}
DecodeUTF82.prototype.push = function(chunk, final) {
if (!this.ondata)
err(5);
final = !!final;
if (this.t) {
this.ondata(this.t.decode(chunk, { stream: true }), final);
if (final) {
if (this.t.decode().length)
err(8);
this.t = null;
}
return;
}
if (!this.p)
err(4);
var dat = new u8(this.p.length + chunk.length);
dat.set(this.p);
dat.set(chunk, this.p.length);
var _a3 = dutf8(dat), s = _a3.s, r = _a3.r;
if (final) {
if (r.length)
err(8);
this.p = null;
} else
this.p = r;
this.ondata(s, final);
};
return DecodeUTF82;
}();
EncodeUTF8 = /* @__PURE__ */ function() {
function EncodeUTF82(cb) {
this.ondata = cb;
}
EncodeUTF82.prototype.push = function(chunk, final) {
if (!this.ondata)
err(5);
if (this.d)
err(4);
this.ondata(strToU8(chunk), this.d = final || false);
};
return EncodeUTF82;
}();
ZipPassThrough = /* @__PURE__ */ function() {
function ZipPassThrough2(filename) {
this.filename = filename;
this.c = crc();
this.size = 0;
this.compression = 0;
}
ZipPassThrough2.prototype.process = function(chunk, final) {
this.ondata(null, chunk, final);
};
ZipPassThrough2.prototype.push = function(chunk, final) {
if (!this.ondata)
err(5);
this.c.p(chunk);
this.size += chunk.length;
if (final)
this.crc = this.c.d();
this.process(chunk, final || false);
};
return ZipPassThrough2;
}();
ZipDeflate = /* @__PURE__ */ function() {
function ZipDeflate2(filename, opts) {
var _this = this;
if (!opts)
opts = {};
ZipPassThrough.call(this, filename);
this.d = new Deflate(opts, function(dat, final) {
_this.ondata(null, dat, final);
});
this.compression = 8;
this.flag = dbf(opts.level);
}
ZipDeflate2.prototype.process = function(chunk, final) {
try {
this.d.push(chunk, final);
} catch (e) {
this.ondata(e, null, final);
}
};
ZipDeflate2.prototype.push = function(chunk, final) {
ZipPassThrough.prototype.push.call(this, chunk, final);
};
return ZipDeflate2;
}();
AsyncZipDeflate = /* @__PURE__ */ function() {
function AsyncZipDeflate2(filename, opts) {
var _this = this;
if (!opts)
opts = {};
ZipPassThrough.call(this, filename);
this.d = new AsyncDeflate(opts, function(err2, dat, final) {
_this.ondata(err2, dat, final);
});
this.compression = 8;
this.flag = dbf(opts.level);
this.terminate = this.d.terminate;
}
AsyncZipDeflate2.prototype.process = function(chunk, final) {
this.d.push(chunk, final);
};
AsyncZipDeflate2.prototype.push = function(chunk, final) {
ZipPassThrough.prototype.push.call(this, chunk, final);
};
return AsyncZipDeflate2;
}();
Zip = /* @__PURE__ */ function() {
function Zip2(cb) {
this.ondata = cb;
this.u = [];
this.d = 1;
}
Zip2.prototype.add = function(file2) {
var _this = this;
if (!this.ondata)
err(5);
if (this.d & 2)
this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
else {
var f = strToU8(file2.filename), fl_1 = f.length;
var com = file2.comment, o2 = com && strToU8(com);
var u2 = fl_1 != file2.filename.length || o2 && com.length != o2.length;
var hl_1 = fl_1 + exfl(file2.extra) + 30;
if (fl_1 > 65535)
this.ondata(err(11, 0, 1), null, false);
var header = new u8(hl_1);
wzh(header, 0, file2, f, u2, -1);
var chks_1 = [header];
var pAll_1 = function() {
for (var _i = 0, chks_2 = chks_1;_i < chks_2.length; _i++) {
var chk = chks_2[_i];
_this.ondata(null, chk, false);
}
chks_1 = [];
};
var tr_1 = this.d;
this.d = 0;
var ind_1 = this.u.length;
var uf_1 = mrg(file2, {
f,
u: u2,
o: o2,
t: function() {
if (file2.terminate)
file2.terminate();
},
r: function() {
pAll_1();
if (tr_1) {
var nxt = _this.u[ind_1 + 1];
if (nxt)
nxt.r();
else
_this.d = 1;
}
tr_1 = 1;
}
});
var cl_1 = 0;
file2.ondata = function(err2, dat, final) {
if (err2) {
_this.ondata(err2, dat, final);
_this.terminate();
} else {
cl_1 += dat.length;
chks_1.push(dat);
if (final) {
var dd = new u8(16);
wbytes(dd, 0, 134695760);
wbytes(dd, 4, file2.crc);
wbytes(dd, 8, cl_1);
wbytes(dd, 12, file2.size);
chks_1.push(dd);
uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file2.crc, uf_1.size = file2.size;
if (tr_1)
uf_1.r();
tr_1 = 1;
} else if (tr_1)
pAll_1();
}
};
this.u.push(uf_1);
}
};
Zip2.prototype.end = function() {
var _this = this;
if (this.d & 2) {
this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
return;
}
if (this.d)
this.e();
else
this.u.push({
r: function() {
if (!(_this.d & 1))
return;
_this.u.splice(-1, 1);
_this.e();
},
t: function() {}
});
this.d = 3;
};
Zip2.prototype.e = function() {
var bt = 0, l = 0, tl = 0;
for (var _i = 0, _a3 = this.u;_i < _a3.length; _i++) {
var f = _a3[_i];
tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
}
var out = new u8(tl + 22);
for (var _b2 = 0, _c = this.u;_b2 < _c.length; _b2++) {
var f = _c[_b2];
wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);
bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
}
wzf(out, bt, this.u.length, tl, l);
this.ondata(null, out, true);
this.d = 2;
};
Zip2.prototype.terminate = function() {
for (var _i = 0, _a3 = this.u;_i < _a3.length; _i++) {
var f = _a3[_i];
f.t();
}
this.d = 2;
};
return Zip2;
}();
UnzipPassThrough = /* @__PURE__ */ function() {
function UnzipPassThrough2() {}
UnzipPassThrough2.prototype.push = function(data, final) {
this.ondata(null, data, final);
};
UnzipPassThrough2.compression = 0;
return UnzipPassThrough2;
}();
UnzipInflate = /* @__PURE__ */ function() {
function UnzipInflate2() {
var _this = this;
this.i = new Inflate(function(dat, final) {
_this.ondata(null, dat, final);
});
}
UnzipInflate2.prototype.push = function(data, final) {
try {
this.i.push(data, final);
} catch (e) {
this.ondata(e, null, final);
}
};
UnzipInflate2.compression = 8;
return UnzipInflate2;
}();
AsyncUnzipInflate = /* @__PURE__ */ function() {
function AsyncUnzipInflate2(_, sz) {
var _this = this;
if (sz < 320000) {
this.i = new Inflate(function(dat, final) {
_this.ondata(null, dat, final);
});
} else {
this.i = new AsyncInflate(function(err2, dat, final) {
_this.ondata(err2, dat, final);
});
this.terminate = this.i.terminate;
}
}
AsyncUnzipInflate2.prototype.push = function(data, final) {
if (this.i.terminate)
data = slc(data, 0);
this.i.push(data, final);
};
AsyncUnzipInflate2.compression = 8;
return AsyncUnzipInflate2;
}();
Unzip = /* @__PURE__ */ function() {
function Unzip2(cb) {
this.onfile = cb;
this.k = [];
this.o = {
0: UnzipPassThrough
};
this.p = et;
}
Unzip2.prototype.push = function(chunk, final) {
var _this = this;
if (!this.onfile)
err(5);
if (!this.p)
err(4);
if (this.c > 0) {
var len = Math.min(this.c, chunk.length);
var toAdd = chunk.subarray(0, len);
this.c -= len;
if (this.d)
this.d.push(toAdd, !this.c);
else
this.k[0].push(toAdd);
chunk = chunk.subarray(len);
if (chunk.length)
return this.push(chunk, final);
} else {
var f = 0, i3 = 0, is = undefined, buf = undefined;
if (!this.p.length)
buf = chunk;
else if (!chunk.length)
buf = this.p;
else {
buf = new u8(this.p.length + chunk.length);
buf.set(this.p), buf.set(chunk, this.p.length);
}
var l = buf.length, oc = this.c, add = oc && this.d;
var _loop_2 = function() {
var _a3;
var sig = b4(buf, i3);
if (sig == 67324752) {
f = 1, is = i3;
this_1.d = null;
this_1.c = 0;
var bf = b2(buf, i3 + 6), cmp_1 = b2(buf, i3 + 8), u2 = bf & 2048, dd = bf & 8, fnl = b2(buf, i3 + 26), es = b2(buf, i3 + 28);
if (l > i3 + 30 + fnl + es) {
var chks_3 = [];
this_1.k.unshift(chks_3);
f = 2;
var sc_1 = b4(buf, i3 + 18), su_1 = b4(buf, i3 + 22);
var fn_1 = strFromU8(buf.subarray(i3 + 30, i3 += 30 + fnl), !u2);
if (sc_1 == 4294967295) {
_a3 = dd ? [-2] : z64e(buf, i3), sc_1 = _a3[0], su_1 = _a3[1];
} else if (dd)
sc_1 = -1;
i3 += es;
this_1.c = sc_1;
var d_1;
var file_1 = {
name: fn_1,
compression: cmp_1,
start: function() {
if (!file_1.ondata)
err(5);
if (!sc_1)
file_1.ondata(null, et, true);
else {
var ctr = _this.o[cmp_1];
if (!ctr)
file_1.ondata(err(14, "unknown compression type " + cmp_1, 1), null, false);
d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
d_1.ondata = function(err2, dat3, final2) {
file_1.ondata(err2, dat3, final2);
};
for (var _i = 0, chks_4 = chks_3;_i < chks_4.length; _i++) {
var dat2 = chks_4[_i];
d_1.push(dat2, false);
}
if (_this.k[0] == chks_3 && _this.c)
_this.d = d_1;
else
d_1.push(et, true);
}
},
terminate: function() {
if (d_1 && d_1.terminate)
d_1.terminate();
}
};
if (sc_1 >= 0)
file_1.size = sc_1, file_1.originalSize = su_1;
this_1.onfile(file_1);
}
return "break";
} else if (oc) {
if (sig == 134695760) {
is = i3 += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
return "break";
} else if (sig == 33639248) {
is = i3 -= 4, f = 3, this_1.c = 0;
return "break";
}
}
};
var this_1 = this;
for (;i3 < l - 4; ++i3) {
var state_1 = _loop_2();
if (state_1 === "break")
break;
}
this.p = et;
if (oc < 0) {
var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 134695760 && 4)) : buf.subarray(0, i3);
if (add)
add.push(dat, !!f);
else
this.k[+(f == 2)].push(dat);
}
if (f & 2)
return this.push(buf.subarray(i3), final);
this.p = buf.subarray(i3);
}
if (final) {
if (this.c)
err(13);
this.p = null;
}
};
Unzip2.prototype.register = function(decoder) {
this.o[decoder.compression] = decoder;
};
return Unzip2;
}();
mt = typeof queueMicrotask == "function" ? queueMicrotask : typeof setTimeout == "function" ? setTimeout : function(fn) {
fn();
};
});
// src/utils/dxt/zip.ts
import { isAbsolute as isAbsolute7, normalize as normalize6 } from "path";
function isPathSafe(filePath) {
if (containsPathTraversal(filePath)) {
return false;
}
const normalized = normalize6(filePath);
if (isAbsolute7(normalized)) {
return false;
}
return true;
}
function validateZipFile(file2, state) {
state.fileCount++;
let error44;
if (state.fileCount > LIMITS.MAX_FILE_COUNT) {
error44 = `Archive contains too many files: ${state.fileCount} (max: ${LIMITS.MAX_FILE_COUNT})`;
}
if (!isPathSafe(file2.name)) {
error44 = `Unsafe file path detected: "${file2.name}". Path traversal or absolute paths are not allowed.`;
}
const fileSize = file2.originalSize || 0;
if (fileSize > LIMITS.MAX_FILE_SIZE) {
error44 = `File "${file2.name}" is too large: ${Math.round(fileSize / 1024 / 1024)}MB (max: ${Math.round(LIMITS.MAX_FILE_SIZE / 1024 / 1024)}MB)`;
}
state.totalUncompressedSize += fileSize;
if (state.totalUncompressedSize > LIMITS.MAX_TOTAL_SIZE) {
error44 = `Archive total size is too large: ${Math.round(state.totalUncompressedSize / 1024 / 1024)}MB (max: ${Math.round(LIMITS.MAX_TOTAL_SIZE / 1024 / 1024)}MB)`;
}
const currentRatio = state.totalUncompressedSize / state.compressedSize;
if (currentRatio > LIMITS.MAX_COMPRESSION_RATIO) {
error44 = `Suspicious compression ratio detected: ${currentRatio.toFixed(1)}:1 (max: ${LIMITS.MAX_COMPRESSION_RATIO}:1). This may be a zip bomb.`;
}
return error44 ? { isValid: false, error: error44 } : { isValid: true };
}
async function unzipFile(zipData) {
const { unzipSync: unzipSync2 } = await Promise.resolve().then(() => (init_esm4(), exports_esm));
const compressedSize = zipData.length;
const state = {
fileCount: 0,
totalUncompressedSize: 0,
compressedSize,
errors: []
};
const result = unzipSync2(new Uint8Array(zipData), {
filter: (file2) => {
const validationResult = validateZipFile(file2, state);
if (!validationResult.isValid) {
throw new Error(validationResult.error);
}
return true;
}
});
logForDebugging(`Zip extraction completed: ${state.fileCount} files, ${Math.round(state.totalUncompressedSize / 1024)}KB uncompressed`);
return result;
}
function parseZipModes(data) {
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
const modes = {};
const minEocd = Math.max(0, buf.length - 22 - 65535);
let eocd = -1;
for (let i3 = buf.length - 22;i3 >= minEocd; i3--) {
if (buf.readUInt32LE(i3) === 101010256) {
eocd = i3;
break;
}
}
if (eocd < 0)
return modes;
const entryCount = buf.readUInt16LE(eocd + 10);
let off = buf.readUInt32LE(eocd + 16);
for (let i3 = 0;i3 < entryCount; i3++) {
if (off + 46 > buf.length || buf.readUInt32LE(off) !== 33639248)
break;
const versionMadeBy = buf.readUInt16LE(off + 4);
const nameLen = buf.readUInt16LE(off + 28);
const extraLen = buf.readUInt16LE(off + 30);
const commentLen = buf.readUInt16LE(off + 32);
const externalAttr = buf.readUInt32LE(off + 38);
const name = buf.toString("utf8", off + 46, off + 46 + nameLen);
if (versionMadeBy >> 8 === 3) {
const mode = externalAttr >>> 16 & 65535;
if (mode)
modes[name] = mode;
}
off += 46 + nameLen + extraLen + commentLen;
}
return modes;
}
var LIMITS;
var init_zip = __esm(() => {
init_debug();
init_errors();
init_fsOperations();
init_path2();
LIMITS = {
MAX_FILE_SIZE: 512 * 1024 * 1024,
MAX_TOTAL_SIZE: 1024 * 1024 * 1024,
MAX_FILE_COUNT: 1e5,
MAX_COMPRESSION_RATIO: 50,
MIN_COMPRESSION_RATIO: 0.5
};
});
// src/utils/systemDirectories.ts
import { homedir as homedir14 } from "os";
import { join as join32 } from "path";
function getSystemDirectories(options) {
const platform2 = options?.platform ?? getPlatform();
const homeDir = options?.homedir ?? homedir14();
const env5 = options?.env ?? process.env;
const defaults2 = {
HOME: homeDir,
DESKTOP: join32(homeDir, "Desktop"),
DOCUMENTS: join32(homeDir, "Documents"),
DOWNLOADS: join32(homeDir, "Downloads")
};
switch (platform2) {
case "windows": {
const userProfile = env5.USERPROFILE || homeDir;
return {
HOME: homeDir,
DESKTOP: join32(userProfile, "Desktop"),
DOCUMENTS: join32(userProfile, "Documents"),
DOWNLOADS: join32(userProfile, "Downloads")
};
}
case "linux":
case "wsl": {
return {
HOME: homeDir,
DESKTOP: env5.XDG_DESKTOP_DIR || defaults2.DESKTOP,
DOCUMENTS: env5.XDG_DOCUMENTS_DIR || defaults2.DOCUMENTS,
DOWNLOADS: env5.XDG_DOWNLOAD_DIR || defaults2.DOWNLOADS
};
}
case "macos":
default: {
if (platform2 === "unknown") {
logForDebugging(`Unknown platform detected, using default paths`);
}
return defaults2;
}
}
}
var init_systemDirectories = __esm(() => {
init_debug();
init_platform2();
});
// src/utils/plugins/mcpbHandler.ts
import { createHash as createHash4 } from "crypto";
import { chmod, writeFile as writeFile3 } from "fs/promises";
import { dirname as dirname18, join as join33 } from "path";
function isMcpbSource(source) {
return source.endsWith(".mcpb") || source.endsWith(".dxt");
}
function isUrl2(source) {
return source.startsWith("http://") || source.startsWith("https://");
}
function generateContentHash(data) {
return createHash4("sha256").update(data).digest("hex").substring(0, 16);
}
function getMcpbCacheDir(pluginPath) {
return join33(pluginPath, ".mcpb-cache");
}
function getMetadataPath(cacheDir, source) {
const sourceHash = createHash4("md5").update(source).digest("hex").substring(0, 8);
return join33(cacheDir, `${sourceHash}.metadata.json`);
}
function serverSecretsKey(pluginId, serverName) {
return `${pluginId}/${serverName}`;
}
function loadMcpServerUserConfig(pluginId, serverName) {
try {
const settings = getSettings_DEPRECATED();
const nonSensitive = settings.pluginConfigs?.[pluginId]?.mcpServers?.[serverName];
const sensitive = getSecureStorage().read()?.pluginSecrets?.[serverSecretsKey(pluginId, serverName)];
if (!nonSensitive && !sensitive) {
return null;
}
logForDebugging(`Loaded user config for ${pluginId}/${serverName} (settings + secureStorage)`);
return { ...nonSensitive, ...sensitive };
} catch (error44) {
const errorObj = toError(error44);
logError2(errorObj);
logForDebugging(`Failed to load user config for ${pluginId}/${serverName}: ${error44}`, { level: "error" });
return null;
}
}
function saveMcpServerUserConfig(pluginId, serverName, config2, schema) {
try {
const nonSensitive = {};
const sensitive = {};
for (const [key, value] of Object.entries(config2)) {
if (schema[key]?.sensitive === true) {
sensitive[key] = String(value);
} else {
nonSensitive[key] = value;
}
}
const sensitiveKeysInThisSave = new Set(Object.keys(sensitive));
const nonSensitiveKeysInThisSave = new Set(Object.keys(nonSensitive));
const storage = getSecureStorage();
const k = serverSecretsKey(pluginId, serverName);
const existingInSecureStorage = storage.read()?.pluginSecrets?.[k] ?? undefined;
const secureScrubbed = existingInSecureStorage ? Object.fromEntries(Object.entries(existingInSecureStorage).filter(([key]) => !nonSensitiveKeysInThisSave.has(key))) : undefined;
const needSecureScrub = secureScrubbed && existingInSecureStorage && Object.keys(secureScrubbed).length !== Object.keys(existingInSecureStorage).length;
if (Object.keys(sensitive).length > 0 || needSecureScrub) {
const existing = storage.read() ?? {};
if (!existing.pluginSecrets) {
existing.pluginSecrets = {};
}
existing.pluginSecrets[k] = {
...secureScrubbed,
...sensitive
};
const result = storage.update(existing);
if (!result.success) {
throw new Error(`Failed to save sensitive config to secure storage for ${k}`);
}
if (result.warning) {
logForDebugging(`Server secrets save warning: ${result.warning}`, {
level: "warn"
});
}
if (needSecureScrub) {
logForDebugging(`saveMcpServerUserConfig: scrubbed ${Object.keys(existingInSecureStorage).length - Object.keys(secureScrubbed).length} stale non-sensitive key(s) from secureStorage for ${k}`);
}
}
const settings = getSettings_DEPRECATED();
const existingInSettings = settings.pluginConfigs?.[pluginId]?.mcpServers?.[serverName] ?? {};
const keysToScrubFromSettings = Object.keys(existingInSettings).filter((k2) => sensitiveKeysInThisSave.has(k2));
if (Object.keys(nonSensitive).length > 0 || keysToScrubFromSettings.length > 0) {
if (!settings.pluginConfigs) {
settings.pluginConfigs = {};
}
if (!settings.pluginConfigs[pluginId]) {
settings.pluginConfigs[pluginId] = {};
}
if (!settings.pluginConfigs[pluginId].mcpServers) {
settings.pluginConfigs[pluginId].mcpServers = {};
}
const scrubbed = Object.fromEntries(keysToScrubFromSettings.map((k2) => [k2, undefined]));
settings.pluginConfigs[pluginId].mcpServers[serverName] = {
...nonSensitive,
...scrubbed
};
const result = updateSettingsForSource("userSettings", settings);
if (result.error) {
throw result.error;
}
if (keysToScrubFromSettings.length > 0) {
logForDebugging(`saveMcpServerUserConfig: scrubbed ${keysToScrubFromSettings.length} plaintext sensitive key(s) from settings.json for ${pluginId}/${serverName}`);
}
}
logForDebugging(`Saved user config for ${pluginId}/${serverName} (${Object.keys(nonSensitive).length} non-sensitive, ${Object.keys(sensitive).length} sensitive)`);
} catch (error44) {
const errorObj = toError(error44);
logError2(errorObj);
throw new Error(`Failed to save user configuration for ${pluginId}/${serverName}: ${errorObj.message}`);
}
}
function validateUserConfig(values2, schema) {
const errors3 = [];
for (const [key, fieldSchema] of Object.entries(schema)) {
const value = values2[key];
if (fieldSchema.required && (value === undefined || value === "")) {
errors3.push(`${fieldSchema.title || key} is required but not provided`);
continue;
}
if (value === undefined || value === "") {
continue;
}
if (fieldSchema.type === "string") {
if (Array.isArray(value)) {
if (!fieldSchema.multiple) {
errors3.push(`${fieldSchema.title || key} must be a string, not an array`);
} else if (!value.every((v) => typeof v === "string")) {
errors3.push(`${fieldSchema.title || key} must be an array of strings`);
}
} else if (typeof value !== "string") {
errors3.push(`${fieldSchema.title || key} must be a string`);
}
} else if (fieldSchema.type === "number" && typeof value !== "number") {
errors3.push(`${fieldSchema.title || key} must be a number`);
} else if (fieldSchema.type === "boolean" && typeof value !== "boolean") {
errors3.push(`${fieldSchema.title || key} must be a boolean`);
} else if ((fieldSchema.type === "file" || fieldSchema.type === "directory") && typeof value !== "string") {
errors3.push(`${fieldSchema.title || key} must be a path string`);
}
if (fieldSchema.type === "number" && typeof value === "number") {
if (fieldSchema.min !== undefined && value < fieldSchema.min) {
errors3.push(`${fieldSchema.title || key} must be at least ${fieldSchema.min}`);
}
if (fieldSchema.max !== undefined && value > fieldSchema.max) {
errors3.push(`${fieldSchema.title || key} must be at most ${fieldSchema.max}`);
}
}
}
return { valid: errors3.length === 0, errors: errors3 };
}
async function generateMcpConfig(manifest, extractedPath, userConfig = {}) {
const { getMcpConfigForManifest: getMcpConfigForManifest3 } = await Promise.resolve().then(() => (init_mcpb(), exports_mcpb));
const mcpConfig = await getMcpConfigForManifest3({
manifest,
extensionPath: extractedPath,
systemDirs: getSystemDirectories(),
userConfig,
pathSeparator: "/"
});
if (!mcpConfig) {
const error44 = new Error(`Failed to generate MCP server configuration from manifest "${manifest.name}"`);
logError2(error44);
throw error44;
}
return mcpConfig;
}
async function loadCacheMetadata(cacheDir, source) {
const fs2 = getFsImplementation();
const metadataPath = getMetadataPath(cacheDir, source);
try {
const content = await fs2.readFile(metadataPath, { encoding: "utf-8" });
return jsonParse(content);
} catch (error44) {
const code = getErrnoCode(error44);
if (code === "ENOENT")
return null;
const errorObj = toError(error44);
logError2(errorObj);
logForDebugging(`Failed to load MCPB cache metadata: ${error44}`, {
level: "error"
});
return null;
}
}
async function saveCacheMetadata(cacheDir, source, metadata) {
const metadataPath = getMetadataPath(cacheDir, source);
await getFsImplementation().mkdir(cacheDir);
await writeFile3(metadataPath, jsonStringify(metadata, null, 2), "utf-8");
}
async function downloadMcpb(url3, destPath, onProgress) {
logForDebugging(`Downloading MCPB from ${url3}`);
if (onProgress) {
onProgress(`Downloading ${url3}...`);
}
const started = performance.now();
let fetchTelemetryFired = false;
try {
const response = await axios_default.get(url3, {
timeout: 120000,
responseType: "arraybuffer",
maxRedirects: 5,
onDownloadProgress: (progressEvent) => {
if (progressEvent.total && onProgress) {
const percent = Math.round(progressEvent.loaded / progressEvent.total * 100);
onProgress(`Downloading... ${percent}%`);
}
}
});
const data = new Uint8Array(response.data);
logPluginFetch("mcpb", url3, "success", performance.now() - started);
fetchTelemetryFired = true;
await writeFile3(destPath, Buffer.from(data));
logForDebugging(`Downloaded ${data.length} bytes to ${destPath}`);
if (onProgress) {
onProgress("Download complete");
}
return data;
} catch (error44) {
if (!fetchTelemetryFired) {
logPluginFetch("mcpb", url3, "failure", performance.now() - started, classifyFetchError(error44));
}
const errorMsg = errorMessage(error44);
const fullError = new Error(`Failed to download MCPB file from ${url3}: ${errorMsg}`);
logError2(fullError);
throw fullError;
}
}
async function extractMcpbContents(unzipped, extractPath, modes, onProgress) {
if (onProgress) {
onProgress("Extracting files...");
}
await getFsImplementation().mkdir(extractPath);
let filesWritten = 0;
const entries = Object.entries(unzipped).filter(([k]) => !k.endsWith("/"));
const totalFiles = entries.length;
for (const [filePath, fileData] of entries) {
const fullPath = join33(extractPath, filePath);
const dir = dirname18(fullPath);
if (dir !== extractPath) {
await getFsImplementation().mkdir(dir);
}
const isTextFile = filePath.endsWith(".json") || filePath.endsWith(".js") || filePath.endsWith(".ts") || filePath.endsWith(".txt") || filePath.endsWith(".md") || filePath.endsWith(".yml") || filePath.endsWith(".yaml");
if (isTextFile) {
const content = new TextDecoder().decode(fileData);
await writeFile3(fullPath, content, "utf-8");
} else {
await writeFile3(fullPath, Buffer.from(fileData));
}
const mode = modes[filePath];
if (mode && mode & 73) {
await chmod(fullPath, mode & 511).catch(() => {});
}
filesWritten++;
if (onProgress && filesWritten % 10 === 0) {
onProgress(`Extracted ${filesWritten}/${totalFiles} files`);
}
}
logForDebugging(`Extracted ${filesWritten} files to ${extractPath}`);
if (onProgress) {
onProgress(`Extraction complete (${filesWritten} files)`);
}
}
async function checkMcpbChanged(source, pluginPath) {
const fs2 = getFsImplementation();
const cacheDir = getMcpbCacheDir(pluginPath);
const metadata = await loadCacheMetadata(cacheDir, source);
if (!metadata) {
return true;
}
try {
await fs2.stat(metadata.extractedPath);
} catch (error44) {
const code = getErrnoCode(error44);
if (code === "ENOENT") {
logForDebugging(`MCPB extraction path missing: ${metadata.extractedPath}`);
} else {
logForDebugging(`MCPB extraction path inaccessible: ${metadata.extractedPath}: ${error44}`, { level: "error" });
}
return true;
}
if (!isUrl2(source)) {
const localPath = join33(pluginPath, source);
let stats;
try {
stats = await fs2.stat(localPath);
} catch (error44) {
const code = getErrnoCode(error44);
if (code === "ENOENT") {
logForDebugging(`MCPB source file missing: ${localPath}`);
} else {
logForDebugging(`MCPB source file inaccessible: ${localPath}: ${error44}`, { level: "error" });
}
return true;
}
const cachedTime = new Date(metadata.cachedAt).getTime();
const fileTime = Math.floor(stats.mtimeMs);
if (fileTime > cachedTime) {
logForDebugging(`MCPB file modified: ${new Date(fileTime)} > ${new Date(cachedTime)}`);
return true;
}
}
return false;
}
async function loadMcpbFile(source, pluginPath, pluginId, onProgress, providedUserConfig, forceConfigDialog) {
const fs2 = getFsImplementation();
const cacheDir = getMcpbCacheDir(pluginPath);
await fs2.mkdir(cacheDir);
logForDebugging(`Loading MCPB from source: ${source}`);
const metadata = await loadCacheMetadata(cacheDir, source);
if (metadata && !await checkMcpbChanged(source, pluginPath)) {
logForDebugging(`Using cached MCPB from ${metadata.extractedPath} (hash: ${metadata.contentHash})`);
const manifestPath = join33(metadata.extractedPath, "manifest.json");
let manifestContent;
try {
manifestContent = await fs2.readFile(manifestPath, { encoding: "utf-8" });
} catch (error44) {
if (isENOENT(error44)) {
const err2 = new Error(`Cached manifest not found: ${manifestPath}`);
logError2(err2);
throw err2;
}
throw error44;
}
const manifestData2 = new TextEncoder().encode(manifestContent);
const manifest2 = await parseAndValidateManifestFromBytes(manifestData2);
if (manifest2.user_config && Object.keys(manifest2.user_config).length > 0) {
const serverName = manifest2.name;
const savedConfig = loadMcpServerUserConfig(pluginId, serverName);
const userConfig = providedUserConfig || savedConfig || {};
const validation = validateUserConfig(userConfig, manifest2.user_config);
if (forceConfigDialog || !validation.valid) {
return {
status: "needs-config",
manifest: manifest2,
extractedPath: metadata.extractedPath,
contentHash: metadata.contentHash,
configSchema: manifest2.user_config,
existingConfig: savedConfig || {},
validationErrors: validation.valid ? [] : validation.errors
};
}
if (providedUserConfig) {
saveMcpServerUserConfig(pluginId, serverName, providedUserConfig, manifest2.user_config ?? {});
}
const mcpConfig3 = await generateMcpConfig(manifest2, metadata.extractedPath, userConfig);
return {
manifest: manifest2,
mcpConfig: mcpConfig3,
extractedPath: metadata.extractedPath,
contentHash: metadata.contentHash
};
}
const mcpConfig2 = await generateMcpConfig(manifest2, metadata.extractedPath);
return {
manifest: manifest2,
mcpConfig: mcpConfig2,
extractedPath: metadata.extractedPath,
contentHash: metadata.contentHash
};
}
let mcpbData;
let mcpbFilePath;
if (isUrl2(source)) {
const sourceHash = createHash4("md5").update(source).digest("hex").substring(0, 8);
mcpbFilePath = join33(cacheDir, `${sourceHash}.mcpb`);
mcpbData = await downloadMcpb(source, mcpbFilePath, onProgress);
} else {
const localPath = join33(pluginPath, source);
if (onProgress) {
onProgress(`Loading ${source}...`);
}
try {
mcpbData = await fs2.readFileBytes(localPath);
mcpbFilePath = localPath;
} catch (error44) {
if (isENOENT(error44)) {
const err2 = new Error(`MCPB file not found: ${localPath}`);
logError2(err2);
throw err2;
}
throw error44;
}
}
const contentHash = generateContentHash(mcpbData);
logForDebugging(`MCPB content hash: ${contentHash}`);
if (onProgress) {
onProgress("Extracting MCPB archive...");
}
const unzipped = await unzipFile(Buffer.from(mcpbData));
const modes = parseZipModes(mcpbData);
const manifestData = unzipped["manifest.json"];
if (!manifestData) {
const error44 = new Error("No manifest.json found in MCPB file");
logError2(error44);
throw error44;
}
const manifest = await parseAndValidateManifestFromBytes(manifestData);
logForDebugging(`MCPB manifest: ${manifest.name} v${manifest.version} by ${manifest.author.name}`);
if (!manifest.server) {
const error44 = new Error(`MCPB manifest for "${manifest.name}" does not define a server configuration`);
logError2(error44);
throw error44;
}
const extractPath = join33(cacheDir, contentHash);
await extractMcpbContents(unzipped, extractPath, modes, onProgress);
if (manifest.user_config && Object.keys(manifest.user_config).length > 0) {
const serverName = manifest.name;
const savedConfig = loadMcpServerUserConfig(pluginId, serverName);
const userConfig = providedUserConfig || savedConfig || {};
const validation = validateUserConfig(userConfig, manifest.user_config);
if (!validation.valid) {
const newMetadata3 = {
source,
contentHash,
extractedPath: extractPath,
cachedAt: new Date().toISOString(),
lastChecked: new Date().toISOString()
};
await saveCacheMetadata(cacheDir, source, newMetadata3);
return {
status: "needs-config",
manifest,
extractedPath: extractPath,
contentHash,
configSchema: manifest.user_config,
existingConfig: savedConfig || {},
validationErrors: validation.errors
};
}
if (providedUserConfig) {
saveMcpServerUserConfig(pluginId, serverName, providedUserConfig, manifest.user_config ?? {});
}
if (onProgress) {
onProgress("Generating MCP server configuration...");
}
const mcpConfig2 = await generateMcpConfig(manifest, extractPath, userConfig);
const newMetadata2 = {
source,
contentHash,
extractedPath: extractPath,
cachedAt: new Date().toISOString(),
lastChecked: new Date().toISOString()
};
await saveCacheMetadata(cacheDir, source, newMetadata2);
return {
manifest,
mcpConfig: mcpConfig2,
extractedPath: extractPath,
contentHash
};
}
if (onProgress) {
onProgress("Generating MCP server configuration...");
}
const mcpConfig = await generateMcpConfig(manifest, extractPath);
const newMetadata = {
source,
contentHash,
extractedPath: extractPath,
cachedAt: new Date().toISOString(),
lastChecked: new Date().toISOString()
};
await saveCacheMetadata(cacheDir, source, newMetadata);
logForDebugging(`Successfully loaded MCPB: ${manifest.name} (extracted to ${extractPath})`);
return {
manifest,
mcpConfig,
extractedPath: extractPath,
contentHash
};
}
var init_mcpbHandler = __esm(() => {
init_axios2();
init_debug();
init_helpers();
init_zip();
init_errors();
init_fsOperations();
init_log3();
init_secureStorage();
init_settings2();
init_slowOperations();
init_systemDirectories();
init_fetchTelemetry();
});
// src/utils/plugins/pluginOptionsStorage.ts
function getPluginStorageId(plugin) {
return plugin.source;
}
function clearPluginOptionsCache() {
loadPluginOptions.cache?.clear?.();
}
function savePluginOptions(pluginId, values2, schema) {
const nonSensitive = {};
const sensitive = {};
for (const [key, value] of Object.entries(values2)) {
if (schema[key]?.sensitive === true) {
sensitive[key] = String(value);
} else {
nonSensitive[key] = value;
}
}
const sensitiveKeysInThisSave = new Set(Object.keys(sensitive));
const nonSensitiveKeysInThisSave = new Set(Object.keys(nonSensitive));
const storage = getSecureStorage();
const existingInSecureStorage = storage.read()?.pluginSecrets?.[pluginId] ?? undefined;
const secureScrubbed = existingInSecureStorage ? Object.fromEntries(Object.entries(existingInSecureStorage).filter(([k]) => !nonSensitiveKeysInThisSave.has(k))) : undefined;
const needSecureScrub = secureScrubbed && existingInSecureStorage && Object.keys(secureScrubbed).length !== Object.keys(existingInSecureStorage).length;
if (Object.keys(sensitive).length > 0 || needSecureScrub) {
const existing = storage.read() ?? {};
if (!existing.pluginSecrets) {
existing.pluginSecrets = {};
}
existing.pluginSecrets[pluginId] = {
...secureScrubbed,
...sensitive
};
const result = storage.update(existing);
if (!result.success) {
const err2 = new Error(`Failed to save sensitive plugin options for ${pluginId} to secure storage`);
logError2(err2);
throw err2;
}
if (result.warning) {
logForDebugging(`Plugin secrets save warning: ${result.warning}`, {
level: "warn"
});
}
}
const settings = getSettings_DEPRECATED();
const existingInSettings = settings.pluginConfigs?.[pluginId]?.options ?? {};
const keysToScrubFromSettings = Object.keys(existingInSettings).filter((k) => sensitiveKeysInThisSave.has(k));
if (Object.keys(nonSensitive).length > 0 || keysToScrubFromSettings.length > 0) {
if (!settings.pluginConfigs) {
settings.pluginConfigs = {};
}
if (!settings.pluginConfigs[pluginId]) {
settings.pluginConfigs[pluginId] = {};
}
const scrubbed = Object.fromEntries(keysToScrubFromSettings.map((k) => [k, undefined]));
settings.pluginConfigs[pluginId].options = {
...nonSensitive,
...scrubbed
};
const result = updateSettingsForSource("userSettings", settings);
if (result.error) {
logError2(result.error);
throw new Error(`Failed to save plugin options for ${pluginId}: ${result.error.message}`);
}
}
clearPluginOptionsCache();
}
function deletePluginOptions(pluginId) {
const settings = getSettings_DEPRECATED();
if (settings.pluginConfigs?.[pluginId]) {
const pluginConfigs = { [pluginId]: undefined };
const { error: error44 } = updateSettingsForSource("userSettings", {
pluginConfigs
});
if (error44) {
logForDebugging(`deletePluginOptions: failed to clear settings.pluginConfigs[${pluginId}]: ${error44.message}`, { level: "warn" });
}
}
const storage = getSecureStorage();
const existing = storage.read();
if (existing?.pluginSecrets) {
const prefix = `${pluginId}/`;
const survivingEntries = Object.entries(existing.pluginSecrets).filter(([k]) => k !== pluginId && !k.startsWith(prefix));
if (survivingEntries.length !== Object.keys(existing.pluginSecrets).length) {
const result = storage.update({
...existing,
pluginSecrets: survivingEntries.length > 0 ? Object.fromEntries(survivingEntries) : undefined
});
if (!result.success) {
logForDebugging(`deletePluginOptions: failed to clear pluginSecrets for ${pluginId} from keychain`, { level: "warn" });
}
}
}
clearPluginOptionsCache();
}
function getUnconfiguredOptions(plugin) {
const manifestSchema = plugin.manifest.userConfig;
if (!manifestSchema || Object.keys(manifestSchema).length === 0) {
return {};
}
const saved = loadPluginOptions(getPluginStorageId(plugin));
const validation = validateUserConfig(saved, manifestSchema);
if (validation.valid) {
return {};
}
const unconfigured = {};
for (const [key, fieldSchema] of Object.entries(manifestSchema)) {
const single = validateUserConfig({ [key]: saved[key] }, { [key]: fieldSchema });
if (!single.valid) {
unconfigured[key] = fieldSchema;
}
}
return unconfigured;
}
function substitutePluginVariables(value, plugin) {
const normalize7 = (p) => process.platform === "win32" ? p.replace(/\\/g, "/") : p;
let out = value.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => normalize7(plugin.path));
if (plugin.source) {
const source = plugin.source;
out = out.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g, () => normalize7(getPluginDataDir(source)));
}
return out;
}
function substituteUserConfigVariables(value, userConfig) {
return value.replace(/\$\{user_config\.([^}]+)\}/g, (_match, key) => {
const configValue = userConfig[key];
if (configValue === undefined) {
throw new Error(`Missing required user configuration value: ${key}. ` + `This should have been validated before variable substitution.`);
}
return String(configValue);
});
}
function substituteUserConfigInContent(content, options, schema) {
return content.replace(/\$\{user_config\.([^}]+)\}/g, (match, key) => {
if (schema[key]?.sensitive === true) {
return `[sensitive option '${key}' not available in skill content]`;
}
const value = options[key];
if (value === undefined) {
return match;
}
return String(value);
});
}
var loadPluginOptions;
var init_pluginOptionsStorage = __esm(() => {
init_memoize();
init_debug();
init_log3();
init_secureStorage();
init_settings2();
init_mcpbHandler();
init_pluginDirectories();
loadPluginOptions = memoize_default((pluginId) => {
const settings = getSettings_DEPRECATED();
const nonSensitive = settings.pluginConfigs?.[pluginId]?.options ?? {};
const storage = getSecureStorage();
const sensitive = storage.read()?.pluginSecrets?.[pluginId] ?? {};
return { ...nonSensitive, ...sensitive };
});
});
// src/utils/plugins/walkPluginMarkdown.ts
import { join as join34 } from "path";
async function walkPluginMarkdown(rootDir, onFile, opts = {}) {
const fs2 = getFsImplementation();
const label = opts.logLabel ?? "plugin";
async function scan(dirPath, namespace) {
try {
const entries = await fs2.readdir(dirPath);
if (opts.stopAtSkillDir && entries.some((e) => e.isFile() && SKILL_MD_RE.test(e.name))) {
await Promise.all(entries.map((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md") ? onFile(join34(dirPath, entry.name), namespace) : undefined));
return;
}
await Promise.all(entries.map((entry) => {
const fullPath = join34(dirPath, entry.name);
if (entry.isDirectory()) {
return scan(fullPath, [...namespace, entry.name]);
}
if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {
return onFile(fullPath, namespace);
}
return;
}));
} catch (error44) {
logForDebugging(`Failed to scan ${label} directory ${dirPath}: ${error44}`, { level: "error" });
}
}
await scan(rootDir, []);
}
var SKILL_MD_RE;
var init_walkPluginMarkdown = __esm(() => {
init_debug();
init_fsOperations();
SKILL_MD_RE = /^skill\.md$/i;
});
// src/utils/plugins/loadPluginAgents.ts
import { basename as basename7 } from "path";
async function loadAgentsFromDirectory(agentsPath, pluginName, sourceName, pluginPath, pluginManifest, loadedPaths) {
const agents = [];
await walkPluginMarkdown(agentsPath, async (fullPath, namespace) => {
const agent = await loadAgentFromFile(fullPath, pluginName, namespace, sourceName, pluginPath, pluginManifest, loadedPaths);
if (agent)
agents.push(agent);
}, { logLabel: "agents" });
return agents;
}
async function loadAgentFromFile(filePath, pluginName, namespace, sourceName, pluginPath, pluginManifest, loadedPaths) {
const fs2 = getFsImplementation();
if (isDuplicatePath(fs2, filePath, loadedPaths)) {
return null;
}
try {
const content = await fs2.readFile(filePath, { encoding: "utf-8" });
const { frontmatter, content: markdownContent } = parseFrontmatter(content, filePath);
const baseAgentName = frontmatter.name || basename7(filePath).replace(/\.md$/, "");
const nameParts = [pluginName, ...namespace, baseAgentName];
const agentType = nameParts.join(":");
const whenToUse = coerceDescriptionToString(frontmatter.description, agentType) ?? coerceDescriptionToString(frontmatter["when-to-use"], agentType) ?? `Agent from ${pluginName} plugin`;
let tools = parseAgentToolsFromFrontmatter(frontmatter.tools);
const skills = parseSlashCommandToolsFromFrontmatter(frontmatter.skills);
const color2 = frontmatter.color;
const modelRaw = frontmatter.model;
let model;
if (typeof modelRaw === "string" && modelRaw.trim().length > 0) {
const trimmed = modelRaw.trim();
model = trimmed.toLowerCase() === "inherit" ? "inherit" : trimmed;
}
const backgroundRaw = frontmatter.background;
const background = backgroundRaw === "true" || backgroundRaw === true ? true : undefined;
let systemPrompt = substitutePluginVariables(markdownContent.trim(), {
path: pluginPath,
source: sourceName
});
if (pluginManifest.userConfig) {
systemPrompt = substituteUserConfigInContent(systemPrompt, loadPluginOptions(sourceName), pluginManifest.userConfig);
}
const memoryRaw = frontmatter.memory;
let memory;
if (memoryRaw !== undefined) {
if (VALID_MEMORY_SCOPES.includes(memoryRaw)) {
memory = memoryRaw;
} else {
logForDebugging(`Plugin agent file ${filePath} has invalid memory value '${memoryRaw}'. Valid options: ${VALID_MEMORY_SCOPES.join(", ")}`);
}
}
const isolationRaw = frontmatter.isolation;
const isolation = isolationRaw === "worktree" ? "worktree" : undefined;
const effortRaw = frontmatter.effort;
const effort = effortRaw !== undefined ? parseEffortValue(effortRaw) : undefined;
if (effortRaw !== undefined && effort === undefined) {
logForDebugging(`Plugin agent file ${filePath} has invalid effort '${effortRaw}'. Valid options: ${EFFORT_LEVELS.join(", ")} or an integer`);
}
for (const field of ["permissionMode", "hooks", "mcpServers"]) {
if (frontmatter[field] !== undefined) {
logForDebugging(`Plugin agent file ${filePath} sets ${field}, which is ignored for plugin agents. Use .claude/agents/ for this level of control.`, { level: "warn" });
}
}
const maxTurnsRaw = frontmatter.maxTurns;
const maxTurns = parsePositiveIntFromFrontmatter(maxTurnsRaw);
if (maxTurnsRaw !== undefined && maxTurns === undefined) {
logForDebugging(`Plugin agent file ${filePath} has invalid maxTurns '${maxTurnsRaw}'. Must be a positive integer.`);
}
const disallowedTools = frontmatter.disallowedTools !== undefined ? parseAgentToolsFromFrontmatter(frontmatter.disallowedTools) : undefined;
if (isAutoMemoryEnabled() && memory && tools !== undefined) {
const toolSet = new Set(tools);
for (const tool of [
FILE_WRITE_TOOL_NAME,
FILE_EDIT_TOOL_NAME,
FILE_READ_TOOL_NAME
]) {
if (!toolSet.has(tool)) {
tools = [...tools, tool];
}
}
}
return {
agentType,
whenToUse,
tools,
...disallowedTools !== undefined ? { disallowedTools } : {},
...skills !== undefined ? { skills } : {},
getSystemPrompt: () => {
if (isAutoMemoryEnabled() && memory) {
const memoryPrompt = loadAgentMemoryPrompt(agentType, memory);
return systemPrompt + `
` + memoryPrompt;
}
return systemPrompt;
},
source: "plugin",
color: color2,
model,
filename: baseAgentName,
plugin: sourceName,
...background ? { background } : {},
...memory ? { memory } : {},
...isolation ? { isolation } : {},
...effort !== undefined ? { effort } : {},
...maxTurns !== undefined ? { maxTurns } : {}
};
} catch (error44) {
logForDebugging(`Failed to load agent from ${filePath}: ${error44}`, {
level: "error"
});
return null;
}
}
function clearPluginAgentCache() {
loadPluginAgents.cache?.clear?.();
}
var VALID_MEMORY_SCOPES, loadPluginAgents;
var init_loadPluginAgents = __esm(() => {
init_memoize();
init_paths();
init_agentMemory();
init_prompt2();
init_prompt3();
init_debug();
init_effort();
init_frontmatterParser();
init_fsOperations();
init_markdownConfigLoader();
init_pluginLoader();
init_pluginOptionsStorage();
init_walkPluginMarkdown();
VALID_MEMORY_SCOPES = ["user", "project", "local"];
loadPluginAgents = memoize_default(async () => {
const { enabled, errors: errors3 } = await loadAllPluginsCacheOnly();
if (errors3.length > 0) {
logForDebugging(`Plugin loading errors: ${errors3.map((e) => getPluginErrorMessage(e)).join(", ")}`);
}
const perPluginAgents = await Promise.all(enabled.map(async (plugin) => {
const loadedPaths = new Set;
const pluginAgents = [];
if (plugin.agentsPath) {
try {
const agents = await loadAgentsFromDirectory(plugin.agentsPath, plugin.name, plugin.source, plugin.path, plugin.manifest, loadedPaths);
pluginAgents.push(...agents);
if (agents.length > 0) {
logForDebugging(`Loaded ${agents.length} agents from plugin ${plugin.name} default directory`);
}
} catch (error44) {
logForDebugging(`Failed to load agents from plugin ${plugin.name} default directory: ${error44}`, { level: "error" });
}
}
if (plugin.agentsPaths) {
const pathResults = await Promise.all(plugin.agentsPaths.map(async (agentPath) => {
try {
const fs2 = getFsImplementation();
const stats = await fs2.stat(agentPath);
if (stats.isDirectory()) {
const agents = await loadAgentsFromDirectory(agentPath, plugin.name, plugin.source, plugin.path, plugin.manifest, loadedPaths);
if (agents.length > 0) {
logForDebugging(`Loaded ${agents.length} agents from plugin ${plugin.name} custom path: ${agentPath}`);
}
return agents;
} else if (stats.isFile() && agentPath.endsWith(".md")) {
const agent = await loadAgentFromFile(agentPath, plugin.name, [], plugin.source, plugin.path, plugin.manifest, loadedPaths);
if (agent) {
logForDebugging(`Loaded agent from plugin ${plugin.name} custom file: ${agentPath}`);
return [agent];
}
}
return [];
} catch (error44) {
logForDebugging(`Failed to load agents from plugin ${plugin.name} custom path ${agentPath}: ${error44}`, { level: "error" });
return [];
}
}));
for (const agents of pathResults) {
pluginAgents.push(...agents);
}
}
return pluginAgents;
}));
const allAgents = perPluginAgents.flat();
logForDebugging(`Total plugin agents loaded: ${allAgents.length}`);
return allAgents;
});
});
// src/tools/AgentTool/agentColorManager.ts
function getAgentColor(agentType) {
if (agentType === "general-purpose") {
return;
}
const agentColorMap = getAgentColorMap();
const existingColor = agentColorMap.get(agentType);
if (existingColor && AGENT_COLORS.includes(existingColor)) {
return AGENT_COLOR_TO_THEME_COLOR[existingColor];
}
return;
}
function setAgentColor(agentType, color2) {
const agentColorMap = getAgentColorMap();
if (!color2) {
agentColorMap.delete(agentType);
return;
}
if (AGENT_COLORS.includes(color2)) {
agentColorMap.set(agentType, color2);
}
}
var AGENT_COLORS, AGENT_COLOR_TO_THEME_COLOR;
var init_agentColorManager = __esm(() => {
init_state();
AGENT_COLORS = [
"red",
"blue",
"green",
"yellow",
"purple",
"orange",
"pink",
"cyan"
];
AGENT_COLOR_TO_THEME_COLOR = {
red: "red_FOR_SUBAGENTS_ONLY",
blue: "blue_FOR_SUBAGENTS_ONLY",
green: "green_FOR_SUBAGENTS_ONLY",
yellow: "yellow_FOR_SUBAGENTS_ONLY",
purple: "purple_FOR_SUBAGENTS_ONLY",
orange: "orange_FOR_SUBAGENTS_ONLY",
pink: "pink_FOR_SUBAGENTS_ONLY",
cyan: "cyan_FOR_SUBAGENTS_ONLY"
};
});
// src/tools/AgentTool/agentMemorySnapshot.ts
var snapshotMetaSchema, syncedMetaSchema;
var init_agentMemorySnapshot = __esm(() => {
init_v4();
init_cwd2();
init_debug();
init_slowOperations();
init_agentMemory();
snapshotMetaSchema = lazySchema(() => exports_external.object({
updatedAt: exports_external.string().min(1)
}));
syncedMetaSchema = lazySchema(() => exports_external.object({
syncedFrom: exports_external.string().min(1)
}));
});
// src/tools/SendMessageTool/constants.ts
var SEND_MESSAGE_TOOL_NAME = "SendMessage";
// src/constants/common.ts
function getLocalISODate() {
if (process.env.CLAUDE_CODE_OVERRIDE_DATE) {
return process.env.CLAUDE_CODE_OVERRIDE_DATE;
}
const now2 = new Date;
const year = now2.getFullYear();
const month = String(now2.getMonth() + 1).padStart(2, "0");
const day = String(now2.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
function getLocalMonthYear() {
const date5 = process.env.CLAUDE_CODE_OVERRIDE_DATE ? new Date(process.env.CLAUDE_CODE_OVERRIDE_DATE) : new Date;
return date5.toLocaleString("en-US", { month: "long", year: "numeric" });
}
var getSessionStartDate;
var init_common = __esm(() => {
init_memoize();
getSessionStartDate = memoize_default(getLocalISODate);
});
// src/tools/WebSearchTool/prompt.ts
function getWebSearchPrompt() {
const currentMonthYear = getLocalMonthYear();
return `
- Allows Claude to search the web and use the results to inform responses
- Provides up-to-date information for current events and recent data
- Returns search result information formatted as search result blocks, including links as markdown hyperlinks
- Use this tool for accessing information beyond Claude's knowledge cutoff
- Searches are performed automatically within a single API call
CRITICAL REQUIREMENT - You MUST follow this:
- After answering the user's question, you MUST include a "Sources:" section at the end of your response
- In the Sources section, list all relevant URLs from the search results as markdown hyperlinks: [Title](URL)
- This is MANDATORY - never skip including sources in your response
- Example format:
[Your answer here]
Sources:
- [Source Title 1](https://example.com/1)
- [Source Title 2](https://example.com/2)
Usage notes:
- Domain filtering is supported to include or block specific websites
- Web search is only available in the US
IMPORTANT - Use the correct year in search queries:
- The current month is ${currentMonthYear}. You MUST use this year when searching for recent information, documentation, or current events.
- Example: If the user asks for "latest React docs", search for "React documentation" with the current year, NOT last year
`;
}
var WEB_SEARCH_TOOL_NAME = "WebSearch";
var init_prompt5 = __esm(() => {
init_common();
});
// src/tools/AgentTool/built-in/claudeCodeGuideAgent.ts
function getClaudeCodeGuideBasePrompt() {
const localSearchHint = hasEmbeddedSearchTools() ? `${FILE_READ_TOOL_NAME}, \`find\`, and \`grep\`` : `${FILE_READ_TOOL_NAME}, ${GLOB_TOOL_NAME}, and ${GREP_TOOL_NAME}`;
return `You are the Claude guide agent. Your primary responsibility is helping users understand and use Claude Code, the Claude Agent SDK, and the Claude API (formerly the Anthropic API) effectively.
**Your expertise spans three domains:**
1. **Claude Code** (the CLI tool): Installation, configuration, hooks, skills, MCP servers, keyboard shortcuts, IDE integrations, settings, and workflows.
2. **Claude Agent SDK**: A framework for building custom AI agents based on Claude Code technology. Available for Node.js/TypeScript and Python.
3. **Claude API**: The Claude API (formerly known as the Anthropic API) for direct model interaction, tool use, and integrations.
**Documentation sources:**
- **Claude Code docs** (${CLAUDE_CODE_DOCS_MAP_URL}): Fetch this for questions about the Claude Code CLI tool, including:
- Installation, setup, and getting started
- Hooks (pre/post command execution)
- Custom skills
- MCP server configuration
- IDE integrations (VS Code, JetBrains)
- Settings files and configuration
- Keyboard shortcuts and hotkeys
- Subagents and plugins
- Sandboxing and security
- **Claude Agent SDK docs** (${CDP_DOCS_MAP_URL}): Fetch this for questions about building agents with the SDK, including:
- SDK overview and getting started (Python and TypeScript)
- Agent configuration + custom tools
- Session management and permissions
- MCP integration in agents
- Hosting and deployment
- Cost tracking and context management
Note: Agent SDK docs are part of the Claude API documentation at the same URL.
- **Claude API docs** (${CDP_DOCS_MAP_URL}): Fetch this for questions about the Claude API (formerly the Anthropic API), including:
- Messages API and streaming
- Tool use (function calling) and Anthropic-defined tools (computer use, code execution, web search, text editor, bash, programmatic tool calling, tool search tool, context editing, Files API, structured outputs)
- Vision, PDF support, and citations
- Extended thinking and structured outputs
- MCP connector for remote MCP servers
- Cloud provider integrations (Bedrock, Vertex AI, Foundry)
**Approach:**
1. Determine which domain the user's question falls into
2. Use ${WEB_FETCH_TOOL_NAME} to fetch the appropriate docs map
3. Identify the most relevant documentation URLs from the map
4. Fetch the specific documentation pages
5. Provide clear, actionable guidance based on official documentation
6. Use ${WEB_SEARCH_TOOL_NAME} if docs don't cover the topic
7. Reference local project files (CLAUDE.md, .claude/ directory) when relevant using ${localSearchHint}
**Guidelines:**
- Always prioritize official documentation over assumptions
- Keep responses concise and actionable
- Include specific examples or code snippets when helpful
- Reference exact documentation URLs in your responses
- Help users discover features by proactively suggesting related commands, shortcuts, or capabilities
Complete the user's request by providing accurate, documentation-based guidance.`;
}
function getFeedbackGuideline() {
if (isUsing3PServices()) {
return `- When you cannot find an answer or the feature doesn't exist, direct the user to ${"report the issue at https://github.com/x1xhlol/better-clawd/issues"}`;
}
return "- When you cannot find an answer or the feature doesn't exist, direct the user to use /feedback to report a feature request or bug";
}
var CLAUDE_CODE_DOCS_MAP_URL = "https://code.claude.com/docs/en/claude_code_docs_map.md", CDP_DOCS_MAP_URL = "https://platform.claude.com/llms.txt", CLAUDE_CODE_GUIDE_AGENT_TYPE = "claude-code-guide", CLAUDE_CODE_GUIDE_AGENT;
var init_claudeCodeGuideAgent = __esm(() => {
init_prompt2();
init_prompt();
init_prompt5();
init_auth2();
init_embeddedTools();
init_settings2();
init_slowOperations();
CLAUDE_CODE_GUIDE_AGENT = {
agentType: CLAUDE_CODE_GUIDE_AGENT_TYPE,
whenToUse: `Use this agent when the user asks questions ("Can Claude...", "Does Claude...", "How do I...") about: (1) Claude Code (the CLI tool) - features, hooks, slash commands, MCP servers, settings, IDE integrations, keyboard shortcuts; (2) Claude Agent SDK - building custom agents; (3) Claude API (formerly Anthropic API) - API usage, tool use, Anthropic SDK usage. **IMPORTANT:** Before spawning a new agent, check if there is already a running or recently completed claude-code-guide agent that you can continue via ${SEND_MESSAGE_TOOL_NAME}.`,
tools: hasEmbeddedSearchTools() ? [
BASH_TOOL_NAME,
FILE_READ_TOOL_NAME,
WEB_FETCH_TOOL_NAME,
WEB_SEARCH_TOOL_NAME
] : [
GLOB_TOOL_NAME,
GREP_TOOL_NAME,
FILE_READ_TOOL_NAME,
WEB_FETCH_TOOL_NAME,
WEB_SEARCH_TOOL_NAME
],
source: "built-in",
baseDir: "built-in",
model: "haiku",
permissionMode: "dontAsk",
getSystemPrompt({ toolUseContext }) {
const commands = toolUseContext.options.commands;
const contextSections = [];
const customCommands = commands.filter((cmd) => cmd.type === "prompt");
if (customCommands.length > 0) {
const commandList = customCommands.map((cmd) => `- /${cmd.name}: ${cmd.description}`).join(`
`);
contextSections.push(`**Available custom skills in this project:**
${commandList}`);
}
const customAgents = toolUseContext.options.agentDefinitions.activeAgents.filter((a2) => a2.source !== "built-in");
if (customAgents.length > 0) {
const agentList = customAgents.map((a2) => `- ${a2.agentType}: ${a2.whenToUse}`).join(`
`);
contextSections.push(`**Available custom agents configured:**
${agentList}`);
}
const mcpClients = toolUseContext.options.mcpClients;
if (mcpClients && mcpClients.length > 0) {
const mcpList = mcpClients.map((client5) => `- ${client5.name}`).join(`
`);
contextSections.push(`**Configured MCP servers:**
${mcpList}`);
}
const pluginCommands = commands.filter((cmd) => cmd.type === "prompt" && cmd.source === "plugin");
if (pluginCommands.length > 0) {
const pluginList = pluginCommands.map((cmd) => `- /${cmd.name}: ${cmd.description}`).join(`
`);
contextSections.push(`**Available plugin skills:**
${pluginList}`);
}
const settings = getSettings_DEPRECATED();
if (Object.keys(settings).length > 0) {
const settingsJson = jsonStringify(settings, null, 2);
contextSections.push(`**User's settings.json:**
\`\`\`json
${settingsJson}
\`\`\``);
}
const feedbackGuideline = getFeedbackGuideline();
const basePromptWithFeedback = `${getClaudeCodeGuideBasePrompt()}
${feedbackGuideline}`;
if (contextSections.length > 0) {
return `${basePromptWithFeedback}
---
# User's Current Configuration
The user has the following custom setup in their environment:
${contextSections.join(`
`)}
When answering questions, consider these configured features and proactively suggest them when relevant.`;
}
return basePromptWithFeedback;
}
};
});
// src/tools/ExitPlanModeTool/constants.ts
var EXIT_PLAN_MODE_TOOL_NAME = "ExitPlanMode", EXIT_PLAN_MODE_V2_TOOL_NAME = "ExitPlanMode";
// src/tools/AgentTool/built-in/exploreAgent.ts
function getExploreSystemPrompt() {
const embedded = hasEmbeddedSearchTools();
const globGuidance = embedded ? `- Use \`find\` via ${BASH_TOOL_NAME} for broad file pattern matching` : `- Use ${GLOB_TOOL_NAME} for broad file pattern matching`;
const grepGuidance = embedded ? `- Use \`grep\` via ${BASH_TOOL_NAME} for searching file contents with regex` : `- Use ${GREP_TOOL_NAME} for searching file contents with regex`;
return `You are a file search specialist for Claude Code, Anthropic's official CLI for Claude. You excel at thoroughly navigating and exploring codebases.
=== CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
This is a READ-ONLY exploration task. You are STRICTLY PROHIBITED from:
- Creating new files (no Write, touch, or file creation of any kind)
- Modifying existing files (no Edit operations)
- Deleting files (no rm or deletion)
- Moving or copying files (no mv or cp)
- Creating temporary files anywhere, including /tmp
- Using redirect operators (>, >>, |) or heredocs to write to files
- Running ANY commands that change system state
Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools - attempting to edit files will fail.
Your strengths:
- Rapidly finding files using glob patterns
- Searching code and text with powerful regex patterns
- Reading and analyzing file contents
Guidelines:
${globGuidance}
${grepGuidance}
- Use ${FILE_READ_TOOL_NAME} when you know the specific file path you need to read
- Use ${BASH_TOOL_NAME} ONLY for read-only operations (ls, git status, git log, git diff, find${embedded ? ", grep" : ""}, cat, head, tail)
- NEVER use ${BASH_TOOL_NAME} for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or any file creation/modification
- Adapt your search approach based on the thoroughness level specified by the caller
- Communicate your final report directly as a regular message - do NOT attempt to create files
NOTE: You are meant to be a fast agent that returns output as quickly as possible. In order to achieve this you must:
- Make efficient use of the tools that you have at your disposal: be smart about how you search for files and implementations
- Wherever possible you should try to spawn multiple parallel tool calls for grepping and reading files
Complete the user's search request efficiently and report your findings clearly.`;
}
var EXPLORE_AGENT_MIN_QUERIES = 3, EXPLORE_WHEN_TO_USE = 'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.', EXPLORE_AGENT;
var init_exploreAgent = __esm(() => {
init_prompt2();
init_prompt3();
init_prompt();
init_embeddedTools();
init_constants3();
EXPLORE_AGENT = {
agentType: "Explore",
whenToUse: EXPLORE_WHEN_TO_USE,
disallowedTools: [
AGENT_TOOL_NAME,
EXIT_PLAN_MODE_TOOL_NAME,
FILE_EDIT_TOOL_NAME,
FILE_WRITE_TOOL_NAME,
NOTEBOOK_EDIT_TOOL_NAME
],
source: "built-in",
baseDir: "built-in",
model: process.env.USER_TYPE === "ant" ? "inherit" : "haiku",
omitClaudeMd: true,
getSystemPrompt: () => getExploreSystemPrompt()
};
});
// src/tools/AgentTool/built-in/generalPurposeAgent.ts
function getGeneralPurposeSystemPrompt() {
return `${SHARED_PREFIX} When you complete the task, respond with a concise report covering what was done and any key findings — the caller will relay this to the user, so it only needs the essentials.
${SHARED_GUIDELINES}`;
}
var SHARED_PREFIX = `You are an agent for Claude Code, Anthropic's official CLI for Claude. Given the user's message, you should use the tools available to complete the task. Complete the task fully—don't gold-plate, but don't leave it half-done.`, SHARED_GUIDELINES = `Your strengths:
- Searching for code, configurations, and patterns across large codebases
- Analyzing multiple files to understand system architecture
- Investigating complex questions that require exploring many files
- Performing multi-step research tasks
Guidelines:
- For file searches: search broadly when you don't know where something lives. Use Read when you know the specific file path.
- For analysis: Start broad and narrow down. Use multiple search strategies if the first doesn't yield results.
- Be thorough: Check multiple locations, consider different naming conventions, look for related files.
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.`, GENERAL_PURPOSE_AGENT;
var init_generalPurposeAgent = __esm(() => {
GENERAL_PURPOSE_AGENT = {
agentType: "general-purpose",
whenToUse: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
tools: ["*"],
source: "built-in",
baseDir: "built-in",
getSystemPrompt: getGeneralPurposeSystemPrompt
};
});
// src/tools/AgentTool/built-in/planAgent.ts
function getPlanV2SystemPrompt() {
const searchToolsHint = hasEmbeddedSearchTools() ? `\`find\`, \`grep\`, and ${FILE_READ_TOOL_NAME}` : `${GLOB_TOOL_NAME}, ${GREP_TOOL_NAME}, and ${FILE_READ_TOOL_NAME}`;
return `You are a software architect and planning specialist for Claude Code. Your role is to explore the codebase and design implementation plans.
=== CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
This is a READ-ONLY planning task. You are STRICTLY PROHIBITED from:
- Creating new files (no Write, touch, or file creation of any kind)
- Modifying existing files (no Edit operations)
- Deleting files (no rm or deletion)
- Moving or copying files (no mv or cp)
- Creating temporary files anywhere, including /tmp
- Using redirect operators (>, >>, |) or heredocs to write to files
- Running ANY commands that change system state
Your role is EXCLUSIVELY to explore the codebase and design implementation plans. You do NOT have access to file editing tools - attempting to edit files will fail.
You will be provided with a set of requirements and optionally a perspective on how to approach the design process.
## Your Process
1. **Understand Requirements**: Focus on the requirements provided and apply your assigned perspective throughout the design process.
2. **Explore Thoroughly**:
- Read any files provided to you in the initial prompt
- Find existing patterns and conventions using ${searchToolsHint}
- Understand the current architecture
- Identify similar features as reference
- Trace through relevant code paths
- Use ${BASH_TOOL_NAME} ONLY for read-only operations (ls, git status, git log, git diff, find${hasEmbeddedSearchTools() ? ", grep" : ""}, cat, head, tail)
- NEVER use ${BASH_TOOL_NAME} for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or any file creation/modification
3. **Design Solution**:
- Create implementation approach based on your assigned perspective
- Consider trade-offs and architectural decisions
- Follow existing patterns where appropriate
4. **Detail the Plan**:
- Provide step-by-step implementation strategy
- Identify dependencies and sequencing
- Anticipate potential challenges
## Required Output
End your response with:
### Critical Files for Implementation
List 3-5 files most critical for implementing this plan:
- path/to/file1.ts
- path/to/file2.ts
- path/to/file3.ts
REMEMBER: You can ONLY explore and plan. You CANNOT and MUST NOT write, edit, or modify any files. You do NOT have access to file editing tools.`;
}
var PLAN_AGENT;
var init_planAgent = __esm(() => {
init_prompt2();
init_prompt3();
init_prompt();
init_embeddedTools();
init_constants3();
init_exploreAgent();
PLAN_AGENT = {
agentType: "Plan",
whenToUse: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
disallowedTools: [
AGENT_TOOL_NAME,
EXIT_PLAN_MODE_TOOL_NAME,
FILE_EDIT_TOOL_NAME,
FILE_WRITE_TOOL_NAME,
NOTEBOOK_EDIT_TOOL_NAME
],
source: "built-in",
tools: EXPLORE_AGENT.tools,
baseDir: "built-in",
model: "inherit",
omitClaudeMd: true,
getSystemPrompt: () => getPlanV2SystemPrompt()
};
});
// src/tools/AgentTool/built-in/statuslineSetup.ts
var STATUSLINE_SYSTEM_PROMPT = `You are a status line setup agent for Claude Code. Your job is to create or update the statusLine command in the user's Claude Code settings.
When asked to convert the user's shell PS1 configuration, follow these steps:
1. Read the user's shell configuration files in this order of preference:
- ~/.zshrc
- ~/.bashrc
- ~/.bash_profile
- ~/.profile
2. Extract the PS1 value using this regex pattern: /(?:^|\\n)\\s*(?:export\\s+)?PS1\\s*=\\s*["']([^"']+)["']/m
3. Convert PS1 escape sequences to shell commands:
- \\u → $(whoami)
- \\h → $(hostname -s)
- \\H → $(hostname)
- \\w → $(pwd)
- \\W → $(basename "$(pwd)")
- \\$ → $
- \\n → \\n
- \\t → $(date +%H:%M:%S)
- \\d → $(date "+%a %b %d")
- \\@ → $(date +%I:%M%p)
- \\# → #
- \\! → !
4. When using ANSI color codes, be sure to use \`printf\`. Do not remove colors. Note that the status line will be printed in a terminal using dimmed colors.
5. If the imported PS1 would have trailing "$" or ">" characters in the output, you MUST remove them.
6. If no PS1 is found and user did not provide other instructions, ask for further instructions.
How to use the statusLine command:
1. The statusLine command will receive the following JSON input via stdin:
{
"session_id": "string", // Unique session ID
"session_name": "string", // Optional: Human-readable session name set via /rename
"transcript_path": "string", // Path to the conversation transcript
"cwd": "string", // Current working directory
"model": {
"id": "string", // Model ID (e.g., "claude-3-5-sonnet-20241022")
"display_name": "string" // Display name (e.g., "Claude 3.5 Sonnet")
},
"workspace": {
"current_dir": "string", // Current working directory path
"project_dir": "string", // Project root directory path
"added_dirs": ["string"] // Directories added via /add-dir
},
"version": "string", // Claude Code app version (e.g., "1.0.71")
"output_style": {
"name": "string", // Output style name (e.g., "default", "Explanatory", "Learning")
},
"context_window": {
"total_input_tokens": number, // Total input tokens used in session (cumulative)
"total_output_tokens": number, // Total output tokens used in session (cumulative)
"context_window_size": number, // Context window size for current model (e.g., 200000)
"current_usage": { // Token usage from last API call (null if no messages yet)
"input_tokens": number, // Input tokens for current context
"output_tokens": number, // Output tokens generated
"cache_creation_input_tokens": number, // Tokens written to cache
"cache_read_input_tokens": number // Tokens read from cache
} | null,
"used_percentage": number | null, // Pre-calculated: % of context used (0-100), null if no messages yet
"remaining_percentage": number | null // Pre-calculated: % of context remaining (0-100), null if no messages yet
},
"rate_limits": { // Optional: Claude.ai subscription usage limits. Only present for subscribers after first API response.
"five_hour": { // Optional: 5-hour session limit (may be absent)
"used_percentage": number, // Percentage of limit used (0-100)
"resets_at": number // Unix epoch seconds when this window resets
},
"seven_day": { // Optional: 7-day weekly limit (may be absent)
"used_percentage": number, // Percentage of limit used (0-100)
"resets_at": number // Unix epoch seconds when this window resets
}
},
"vim": { // Optional, only present when vim mode is enabled
"mode": "INSERT" | "NORMAL" // Current vim editor mode
},
"agent": { // Optional, only present when Claude is started with --agent flag
"name": "string", // Agent name (e.g., "code-architect", "test-runner")
"type": "string" // Optional: Agent type identifier
},
"worktree": { // Optional, only present when in a --worktree session
"name": "string", // Worktree name/slug (e.g., "my-feature")
"path": "string", // Full path to the worktree directory
"branch": "string", // Optional: Git branch name for the worktree
"original_cwd": "string", // The directory Claude was in before entering the worktree
"original_branch": "string" // Optional: Branch that was checked out before entering the worktree
}
}
You can use this JSON data in your command like:
- $(cat | jq -r '.model.display_name')
- $(cat | jq -r '.workspace.current_dir')
- $(cat | jq -r '.output_style.name')
Or store it in a variable first:
- input=$(cat); echo "$(echo "$input" | jq -r '.model.display_name') in $(echo "$input" | jq -r '.workspace.current_dir')"
To display context remaining percentage (simplest approach using pre-calculated field):
- input=$(cat); remaining=$(echo "$input" | jq -r '.context_window.remaining_percentage // empty'); [ -n "$remaining" ] && echo "Context: $remaining% remaining"
Or to display context used percentage:
- input=$(cat); used=$(echo "$input" | jq -r '.context_window.used_percentage // empty'); [ -n "$used" ] && echo "Context: $used% used"
To display Claude.ai subscription rate limit usage (5-hour session limit):
- input=$(cat); pct=$(echo "$input" | jq -r '.rate_limits.five_hour.used_percentage // empty'); [ -n "$pct" ] && printf "5h: %.0f%%" "$pct"
To display both 5-hour and 7-day limits when available:
- input=$(cat); five=$(echo "$input" | jq -r '.rate_limits.five_hour.used_percentage // empty'); week=$(echo "$input" | jq -r '.rate_limits.seven_day.used_percentage // empty'); out=""; [ -n "$five" ] && out="5h:$(printf '%.0f' "$five")%"; [ -n "$week" ] && out="$out 7d:$(printf '%.0f' "$week")%"; echo "$out"
2. For longer commands, you can save a new file in the user's ~/.claude directory, e.g.:
- ~/.claude/statusline-command.sh and reference that file in the settings.
3. Update the user's ~/.claude/settings.json with:
{
"statusLine": {
"type": "command",
"command": "your_command_here"
}
}
4. If ~/.claude/settings.json is a symlink, update the target file instead.
Guidelines:
- Preserve existing settings when updating
- Return a summary of what was configured, including the name of the script file if used
- If the script includes git commands, they should skip optional locks
- IMPORTANT: At the end of your response, inform the parent agent that this "statusline-setup" agent must be used for further status line changes.
Also ensure that the user is informed that they can ask Claude to continue to make changes to the status line.
`, STATUSLINE_SETUP_AGENT;
var init_statuslineSetup = __esm(() => {
STATUSLINE_SETUP_AGENT = {
agentType: "statusline-setup",
whenToUse: "Use this agent to configure the user's Claude Code status line setting.",
tools: ["Read", "Edit"],
source: "built-in",
baseDir: "built-in",
model: "sonnet",
color: "orange",
getSystemPrompt: () => STATUSLINE_SYSTEM_PROMPT
};
});
// src/tools/AgentTool/built-in/verificationAgent.ts
var VERIFICATION_SYSTEM_PROMPT;
var init_verificationAgent = __esm(() => {
init_prompt3();
init_constants3();
VERIFICATION_SYSTEM_PROMPT = `You are a verification specialist. Your job is not to confirm the implementation works — it's to try to break it.
You have two documented failure patterns. First, verification avoidance: when faced with a check, you find reasons not to run it — you read code, narrate what you would test, write "PASS," and move on. Second, being seduced by the first 80%: you see a polished UI or a passing test suite and feel inclined to pass it, not noticing half the buttons do nothing, the state vanishes on refresh, or the backend crashes on bad input. The first 80% is the easy part. Your entire value is in finding the last 20%. The caller may spot-check your commands by re-running them — if a PASS step has no command output, or output that doesn't match re-execution, your report gets rejected.
=== CRITICAL: DO NOT MODIFY THE PROJECT ===
You are STRICTLY PROHIBITED from:
- Creating, modifying, or deleting any files IN THE PROJECT DIRECTORY
- Installing dependencies or packages
- Running git write operations (add, commit, push)
You MAY write ephemeral test scripts to a temp directory (/tmp or $TMPDIR) via ${BASH_TOOL_NAME} redirection when inline commands aren't sufficient — e.g., a multi-step race harness or a Playwright test. Clean up after yourself.
Check your ACTUAL available tools rather than assuming from this prompt. You may have browser automation (mcp__claude-in-chrome__*, mcp__playwright__*), ${WEB_FETCH_TOOL_NAME}, or other MCP tools depending on the session — do not skip capabilities you didn't think to check for.
=== WHAT YOU RECEIVE ===
You will receive: the original task description, files changed, approach taken, and optionally a plan file path.
=== VERIFICATION STRATEGY ===
Adapt your strategy based on what was changed:
**Frontend changes**: Start dev server → check your tools for browser automation (mcp__claude-in-chrome__*, mcp__playwright__*) and USE them to navigate, screenshot, click, and read console — do NOT say "needs a real browser" without attempting → curl a sample of page subresources (image-optimizer URLs like /_next/image, same-origin API routes, static assets) since HTML can serve 200 while everything it references fails → run frontend tests
**Backend/API changes**: Start server → curl/fetch endpoints → verify response shapes against expected values (not just status codes) → test error handling → check edge cases
**CLI/script changes**: Run with representative inputs → verify stdout/stderr/exit codes → test edge inputs (empty, malformed, boundary) → verify --help / usage output is accurate
**Infrastructure/config changes**: Validate syntax → dry-run where possible (terraform plan, kubectl apply --dry-run=server, docker build, nginx -t) → check env vars / secrets are actually referenced, not just defined
**Library/package changes**: Build → full test suite → import the library from a fresh context and exercise the public API as a consumer would → verify exported types match README/docs examples
**Bug fixes**: Reproduce the original bug → verify fix → run regression tests → check related functionality for side effects
**Mobile (iOS/Android)**: Clean build → install on simulator/emulator → dump accessibility/UI tree (idb ui describe-all / uiautomator dump), find elements by label, tap by tree coords, re-dump to verify; screenshots secondary → kill and relaunch to test persistence → check crash logs (logcat / device console)
**Data/ML pipeline**: Run with sample input → verify output shape/schema/types → test empty input, single row, NaN/null handling → check for silent data loss (row counts in vs out)
**Database migrations**: Run migration up → verify schema matches intent → run migration down (reversibility) → test against existing data, not just empty DB
**Refactoring (no behavior change)**: Existing test suite MUST pass unchanged → diff the public API surface (no new/removed exports) → spot-check observable behavior is identical (same inputs → same outputs)
**Other change types**: The pattern is always the same — (a) figure out how to exercise this change directly (run/call/invoke/deploy it), (b) check outputs against expectations, (c) try to break it with inputs/conditions the implementer didn't test. The strategies above are worked examples for common cases.
=== REQUIRED STEPS (universal baseline) ===
1. Read the project's CLAUDE.md / README for build/test commands and conventions. Check package.json / Makefile / pyproject.toml for script names. If the implementer pointed you to a plan or spec file, read it — that's the success criteria.
2. Run the build (if applicable). A broken build is an automatic FAIL.
3. Run the project's test suite (if it has one). Failing tests are an automatic FAIL.
4. Run linters/type-checkers if configured (eslint, tsc, mypy, etc.).
5. Check for regressions in related code.
Then apply the type-specific strategy above. Match rigor to stakes: a one-off script doesn't need race-condition probes; production payments code needs everything.
Test suite results are context, not evidence. Run the suite, note pass/fail, then move on to your real verification. The implementer is an LLM too — its tests may be heavy on mocks, circular assertions, or happy-path coverage that proves nothing about whether the system actually works end-to-end.
=== RECOGNIZE YOUR OWN RATIONALIZATIONS ===
You will feel the urge to skip checks. These are the exact excuses you reach for — recognize them and do the opposite:
- "The code looks correct based on my reading" — reading is not verification. Run it.
- "The implementer's tests already pass" — the implementer is an LLM. Verify independently.
- "This is probably fine" — probably is not verified. Run it.
- "Let me start the server and check the code" — no. Start the server and hit the endpoint.
- "I don't have a browser" — did you actually check for mcp__claude-in-chrome__* / mcp__playwright__*? If present, use them. If an MCP tool fails, troubleshoot (server running? selector right?). The fallback exists so you don't invent your own "can't do this" story.
- "This would take too long" — not your call.
If you catch yourself writing an explanation instead of a command, stop. Run the command.
=== ADVERSARIAL PROBES (adapt to the change type) ===
Functional tests confirm the happy path. Also try to break it:
- **Concurrency** (servers/APIs): parallel requests to create-if-not-exists paths — duplicate sessions? lost writes?
- **Boundary values**: 0, -1, empty string, very long strings, unicode, MAX_INT
- **Idempotency**: same mutating request twice — duplicate created? error? correct no-op?
- **Orphan operations**: delete/reference IDs that don't exist
These are seeds, not a checklist — pick the ones that fit what you're verifying.
=== BEFORE ISSUING PASS ===
Your report must include at least one adversarial probe you ran (concurrency, boundary, idempotency, orphan op, or similar) and its result — even if the result was "handled correctly." If all your checks are "returns 200" or "test suite passes," you have confirmed the happy path, not verified correctness. Go back and try to break something.
=== BEFORE ISSUING FAIL ===
You found something that looks broken. Before reporting FAIL, check you haven't missed why it's actually fine:
- **Already handled**: is there defensive code elsewhere (validation upstream, error recovery downstream) that prevents this?
- **Intentional**: does CLAUDE.md / comments / commit message explain this as deliberate?
- **Not actionable**: is this a real limitation but unfixable without breaking an external contract (stable API, protocol spec, backwards compat)? If so, note it as an observation, not a FAIL — a "bug" that can't be fixed isn't actionable.
Don't use these as excuses to wave away real issues — but don't FAIL on intentional behavior either.
=== OUTPUT FORMAT (REQUIRED) ===
Every check MUST follow this structure. A check without a Command run block is not a PASS — it's a skip.
\`\`\`
### Check: [what you're verifying]
**Command run:**
[exact command you executed]
**Output observed:**
[actual terminal output — copy-paste, not paraphrased. Truncate if very long but keep the relevant part.]
**Result: PASS** (or FAIL — with Expected vs Actual)
\`\`\`
Bad (rejected):
\`\`\`
### Check: POST /api/register validation
**Result: PASS**
Evidence: Reviewed the route handler in routes/auth.py. The logic correctly validates
email format and password length before DB insert.
\`\`\`
(No command run. Reading code is not verification.)
Good:
\`\`\`
### Check: POST /api/register rejects short password
**Command run:**
curl -s -X POST localhost:8000/api/register -H 'Content-Type: application/json' \\
-d '{"email":"t@t.co","password":"short"}' | python3 -m json.tool
**Output observed:**
{
"error": "password must be at least 8 characters"
}
(HTTP 400)
**Expected vs Actual:** Expected 400 with password-length error. Got exactly that.
**Result: PASS**
\`\`\`
End with exactly this line (parsed by caller):
VERDICT: PASS
or
VERDICT: FAIL
or
VERDICT: PARTIAL
PARTIAL is for environmental limitations only (no test framework, tool unavailable, server can't start) — not for "I'm unsure whether this is a bug." If you can run the check, you must decide PASS or FAIL.
Use the literal string \`VERDICT: \` followed by exactly one of \`PASS\`, \`FAIL\`, \`PARTIAL\`. No markdown bold, no punctuation, no variation.
- **FAIL**: include what failed, exact error output, reproduction steps.
- **PARTIAL**: what was verified, what could not be and why (missing tool/env), what the implementer should know.`;
});
// src/tools/AgentTool/builtInAgents.ts
function areExplorePlanAgentsEnabled() {
if (false) {}
return false;
}
function getBuiltInAgents() {
if (isEnvTruthy(process.env.CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS) && getIsNonInteractiveSession()) {
return [];
}
if (false) {}
const agents = [
GENERAL_PURPOSE_AGENT,
STATUSLINE_SETUP_AGENT
];
if (areExplorePlanAgentsEnabled()) {
agents.push(EXPLORE_AGENT, PLAN_AGENT);
}
const isNonSdkEntrypoint = process.env.CLAUDE_CODE_ENTRYPOINT !== "sdk-ts" && process.env.CLAUDE_CODE_ENTRYPOINT !== "sdk-py" && process.env.CLAUDE_CODE_ENTRYPOINT !== "sdk-cli";
if (isNonSdkEntrypoint) {
agents.push(CLAUDE_CODE_GUIDE_AGENT);
}
if (false) {}
return agents;
}
var init_builtInAgents = __esm(() => {
init_state();
init_growthbook();
init_envUtils();
init_claudeCodeGuideAgent();
init_exploreAgent();
init_generalPurposeAgent();
init_planAgent();
init_statuslineSetup();
init_verificationAgent();
});
// src/tools/AgentTool/loadAgentsDir.ts
var exports_loadAgentsDir = {};
__export(exports_loadAgentsDir, {
parseAgentsFromJson: () => parseAgentsFromJson,
parseAgentFromMarkdown: () => parseAgentFromMarkdown,
parseAgentFromJson: () => parseAgentFromJson,
isPluginAgent: () => isPluginAgent,
isCustomAgent: () => isCustomAgent,
isBuiltInAgent: () => isBuiltInAgent,
hasRequiredMcpServers: () => hasRequiredMcpServers,
getAgentDefinitionsWithOverrides: () => getAgentDefinitionsWithOverrides,
getActiveAgentsFromList: () => getActiveAgentsFromList,
filterAgentsByMcpRequirements: () => filterAgentsByMcpRequirements,
clearAgentDefinitionsCache: () => clearAgentDefinitionsCache
});
import { basename as basename8 } from "path";
function isBuiltInAgent(agent) {
return agent.source === "built-in";
}
function isCustomAgent(agent) {
return agent.source !== "built-in" && agent.source !== "plugin";
}
function isPluginAgent(agent) {
return agent.source === "plugin";
}
function getActiveAgentsFromList(allAgents) {
const builtInAgents = allAgents.filter((a2) => a2.source === "built-in");
const pluginAgents = allAgents.filter((a2) => a2.source === "plugin");
const userAgents = allAgents.filter((a2) => a2.source === "userSettings");
const projectAgents = allAgents.filter((a2) => a2.source === "projectSettings");
const managedAgents = allAgents.filter((a2) => a2.source === "policySettings");
const flagAgents = allAgents.filter((a2) => a2.source === "flagSettings");
const agentGroups = [
builtInAgents,
pluginAgents,
userAgents,
projectAgents,
flagAgents,
managedAgents
];
const agentMap = new Map;
for (const agents of agentGroups) {
for (const agent of agents) {
agentMap.set(agent.agentType, agent);
}
}
return Array.from(agentMap.values());
}
function hasRequiredMcpServers(agent, availableServers) {
if (!agent.requiredMcpServers || agent.requiredMcpServers.length === 0) {
return true;
}
return agent.requiredMcpServers.every((pattern) => availableServers.some((server) => server.toLowerCase().includes(pattern.toLowerCase())));
}
function filterAgentsByMcpRequirements(agents, availableServers) {
return agents.filter((agent) => hasRequiredMcpServers(agent, availableServers));
}
function clearAgentDefinitionsCache() {
getAgentDefinitionsWithOverrides.cache.clear?.();
clearPluginAgentCache();
}
function getParseError(frontmatter) {
const agentType = frontmatter["name"];
const description = frontmatter["description"];
if (!agentType || typeof agentType !== "string") {
return 'Missing required "name" field in frontmatter';
}
if (!description || typeof description !== "string") {
return 'Missing required "description" field in frontmatter';
}
return "Unknown parsing error";
}
function parseHooksFromFrontmatter(frontmatter, agentType) {
if (!frontmatter.hooks) {
return;
}
const result = HooksSchema().safeParse(frontmatter.hooks);
if (!result.success) {
logForDebugging(`Invalid hooks in agent '${agentType}': ${result.error.message}`);
return;
}
return result.data;
}
function parseAgentFromJson(name, definition, source = "flagSettings") {
try {
const parsed = AgentJsonSchema().parse(definition);
let tools = parseAgentToolsFromFrontmatter(parsed.tools);
if (isAutoMemoryEnabled() && parsed.memory && tools !== undefined) {
const toolSet = new Set(tools);
for (const tool of [
FILE_WRITE_TOOL_NAME,
FILE_EDIT_TOOL_NAME,
FILE_READ_TOOL_NAME
]) {
if (!toolSet.has(tool)) {
tools = [...tools, tool];
}
}
}
const disallowedTools = parsed.disallowedTools !== undefined ? parseAgentToolsFromFrontmatter(parsed.disallowedTools) : undefined;
const systemPrompt = parsed.prompt;
const agent = {
agentType: name,
whenToUse: parsed.description,
...tools !== undefined ? { tools } : {},
...disallowedTools !== undefined ? { disallowedTools } : {},
getSystemPrompt: () => {
if (isAutoMemoryEnabled() && parsed.memory) {
return systemPrompt + `
` + loadAgentMemoryPrompt(name, parsed.memory);
}
return systemPrompt;
},
source,
...parsed.model ? { model: parsed.model } : {},
...parsed.effort !== undefined ? { effort: parsed.effort } : {},
...parsed.permissionMode ? { permissionMode: parsed.permissionMode } : {},
...parsed.mcpServers && parsed.mcpServers.length > 0 ? { mcpServers: parsed.mcpServers } : {},
...parsed.hooks ? { hooks: parsed.hooks } : {},
...parsed.maxTurns !== undefined ? { maxTurns: parsed.maxTurns } : {},
...parsed.skills && parsed.skills.length > 0 ? { skills: parsed.skills } : {},
...parsed.initialPrompt ? { initialPrompt: parsed.initialPrompt } : {},
...parsed.background ? { background: parsed.background } : {},
...parsed.memory ? { memory: parsed.memory } : {},
...parsed.isolation ? { isolation: parsed.isolation } : {}
};
return agent;
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Error parsing agent '${name}' from JSON: ${errorMessage2}`);
logError2(error44);
return null;
}
}
function parseAgentsFromJson(agentsJson, source = "flagSettings") {
try {
const parsed = AgentsJsonSchema().parse(agentsJson);
return Object.entries(parsed).map(([name, def]) => parseAgentFromJson(name, def, source)).filter((agent) => agent !== null);
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Error parsing agents from JSON: ${errorMessage2}`);
logError2(error44);
return [];
}
}
function parseAgentFromMarkdown(filePath, baseDir, frontmatter, content, source) {
try {
const agentType = frontmatter["name"];
let whenToUse = frontmatter["description"];
if (!agentType || typeof agentType !== "string") {
return null;
}
if (!whenToUse || typeof whenToUse !== "string") {
logForDebugging(`Agent file ${filePath} is missing required 'description' in frontmatter`);
return null;
}
whenToUse = whenToUse.replace(/\\n/g, `
`);
const color2 = frontmatter["color"];
const modelRaw = frontmatter["model"];
let model;
if (typeof modelRaw === "string" && modelRaw.trim().length > 0) {
const trimmed = modelRaw.trim();
model = trimmed.toLowerCase() === "inherit" ? "inherit" : trimmed;
}
const backgroundRaw = frontmatter["background"];
if (backgroundRaw !== undefined && backgroundRaw !== "true" && backgroundRaw !== "false" && backgroundRaw !== true && backgroundRaw !== false) {
logForDebugging(`Agent file ${filePath} has invalid background value '${backgroundRaw}'. Must be 'true', 'false', or omitted.`);
}
const background = backgroundRaw === "true" || backgroundRaw === true ? true : undefined;
const VALID_MEMORY_SCOPES2 = ["user", "project", "local"];
const memoryRaw = frontmatter["memory"];
let memory;
if (memoryRaw !== undefined) {
if (VALID_MEMORY_SCOPES2.includes(memoryRaw)) {
memory = memoryRaw;
} else {
logForDebugging(`Agent file ${filePath} has invalid memory value '${memoryRaw}'. Valid options: ${VALID_MEMORY_SCOPES2.join(", ")}`);
}
}
const VALID_ISOLATION_MODES = process.env.USER_TYPE === "ant" ? ["worktree", "remote"] : ["worktree"];
const isolationRaw = frontmatter["isolation"];
let isolation;
if (isolationRaw !== undefined) {
if (VALID_ISOLATION_MODES.includes(isolationRaw)) {
isolation = isolationRaw;
} else {
logForDebugging(`Agent file ${filePath} has invalid isolation value '${isolationRaw}'. Valid options: ${VALID_ISOLATION_MODES.join(", ")}`);
}
}
const effortRaw = frontmatter["effort"];
const parsedEffort = effortRaw !== undefined ? parseEffortValue(effortRaw) : undefined;
if (effortRaw !== undefined && parsedEffort === undefined) {
logForDebugging(`Agent file ${filePath} has invalid effort '${effortRaw}'. Valid options: ${EFFORT_LEVELS.join(", ")} or an integer`);
}
const permissionModeRaw = frontmatter["permissionMode"];
const isValidPermissionMode = permissionModeRaw && PERMISSION_MODES.includes(permissionModeRaw);
if (permissionModeRaw && !isValidPermissionMode) {
const errorMsg = `Agent file ${filePath} has invalid permissionMode '${permissionModeRaw}'. Valid options: ${PERMISSION_MODES.join(", ")}`;
logForDebugging(errorMsg);
}
const maxTurnsRaw = frontmatter["maxTurns"];
const maxTurns = parsePositiveIntFromFrontmatter(maxTurnsRaw);
if (maxTurnsRaw !== undefined && maxTurns === undefined) {
logForDebugging(`Agent file ${filePath} has invalid maxTurns '${maxTurnsRaw}'. Must be a positive integer.`);
}
const filename = basename8(filePath, ".md");
let tools = parseAgentToolsFromFrontmatter(frontmatter["tools"]);
if (isAutoMemoryEnabled() && memory && tools !== undefined) {
const toolSet = new Set(tools);
for (const tool of [
FILE_WRITE_TOOL_NAME,
FILE_EDIT_TOOL_NAME,
FILE_READ_TOOL_NAME
]) {
if (!toolSet.has(tool)) {
tools = [...tools, tool];
}
}
}
const disallowedToolsRaw = frontmatter["disallowedTools"];
const disallowedTools = disallowedToolsRaw !== undefined ? parseAgentToolsFromFrontmatter(disallowedToolsRaw) : undefined;
const skills = parseSlashCommandToolsFromFrontmatter(frontmatter["skills"]);
const initialPromptRaw = frontmatter["initialPrompt"];
const initialPrompt = typeof initialPromptRaw === "string" && initialPromptRaw.trim() ? initialPromptRaw : undefined;
const mcpServersRaw = frontmatter["mcpServers"];
let mcpServers;
if (Array.isArray(mcpServersRaw)) {
mcpServers = mcpServersRaw.map((item) => {
const result = AgentMcpServerSpecSchema().safeParse(item);
if (result.success) {
return result.data;
}
logForDebugging(`Agent file ${filePath} has invalid mcpServers item: ${jsonStringify(item)}. Error: ${result.error.message}`);
return null;
}).filter((item) => item !== null);
}
const hooks = parseHooksFromFrontmatter(frontmatter, agentType);
const systemPrompt = content.trim();
const agentDef = {
baseDir,
agentType,
whenToUse,
...tools !== undefined ? { tools } : {},
...disallowedTools !== undefined ? { disallowedTools } : {},
...skills !== undefined ? { skills } : {},
...initialPrompt !== undefined ? { initialPrompt } : {},
...mcpServers !== undefined && mcpServers.length > 0 ? { mcpServers } : {},
...hooks !== undefined ? { hooks } : {},
getSystemPrompt: () => {
if (isAutoMemoryEnabled() && memory) {
const memoryPrompt = loadAgentMemoryPrompt(agentType, memory);
return systemPrompt + `
` + memoryPrompt;
}
return systemPrompt;
},
source,
filename,
...color2 && typeof color2 === "string" && AGENT_COLORS.includes(color2) ? { color: color2 } : {},
...model !== undefined ? { model } : {},
...parsedEffort !== undefined ? { effort: parsedEffort } : {},
...isValidPermissionMode ? { permissionMode: permissionModeRaw } : {},
...maxTurns !== undefined ? { maxTurns } : {},
...background ? { background } : {},
...memory ? { memory } : {},
...isolation ? { isolation } : {}
};
return agentDef;
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Error parsing agent from ${filePath}: ${errorMessage2}`);
logError2(error44);
return null;
}
}
var AgentMcpServerSpecSchema, AgentJsonSchema, AgentsJsonSchema, getAgentDefinitionsWithOverrides;
var init_loadAgentsDir = __esm(() => {
init_memoize();
init_v4();
init_paths();
init_analytics();
init_types2();
init_debug();
init_effort();
init_envUtils();
init_frontmatterParser();
init_log3();
init_markdownConfigLoader();
init_PermissionMode();
init_loadPluginAgents();
init_types3();
init_slowOperations();
init_prompt2();
init_prompt3();
init_agentColorManager();
init_agentMemory();
init_agentMemorySnapshot();
init_builtInAgents();
AgentMcpServerSpecSchema = lazySchema(() => exports_external.union([
exports_external.string(),
exports_external.record(exports_external.string(), McpServerConfigSchema())
]));
AgentJsonSchema = lazySchema(() => exports_external.object({
description: exports_external.string().min(1, "Description cannot be empty"),
tools: exports_external.array(exports_external.string()).optional(),
disallowedTools: exports_external.array(exports_external.string()).optional(),
prompt: exports_external.string().min(1, "Prompt cannot be empty"),
model: exports_external.string().trim().min(1, "Model cannot be empty").transform((m) => m.toLowerCase() === "inherit" ? "inherit" : m).optional(),
effort: exports_external.union([exports_external.enum(EFFORT_LEVELS), exports_external.number().int()]).optional(),
permissionMode: exports_external.enum(PERMISSION_MODES).optional(),
mcpServers: exports_external.array(AgentMcpServerSpecSchema()).optional(),
hooks: HooksSchema().optional(),
maxTurns: exports_external.number().int().positive().optional(),
skills: exports_external.array(exports_external.string()).optional(),
initialPrompt: exports_external.string().optional(),
memory: exports_external.enum(["user", "project", "local"]).optional(),
background: exports_external.boolean().optional(),
isolation: (process.env.USER_TYPE === "ant" ? exports_external.enum(["worktree", "remote"]) : exports_external.enum(["worktree"])).optional()
}));
AgentsJsonSchema = lazySchema(() => exports_external.record(exports_external.string(), AgentJsonSchema()));
getAgentDefinitionsWithOverrides = memoize_default(async (cwd2) => {
if (isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)) {
const builtInAgents = getBuiltInAgents();
return {
activeAgents: builtInAgents,
allAgents: builtInAgents
};
}
try {
const markdownFiles = await loadMarkdownFilesForSubdir("agents", cwd2);
const failedFiles = [];
const customAgents = markdownFiles.map(({ filePath, baseDir, frontmatter, content, source }) => {
const agent = parseAgentFromMarkdown(filePath, baseDir, frontmatter, content, source);
if (!agent) {
if (!frontmatter["name"]) {
return null;
}
const errorMsg = getParseError(frontmatter);
failedFiles.push({ path: filePath, error: errorMsg });
logForDebugging(`Failed to parse agent from ${filePath}: ${errorMsg}`);
logEvent("tengu_agent_parse_error", {
error: errorMsg,
location: source
});
return null;
}
return agent;
}).filter((agent) => agent !== null);
let pluginAgentsPromise = loadPluginAgents();
if (false) {}
const pluginAgents = await pluginAgentsPromise;
const builtInAgents = getBuiltInAgents();
const allAgentsList = [
...builtInAgents,
...pluginAgents,
...customAgents
];
const activeAgents = getActiveAgentsFromList(allAgentsList);
for (const agent of activeAgents) {
if (agent.color) {
setAgentColor(agent.agentType, agent.color);
}
}
return {
activeAgents,
allAgents: allAgentsList,
failedFiles: failedFiles.length > 0 ? failedFiles : undefined
};
} catch (error44) {
const errorMessage2 = error44 instanceof Error ? error44.message : String(error44);
logForDebugging(`Error loading agent definitions: ${errorMessage2}`);
logError2(error44);
const builtInAgents = getBuiltInAgents();
return {
activeAgents: builtInAgents,
allAgents: builtInAgents,
failedFiles: [{ path: "unknown", error: errorMessage2 }]
};
}
});
});
// src/tools/SkillTool/prompt.ts
var exports_prompt = {};
__export(exports_prompt, {
getSkillToolInfo: () => getSkillToolInfo,
getSkillInfo: () => getSkillInfo,
getPrompt: () => getPrompt,
getLimitedSkillToolCommands: () => getLimitedSkillToolCommands,
getCharBudget: () => getCharBudget,
formatCommandsWithinBudget: () => formatCommandsWithinBudget,
clearPromptCache: () => clearPromptCache,
SKILL_BUDGET_CONTEXT_PERCENT: () => SKILL_BUDGET_CONTEXT_PERCENT,
MAX_LISTING_DESC_CHARS: () => MAX_LISTING_DESC_CHARS,
DEFAULT_CHAR_BUDGET: () => DEFAULT_CHAR_BUDGET,
CHARS_PER_TOKEN: () => CHARS_PER_TOKEN
});
function getCharBudget(contextWindowTokens) {
if (Number(process.env.SLASH_COMMAND_TOOL_CHAR_BUDGET)) {
return Number(process.env.SLASH_COMMAND_TOOL_CHAR_BUDGET);
}
if (contextWindowTokens) {
return Math.floor(contextWindowTokens * CHARS_PER_TOKEN * SKILL_BUDGET_CONTEXT_PERCENT);
}
return DEFAULT_CHAR_BUDGET;
}
function getCommandDescription(cmd) {
const desc = cmd.whenToUse ? `${cmd.description} - ${cmd.whenToUse}` : cmd.description;
return desc.length > MAX_LISTING_DESC_CHARS ? desc.slice(0, MAX_LISTING_DESC_CHARS - 1) + "…" : desc;
}
function formatCommandDescription(cmd) {
const displayName = getCommandName(cmd);
if (cmd.name !== displayName && cmd.type === "prompt" && cmd.source === "plugin") {
logForDebugging(`Skill prompt: showing "${cmd.name}" (userFacingName="${displayName}")`);
}
return `- ${cmd.name}: ${getCommandDescription(cmd)}`;
}
function formatCommandsWithinBudget(commands, contextWindowTokens) {
if (commands.length === 0)
return "";
const budget = getCharBudget(contextWindowTokens);
const fullEntries = commands.map((cmd) => ({
cmd,
full: formatCommandDescription(cmd)
}));
const fullTotal = fullEntries.reduce((sum, e) => sum + stringWidth(e.full), 0) + (fullEntries.length - 1);
if (fullTotal <= budget) {
return fullEntries.map((e) => e.full).join(`
`);
}
const bundledIndices = new Set;
const restCommands = [];
for (let i3 = 0;i3 < commands.length; i3++) {
const cmd = commands[i3];
if (cmd.type === "prompt" && cmd.source === "bundled") {
bundledIndices.add(i3);
} else {
restCommands.push(cmd);
}
}
const bundledChars = fullEntries.reduce((sum, e, i3) => bundledIndices.has(i3) ? sum + stringWidth(e.full) + 1 : sum, 0);
const remainingBudget = budget - bundledChars;
if (restCommands.length === 0) {
return fullEntries.map((e) => e.full).join(`
`);
}
const restNameOverhead = restCommands.reduce((sum, cmd) => sum + stringWidth(cmd.name) + 4, 0) + (restCommands.length - 1);
const availableForDescs = remainingBudget - restNameOverhead;
const maxDescLen = Math.floor(availableForDescs / restCommands.length);
if (maxDescLen < MIN_DESC_LENGTH) {
if (process.env.USER_TYPE === "ant") {
logEvent("tengu_skill_descriptions_truncated", {
skill_count: commands.length,
budget,
full_total: fullTotal,
truncation_mode: "names_only",
max_desc_length: maxDescLen,
bundled_count: bundledIndices.size,
bundled_chars: bundledChars
});
}
return commands.map((cmd, i3) => bundledIndices.has(i3) ? fullEntries[i3].full : `- ${cmd.name}`).join(`
`);
}
const truncatedCount = count2(restCommands, (cmd) => stringWidth(getCommandDescription(cmd)) > maxDescLen);
if (process.env.USER_TYPE === "ant") {
logEvent("tengu_skill_descriptions_truncated", {
skill_count: commands.length,
budget,
full_total: fullTotal,
truncation_mode: "description_trimmed",
max_desc_length: maxDescLen,
truncated_count: truncatedCount,
bundled_count: bundledIndices.size,
bundled_chars: bundledChars
});
}
return commands.map((cmd, i3) => {
if (bundledIndices.has(i3))
return fullEntries[i3].full;
const description = getCommandDescription(cmd);
return `- ${cmd.name}: ${truncate(description, maxDescLen)}`;
}).join(`
`);
}
async function getSkillToolInfo(cwd2) {
const agentCommands = await getSkillToolCommands(cwd2);
return {
totalCommands: agentCommands.length,
includedCommands: agentCommands.length
};
}
function getLimitedSkillToolCommands(cwd2) {
return getSkillToolCommands(cwd2);
}
function clearPromptCache() {
getPrompt.cache?.clear?.();
}
async function getSkillInfo(cwd2) {
try {
const skills = await getSlashCommandToolSkills(cwd2);
return {
totalSkills: skills.length,
includedSkills: skills.length
};
} catch (error44) {
logError2(toError(error44));
return {
totalSkills: 0,
includedSkills: 0
};
}
}
var SKILL_BUDGET_CONTEXT_PERCENT = 0.01, CHARS_PER_TOKEN = 4, DEFAULT_CHAR_BUDGET = 8000, MAX_LISTING_DESC_CHARS = 250, MIN_DESC_LENGTH = 20, getPrompt;
var init_prompt6 = __esm(() => {
init_lodash();
init_commands2();
init_xml();
init_stringWidth();
init_analytics();
init_debug();
init_errors();
init_format();
init_log3();
getPrompt = memoize_default(async (_cwd) => {
return `Execute a skill within the main conversation
When users ask you to perform tasks, check if any of the available skills match. Skills provide specialized capabilities and domain knowledge.
When users reference a "slash command" or "/" (e.g., "/commit", "/review-pr"), they are referring to a skill. Use this tool to invoke it.
How to invoke:
- Use this tool with the skill name and optional arguments
- Examples:
- \`skill: "pdf"\` - invoke the pdf skill
- \`skill: "commit", args: "-m 'Fix bug'"\` - invoke with arguments
- \`skill: "review-pr", args: "123"\` - invoke with arguments
- \`skill: "ms-office-suite:pdf"\` - invoke using fully qualified name
Important:
- Available skills are listed in system-reminder messages in the conversation
- When a skill matches the user's request, this is a BLOCKING REQUIREMENT: invoke the relevant Skill tool BEFORE generating any other response about the task
- NEVER mention a skill without actually calling this tool
- Do not invoke a skill that is already running
- Do not use this tool for built-in CLI commands (like /help, /clear, etc.)
- If you see a <${COMMAND_NAME_TAG}> tag in the current conversation turn, the skill has ALREADY been loaded - follow the instructions directly instead of calling this tool again
`;
});
});
// src/constants/apiLimits.ts
var API_IMAGE_MAX_BASE64_SIZE, IMAGE_TARGET_RAW_SIZE, IMAGE_MAX_WIDTH = 2000, IMAGE_MAX_HEIGHT = 2000, PDF_TARGET_RAW_SIZE, API_PDF_MAX_PAGES = 100, PDF_EXTRACT_SIZE_THRESHOLD, PDF_MAX_EXTRACT_SIZE, PDF_MAX_PAGES_PER_READ = 20, PDF_AT_MENTION_INLINE_THRESHOLD = 10, API_MAX_MEDIA_PER_REQUEST = 100;
var init_apiLimits = __esm(() => {
API_IMAGE_MAX_BASE64_SIZE = 5 * 1024 * 1024;
IMAGE_TARGET_RAW_SIZE = API_IMAGE_MAX_BASE64_SIZE * 3 / 4;
PDF_TARGET_RAW_SIZE = 20 * 1024 * 1024;
PDF_EXTRACT_SIZE_THRESHOLD = 3 * 1024 * 1024;
PDF_MAX_EXTRACT_SIZE = 100 * 1024 * 1024;
});
// src/memdir/memoryAge.ts
function memoryAgeDays(mtimeMs) {
return Math.max(0, Math.floor((Date.now() - mtimeMs) / 86400000));
}
function memoryAge(mtimeMs) {
const d = memoryAgeDays(mtimeMs);
if (d === 0)
return "today";
if (d === 1)
return "yesterday";
return `${d} days ago`;
}
function memoryFreshnessText(mtimeMs) {
const d = memoryAgeDays(mtimeMs);
if (d <= 1)
return "";
return `This memory is ${d} days old. ` + `Memories are point-in-time observations, not live state — ` + `claims about code behavior or file:line citations may be outdated. ` + `Verify against current code before asserting as fact.`;
}
function memoryFreshnessNote(mtimeMs) {
const text = memoryFreshnessText(mtimeMs);
if (!text)
return "";
return `${text}
`;
}
// src/tools/ToolSearchTool/constants.ts
var TOOL_SEARCH_TOOL_NAME = "ToolSearch";
// src/tools/ToolSearchTool/prompt.ts
var exports_prompt2 = {};
__export(exports_prompt2, {
isDeferredTool: () => isDeferredTool,
getPrompt: () => getPrompt2,
formatDeferredToolLine: () => formatDeferredToolLine,
TOOL_SEARCH_TOOL_NAME: () => TOOL_SEARCH_TOOL_NAME
});
function getToolLocationHint() {
const deltaEnabled = process.env.USER_TYPE === "ant" || getFeatureValue_CACHED_MAY_BE_STALE("tengu_glacier_2xr", false);
return deltaEnabled ? "Deferred tools appear by name in messages." : "Deferred tools appear by name in messages.";
}
function isDeferredTool(tool) {
if (tool.alwaysLoad === true)
return false;
if (tool.isMcp === true)
return true;
if (tool.name === TOOL_SEARCH_TOOL_NAME)
return false;
if (false) {}
if (false) {}
if (false) {}
return tool.shouldDefer === true;
}
function formatDeferredToolLine(tool) {
return tool.name;
}
function getPrompt2() {
return PROMPT_HEAD + getToolLocationHint() + PROMPT_TAIL;
}
var PROMPT_HEAD = `Fetches full schema definitions for deferred tools so they can be called.
`, PROMPT_TAIL = ` Until fetched, only the name is known — there is no parameter schema, so the tool cannot be invoked. This tool takes a query, matches it against the deferred tool list, and returns the matched tools' complete JSONSchema definitions inside a block. Once a tool's schema appears in that result, it is callable exactly like any tool defined at the top of the prompt.
Result format: each matched tool appears as one {"description": "...", "name": "...", "parameters": {...}} line inside the 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/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 _a3;
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 = (_a3 = options.timeout) !== null && _a3 !== undefined ? _a3 : 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(path11, added, removed, oldPosInc, options) {
const last2 = path11.lastComponent;
if (last2 && !options.oneChangePerToken && last2.added === added && last2.removed === removed) {
return {
oldPos: path11.oldPos + oldPosInc,
lastComponent: { count: last2.count + 1, added, removed, previousComponent: last2.previousComponent }
};
} else {
return {
oldPos: path11.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 i3 = 0;i3 < array2.length; i3++) {
if (array2[i3]) {
ret.push(array2[i3]);
}
}
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, i3) {
const oldValue = oldTokens[oldPos + i3];
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/diff/libesm/util/string.js
function longestCommonPrefix(str1, str2) {
let i3;
for (i3 = 0;i3 < str1.length && i3 < str2.length; i3++) {
if (str1[i3] != str2[i3]) {
return str1.slice(0, i3);
}
}
return str1.slice(0, i3);
}
function longestCommonSuffix(str1, str2) {
let i3;
if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
return "";
}
for (i3 = 0;i3 < str1.length && i3 < str2.length; i3++) {
if (str1[str1.length - (i3 + 1)] != str2[str2.length - (i3 + 1)]) {
return str1.slice(-i3);
}
}
return str1.slice(-i3);
}
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 i3 = startA;i3 < a2.length; i3++) {
while (k > 0 && a2[i3] != b[k]) {
k = map3[k];
}
if (a2[i3] == b[k]) {
k++;
}
}
return k;
}
function segment(string4, segmenter3) {
const parts = [];
for (const segmentObj of Array.from(segmenter3.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, segmenter3) {
if (segmenter3) {
return leadingAndTrailingWs(string4, segmenter3)[1];
}
let i3;
for (i3 = string4.length - 1;i3 >= 0; i3--) {
if (!string4[i3].match(/\s/)) {
break;
}
}
return string4.substring(i3 + 1);
}
function leadingWs(string4, segmenter3) {
if (segmenter3) {
return leadingAndTrailingWs(string4, segmenter3)[0];
}
const match = string4.match(/^\s*/);
return match ? match[0] : "";
}
function leadingAndTrailingWs(string4, segmenter3) {
if (!segmenter3) {
return [leadingWs(string4), trailingWs(string4)];
}
if (segmenter3.resolvedOptions().granularity != "word") {
throw new Error('The segmenter passed must have a granularity of "word"');
}
const segments = segment(string4, segmenter3);
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/diff/libesm/diff/word.js
function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep, segmenter3) {
if (deletion && insertion) {
const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter3);
const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter3);
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, segmenter3);
insertion.value = insertion.value.substring(ws.length);
}
if (endKeep) {
const ws = leadingWs(endKeep.value, segmenter3);
endKeep.value = endKeep.value.substring(ws.length);
}
} else if (startKeep && endKeep) {
const newWsFull = leadingWs(endKeep.value, segmenter3), [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion.value, segmenter3);
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, segmenter3);
const deletionWsSuffix = trailingWs(deletion.value, segmenter3);
const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
deletion.value = removeSuffix(deletion.value, overlap);
} else if (startKeep) {
const startKeepWsSuffix = trailingWs(startKeep.value, segmenter3);
const deletionWsPrefix = leadingWs(deletion.value, segmenter3);
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 segmenter3 = options.intlSegmenter;
if (segmenter3.resolvedOptions().granularity != "word") {
throw new Error('The segmenter passed must have a granularity of "word"');
}
parts = segment(value, segmenter3);
} 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, i3) => {
if (i3 == 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/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 i3 = 0;i3 < linesAndNewlines.length; i3++) {
const line = linesAndNewlines[i3];
if (i3 % 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/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 i3 = 0;i3 < diff2.length; i3++) {
const current = diff2[i3], lines = current.lines || splitLines(current.value);
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
const prev = diff2[i3 - 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 && i3 < 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 i3 = 0;i3 < hunk.lines.length; i3++) {
if (hunk.lines[i3].endsWith(`
`)) {
hunk.lines[i3] = hunk.lines[i3].slice(0, -1);
} else {
hunk.lines.splice(i3 + 1, 0, "\\ No newline at end of file");
i3++;
}
}
}
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/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((m) => m.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/marked/lib/marked.esm.js
function _getDefaults() {
return {
async: false,
breaks: false,
extensions: null,
gfm: true,
hooks: null,
pedantic: false,
renderer: null,
silent: false,
tokenizer: null,
walkTokens: null
};
}
function changeDefaults(newDefaults) {
_defaults = newDefaults;
}
function edit(regex2, opt = "") {
let source = typeof regex2 === "string" ? regex2 : regex2.source;
const obj = {
replace: (name, val) => {
let valSource = typeof val === "string" ? val : val.source;
valSource = valSource.replace(other.caret, "$1");
source = source.replace(name, valSource);
return obj;
},
getRegex: () => {
return new RegExp(source, opt);
}
};
return obj;
}
function escape22(html2, encode3) {
if (encode3) {
if (other.escapeTest.test(html2)) {
return html2.replace(other.escapeReplace, getEscapeReplacement);
}
} else {
if (other.escapeTestNoEncode.test(html2)) {
return html2.replace(other.escapeReplaceNoEncode, getEscapeReplacement);
}
}
return html2;
}
function cleanUrl(href) {
try {
href = encodeURI(href).replace(other.percentDecode, "%");
} catch {
return null;
}
return href;
}
function splitCells(tableRow, count3) {
const row = tableRow.replace(other.findPipe, (match, offset, str) => {
let escaped = false;
let curr = offset;
while (--curr >= 0 && str[curr] === "\\")
escaped = !escaped;
if (escaped) {
return "|";
} else {
return " |";
}
}), cells = row.split(other.splitPipe);
let i3 = 0;
if (!cells[0].trim()) {
cells.shift();
}
if (cells.length > 0 && !cells.at(-1)?.trim()) {
cells.pop();
}
if (count3) {
if (cells.length > count3) {
cells.splice(count3);
} else {
while (cells.length < count3)
cells.push("");
}
}
for (;i3 < cells.length; i3++) {
cells[i3] = cells[i3].trim().replace(other.slashPipe, "|");
}
return cells;
}
function rtrim(str, c7, invert) {
const l = str.length;
if (l === 0) {
return "";
}
let suffLen = 0;
while (suffLen < l) {
const currChar = str.charAt(l - suffLen - 1);
if (currChar === c7 && !invert) {
suffLen++;
} else if (currChar !== c7 && invert) {
suffLen++;
} else {
break;
}
}
return str.slice(0, l - suffLen);
}
function findClosingBracket(str, b) {
if (str.indexOf(b[1]) === -1) {
return -1;
}
let level = 0;
for (let i3 = 0;i3 < str.length; i3++) {
if (str[i3] === "\\") {
i3++;
} else if (str[i3] === b[0]) {
level++;
} else if (str[i3] === b[1]) {
level--;
if (level < 0) {
return i3;
}
}
}
if (level > 0) {
return -2;
}
return -1;
}
function outputLink(cap, link22, raw, lexer2, rules) {
const href = link22.href;
const title = link22.title || null;
const text = cap[1].replace(rules.other.outputLinkReplace, "$1");
lexer2.state.inLink = true;
const token = {
type: cap[0].charAt(0) === "!" ? "image" : "link",
raw,
href,
title,
text,
tokens: lexer2.inlineTokens(text)
};
lexer2.state.inLink = false;
return token;
}
function indentCodeCompensation(raw, text, rules) {
const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);
if (matchIndentToCode === null) {
return text;
}
const indentToCode = matchIndentToCode[1];
return text.split(`
`).map((node) => {
const matchIndentInNode = node.match(rules.other.beginningSpace);
if (matchIndentInNode === null) {
return node;
}
const [indentInNode] = matchIndentInNode;
if (indentInNode.length >= indentToCode.length) {
return node.slice(indentToCode.length);
}
return node;
}).join(`
`);
}
function marked(src, opt) {
return markedInstance.parse(src, opt);
}
var _defaults, noopTest, other, newline, blockCode, fences, hr, heading, bullet, lheadingCore, lheading, lheadingGfm, _paragraph, blockText, _blockLabel, def, list, _tag = "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", _comment, html, paragraph, blockquote, blockNormal, gfmTable, blockGfm, blockPedantic, escape2, inlineCode, br, inlineText, _punctuation, _punctuationOrSpace, _notPunctuationOrSpace, punctuation, _punctuationGfmStrongEm, _punctuationOrSpaceGfmStrongEm, _notPunctuationOrSpaceGfmStrongEm, blockSkip, emStrongLDelimCore, emStrongLDelim, emStrongLDelimGfm, emStrongRDelimAstCore = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", emStrongRDelimAst, emStrongRDelimAstGfm, emStrongRDelimUnd, anyPunctuation, autolink, _inlineComment, tag, _inlineLabel, link2, reflink, nolink, reflinkSearch, inlineNormal, inlinePedantic, inlineGfm, inlineBreaks, block, inline, escapeReplacements, getEscapeReplacement = (ch2) => escapeReplacements[ch2], _Tokenizer = class {
options;
rules;
lexer;
constructor(options2) {
this.options = options2 || _defaults;
}
space(src) {
const cap = this.rules.block.newline.exec(src);
if (cap && cap[0].length > 0) {
return {
type: "space",
raw: cap[0]
};
}
}
code(src) {
const cap = this.rules.block.code.exec(src);
if (cap) {
const text = cap[0].replace(this.rules.other.codeRemoveIndent, "");
return {
type: "code",
raw: cap[0],
codeBlockStyle: "indented",
text: !this.options.pedantic ? rtrim(text, `
`) : text
};
}
}
fences(src) {
const cap = this.rules.block.fences.exec(src);
if (cap) {
const raw = cap[0];
const text = indentCodeCompensation(raw, cap[3] || "", this.rules);
return {
type: "code",
raw,
lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
text
};
}
}
heading(src) {
const cap = this.rules.block.heading.exec(src);
if (cap) {
let text = cap[2].trim();
if (this.rules.other.endingHash.test(text)) {
const trimmed = rtrim(text, "#");
if (this.options.pedantic) {
text = trimmed.trim();
} else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {
text = trimmed.trim();
}
}
return {
type: "heading",
raw: cap[0],
depth: cap[1].length,
text,
tokens: this.lexer.inline(text)
};
}
}
hr(src) {
const cap = this.rules.block.hr.exec(src);
if (cap) {
return {
type: "hr",
raw: rtrim(cap[0], `
`)
};
}
}
blockquote(src) {
const cap = this.rules.block.blockquote.exec(src);
if (cap) {
let lines = rtrim(cap[0], `
`).split(`
`);
let raw = "";
let text = "";
const tokens = [];
while (lines.length > 0) {
let inBlockquote = false;
const currentLines = [];
let i3;
for (i3 = 0;i3 < lines.length; i3++) {
if (this.rules.other.blockquoteStart.test(lines[i3])) {
currentLines.push(lines[i3]);
inBlockquote = true;
} else if (!inBlockquote) {
currentLines.push(lines[i3]);
} else {
break;
}
}
lines = lines.slice(i3);
const currentRaw = currentLines.join(`
`);
const currentText = currentRaw.replace(this.rules.other.blockquoteSetextReplace, `
$1`).replace(this.rules.other.blockquoteSetextReplace2, "");
raw = raw ? `${raw}
${currentRaw}` : currentRaw;
text = text ? `${text}
${currentText}` : currentText;
const top = this.lexer.state.top;
this.lexer.state.top = true;
this.lexer.blockTokens(currentText, tokens, true);
this.lexer.state.top = top;
if (lines.length === 0) {
break;
}
const lastToken = tokens.at(-1);
if (lastToken?.type === "code") {
break;
} else if (lastToken?.type === "blockquote") {
const oldToken = lastToken;
const newText = oldToken.raw + `
` + lines.join(`
`);
const newToken = this.blockquote(newText);
tokens[tokens.length - 1] = newToken;
raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
break;
} else if (lastToken?.type === "list") {
const oldToken = lastToken;
const newText = oldToken.raw + `
` + lines.join(`
`);
const newToken = this.list(newText);
tokens[tokens.length - 1] = newToken;
raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
lines = newText.substring(tokens.at(-1).raw.length).split(`
`);
continue;
}
}
return {
type: "blockquote",
raw,
tokens,
text
};
}
}
list(src) {
let cap = this.rules.block.list.exec(src);
if (cap) {
let bull = cap[1].trim();
const isordered = bull.length > 1;
const list2 = {
type: "list",
raw: "",
ordered: isordered,
start: isordered ? +bull.slice(0, -1) : "",
loose: false,
items: []
};
bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
if (this.options.pedantic) {
bull = isordered ? bull : "[*+-]";
}
const itemRegex = this.rules.other.listItemRegex(bull);
let endsWithBlankLine = false;
while (src) {
let endEarly = false;
let raw = "";
let itemContents = "";
if (!(cap = itemRegex.exec(src))) {
break;
}
if (this.rules.block.hr.test(src)) {
break;
}
raw = cap[0];
src = src.substring(raw.length);
let line = cap[2].split(`
`, 1)[0].replace(this.rules.other.listReplaceTabs, (t) => " ".repeat(3 * t.length));
let nextLine = src.split(`
`, 1)[0];
let blankLine = !line.trim();
let indent = 0;
if (this.options.pedantic) {
indent = 2;
itemContents = line.trimStart();
} else if (blankLine) {
indent = cap[1].length + 1;
} else {
indent = cap[2].search(this.rules.other.nonSpaceChar);
indent = indent > 4 ? 1 : indent;
itemContents = line.slice(indent);
indent += cap[1].length;
}
if (blankLine && this.rules.other.blankLine.test(nextLine)) {
raw += nextLine + `
`;
src = src.substring(nextLine.length + 1);
endEarly = true;
}
if (!endEarly) {
const nextBulletRegex = this.rules.other.nextBulletRegex(indent);
const hrRegex = this.rules.other.hrRegex(indent);
const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);
const headingBeginRegex = this.rules.other.headingBeginRegex(indent);
const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);
while (src) {
const rawLine = src.split(`
`, 1)[0];
let nextLineWithoutTabs;
nextLine = rawLine;
if (this.options.pedantic) {
nextLine = nextLine.replace(this.rules.other.listReplaceNesting, " ");
nextLineWithoutTabs = nextLine;
} else {
nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, " ");
}
if (fencesBeginRegex.test(nextLine)) {
break;
}
if (headingBeginRegex.test(nextLine)) {
break;
}
if (htmlBeginRegex.test(nextLine)) {
break;
}
if (nextBulletRegex.test(nextLine)) {
break;
}
if (hrRegex.test(nextLine)) {
break;
}
if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) {
itemContents += `
` + nextLineWithoutTabs.slice(indent);
} else {
if (blankLine) {
break;
}
if (line.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4) {
break;
}
if (fencesBeginRegex.test(line)) {
break;
}
if (headingBeginRegex.test(line)) {
break;
}
if (hrRegex.test(line)) {
break;
}
itemContents += `
` + nextLine;
}
if (!blankLine && !nextLine.trim()) {
blankLine = true;
}
raw += rawLine + `
`;
src = src.substring(rawLine.length + 1);
line = nextLineWithoutTabs.slice(indent);
}
}
if (!list2.loose) {
if (endsWithBlankLine) {
list2.loose = true;
} else if (this.rules.other.doubleBlankLine.test(raw)) {
endsWithBlankLine = true;
}
}
let istask = null;
let ischecked;
if (this.options.gfm) {
istask = this.rules.other.listIsTask.exec(itemContents);
if (istask) {
ischecked = istask[0] !== "[ ] ";
itemContents = itemContents.replace(this.rules.other.listReplaceTask, "");
}
}
list2.items.push({
type: "list_item",
raw,
task: !!istask,
checked: ischecked,
loose: false,
text: itemContents,
tokens: []
});
list2.raw += raw;
}
const lastItem = list2.items.at(-1);
if (lastItem) {
lastItem.raw = lastItem.raw.trimEnd();
lastItem.text = lastItem.text.trimEnd();
} else {
return;
}
list2.raw = list2.raw.trimEnd();
for (let i3 = 0;i3 < list2.items.length; i3++) {
this.lexer.state.top = false;
list2.items[i3].tokens = this.lexer.blockTokens(list2.items[i3].text, []);
if (!list2.loose) {
const spacers = list2.items[i3].tokens.filter((t) => t.type === "space");
const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t) => this.rules.other.anyLine.test(t.raw));
list2.loose = hasMultipleLineBreaks;
}
}
if (list2.loose) {
for (let i3 = 0;i3 < list2.items.length; i3++) {
list2.items[i3].loose = true;
}
}
return list2;
}
}
html(src) {
const cap = this.rules.block.html.exec(src);
if (cap) {
const token = {
type: "html",
block: true,
raw: cap[0],
pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
text: cap[0]
};
return token;
}
}
def(src) {
const cap = this.rules.block.def.exec(src);
if (cap) {
const tag2 = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " ");
const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
return {
type: "def",
tag: tag2,
raw: cap[0],
href,
title
};
}
}
table(src) {
const cap = this.rules.block.table.exec(src);
if (!cap) {
return;
}
if (!this.rules.other.tableDelimiter.test(cap[2])) {
return;
}
const headers = splitCells(cap[1]);
const aligns = cap[2].replace(this.rules.other.tableAlignChars, "").split("|");
const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [];
const item = {
type: "table",
raw: cap[0],
header: [],
align: [],
rows: []
};
if (headers.length !== aligns.length) {
return;
}
for (const align of aligns) {
if (this.rules.other.tableAlignRight.test(align)) {
item.align.push("right");
} else if (this.rules.other.tableAlignCenter.test(align)) {
item.align.push("center");
} else if (this.rules.other.tableAlignLeft.test(align)) {
item.align.push("left");
} else {
item.align.push(null);
}
}
for (let i3 = 0;i3 < headers.length; i3++) {
item.header.push({
text: headers[i3],
tokens: this.lexer.inline(headers[i3]),
header: true,
align: item.align[i3]
});
}
for (const row of rows) {
item.rows.push(splitCells(row, item.header.length).map((cell, i3) => {
return {
text: cell,
tokens: this.lexer.inline(cell),
header: false,
align: item.align[i3]
};
}));
}
return item;
}
lheading(src) {
const cap = this.rules.block.lheading.exec(src);
if (cap) {
return {
type: "heading",
raw: cap[0],
depth: cap[2].charAt(0) === "=" ? 1 : 2,
text: cap[1],
tokens: this.lexer.inline(cap[1])
};
}
}
paragraph(src) {
const cap = this.rules.block.paragraph.exec(src);
if (cap) {
const text = cap[1].charAt(cap[1].length - 1) === `
` ? cap[1].slice(0, -1) : cap[1];
return {
type: "paragraph",
raw: cap[0],
text,
tokens: this.lexer.inline(text)
};
}
}
text(src) {
const cap = this.rules.block.text.exec(src);
if (cap) {
return {
type: "text",
raw: cap[0],
text: cap[0],
tokens: this.lexer.inline(cap[0])
};
}
}
escape(src) {
const cap = this.rules.inline.escape.exec(src);
if (cap) {
return {
type: "escape",
raw: cap[0],
text: cap[1]
};
}
}
tag(src) {
const cap = this.rules.inline.tag.exec(src);
if (cap) {
if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {
this.lexer.state.inLink = true;
} else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {
this.lexer.state.inLink = false;
}
if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {
this.lexer.state.inRawBlock = true;
} else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {
this.lexer.state.inRawBlock = false;
}
return {
type: "html",
raw: cap[0],
inLink: this.lexer.state.inLink,
inRawBlock: this.lexer.state.inRawBlock,
block: false,
text: cap[0]
};
}
}
link(src) {
const cap = this.rules.inline.link.exec(src);
if (cap) {
const trimmedUrl = cap[2].trim();
if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {
if (!this.rules.other.endAngleBracket.test(trimmedUrl)) {
return;
}
const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
return;
}
} else {
const lastParenIndex = findClosingBracket(cap[2], "()");
if (lastParenIndex === -2) {
return;
}
if (lastParenIndex > -1) {
const start = cap[0].indexOf("!") === 0 ? 5 : 4;
const linkLen = start + cap[1].length + lastParenIndex;
cap[2] = cap[2].substring(0, lastParenIndex);
cap[0] = cap[0].substring(0, linkLen).trim();
cap[3] = "";
}
}
let href = cap[2];
let title = "";
if (this.options.pedantic) {
const link22 = this.rules.other.pedanticHrefTitle.exec(href);
if (link22) {
href = link22[1];
title = link22[3];
}
} else {
title = cap[3] ? cap[3].slice(1, -1) : "";
}
href = href.trim();
if (this.rules.other.startAngleBracket.test(href)) {
if (this.options.pedantic && !this.rules.other.endAngleBracket.test(trimmedUrl)) {
href = href.slice(1);
} else {
href = href.slice(1, -1);
}
}
return outputLink(cap, {
href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href,
title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
}, cap[0], this.lexer, this.rules);
}
}
reflink(src, links) {
let cap;
if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, " ");
const link22 = links[linkString.toLowerCase()];
if (!link22) {
const text = cap[0].charAt(0);
return {
type: "text",
raw: text,
text
};
}
return outputLink(cap, link22, cap[0], this.lexer, this.rules);
}
}
emStrong(src, maskedSrc, prevChar = "") {
let match = this.rules.inline.emStrongLDelim.exec(src);
if (!match)
return;
if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric))
return;
const nextChar = match[1] || match[2] || "";
if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
const lLength = [...match[0]].length - 1;
let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
const endReg = match[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
endReg.lastIndex = 0;
maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
while ((match = endReg.exec(maskedSrc)) != null) {
rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
if (!rDelim)
continue;
rLength = [...rDelim].length;
if (match[3] || match[4]) {
delimTotal += rLength;
continue;
} else if (match[5] || match[6]) {
if (lLength % 3 && !((lLength + rLength) % 3)) {
midDelimTotal += rLength;
continue;
}
}
delimTotal -= rLength;
if (delimTotal > 0)
continue;
rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
const lastCharLength = [...match[0]][0].length;
const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
if (Math.min(lLength, rLength) % 2) {
const text2 = raw.slice(1, -1);
return {
type: "em",
raw,
text: text2,
tokens: this.lexer.inlineTokens(text2)
};
}
const text = raw.slice(2, -2);
return {
type: "strong",
raw,
text,
tokens: this.lexer.inlineTokens(text)
};
}
}
}
codespan(src) {
const cap = this.rules.inline.code.exec(src);
if (cap) {
let text = cap[2].replace(this.rules.other.newLineCharGlobal, " ");
const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);
const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);
if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
text = text.substring(1, text.length - 1);
}
return {
type: "codespan",
raw: cap[0],
text
};
}
}
br(src) {
const cap = this.rules.inline.br.exec(src);
if (cap) {
return {
type: "br",
raw: cap[0]
};
}
}
del(src) {
const cap = this.rules.inline.del.exec(src);
if (cap) {
return {
type: "del",
raw: cap[0],
text: cap[2],
tokens: this.lexer.inlineTokens(cap[2])
};
}
}
autolink(src) {
const cap = this.rules.inline.autolink.exec(src);
if (cap) {
let text, href;
if (cap[2] === "@") {
text = cap[1];
href = "mailto:" + text;
} else {
text = cap[1];
href = text;
}
return {
type: "link",
raw: cap[0],
text,
href,
tokens: [
{
type: "text",
raw: text,
text
}
]
};
}
}
url(src) {
let cap;
if (cap = this.rules.inline.url.exec(src)) {
let text, href;
if (cap[2] === "@") {
text = cap[0];
href = "mailto:" + text;
} else {
let prevCapZero;
do {
prevCapZero = cap[0];
cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
} while (prevCapZero !== cap[0]);
text = cap[0];
if (cap[1] === "www.") {
href = "http://" + cap[0];
} else {
href = cap[0];
}
}
return {
type: "link",
raw: cap[0],
text,
href,
tokens: [
{
type: "text",
raw: text,
text
}
]
};
}
}
inlineText(src) {
const cap = this.rules.inline.text.exec(src);
if (cap) {
const escaped = this.lexer.state.inRawBlock;
return {
type: "text",
raw: cap[0],
text: cap[0],
escaped
};
}
}
}, _Lexer = class __Lexer {
tokens;
options;
state;
tokenizer;
inlineQueue;
constructor(options2) {
this.tokens = [];
this.tokens.links = /* @__PURE__ */ Object.create(null);
this.options = options2 || _defaults;
this.options.tokenizer = this.options.tokenizer || new _Tokenizer;
this.tokenizer = this.options.tokenizer;
this.tokenizer.options = this.options;
this.tokenizer.lexer = this;
this.inlineQueue = [];
this.state = {
inLink: false,
inRawBlock: false,
top: true
};
const rules = {
other,
block: block.normal,
inline: inline.normal
};
if (this.options.pedantic) {
rules.block = block.pedantic;
rules.inline = inline.pedantic;
} else if (this.options.gfm) {
rules.block = block.gfm;
if (this.options.breaks) {
rules.inline = inline.breaks;
} else {
rules.inline = inline.gfm;
}
}
this.tokenizer.rules = rules;
}
static get rules() {
return {
block,
inline
};
}
static lex(src, options2) {
const lexer2 = new __Lexer(options2);
return lexer2.lex(src);
}
static lexInline(src, options2) {
const lexer2 = new __Lexer(options2);
return lexer2.inlineTokens(src);
}
lex(src) {
src = src.replace(other.carriageReturn, `
`);
this.blockTokens(src, this.tokens);
for (let i3 = 0;i3 < this.inlineQueue.length; i3++) {
const next = this.inlineQueue[i3];
this.inlineTokens(next.src, next.tokens);
}
this.inlineQueue = [];
return this.tokens;
}
blockTokens(src, tokens = [], lastParagraphClipped = false) {
if (this.options.pedantic) {
src = src.replace(other.tabCharGlobal, " ").replace(other.spaceLine, "");
}
while (src) {
let token;
if (this.options.extensions?.block?.some((extTokenizer) => {
if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
src = src.substring(token.raw.length);
tokens.push(token);
return true;
}
return false;
})) {
continue;
}
if (token = this.tokenizer.space(src)) {
src = src.substring(token.raw.length);
const lastToken = tokens.at(-1);
if (token.raw.length === 1 && lastToken !== undefined) {
lastToken.raw += `
`;
} else {
tokens.push(token);
}
continue;
}
if (token = this.tokenizer.code(src)) {
src = src.substring(token.raw.length);
const lastToken = tokens.at(-1);
if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
lastToken.raw += `
` + token.raw;
lastToken.text += `
` + token.text;
this.inlineQueue.at(-1).src = lastToken.text;
} else {
tokens.push(token);
}
continue;
}
if (token = this.tokenizer.fences(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.heading(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.hr(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.blockquote(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.list(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.html(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.def(src)) {
src = src.substring(token.raw.length);
const lastToken = tokens.at(-1);
if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
lastToken.raw += `
` + token.raw;
lastToken.text += `
` + token.raw;
this.inlineQueue.at(-1).src = lastToken.text;
} else if (!this.tokens.links[token.tag]) {
this.tokens.links[token.tag] = {
href: token.href,
title: token.title
};
}
continue;
}
if (token = this.tokenizer.table(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.lheading(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
let cutSrc = src;
if (this.options.extensions?.startBlock) {
let startIndex = Infinity;
const tempSrc = src.slice(1);
let tempStart;
this.options.extensions.startBlock.forEach((getStartIndex) => {
tempStart = getStartIndex.call({ lexer: this }, tempSrc);
if (typeof tempStart === "number" && tempStart >= 0) {
startIndex = Math.min(startIndex, tempStart);
}
});
if (startIndex < Infinity && startIndex >= 0) {
cutSrc = src.substring(0, startIndex + 1);
}
}
if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
const lastToken = tokens.at(-1);
if (lastParagraphClipped && lastToken?.type === "paragraph") {
lastToken.raw += `
` + token.raw;
lastToken.text += `
` + token.text;
this.inlineQueue.pop();
this.inlineQueue.at(-1).src = lastToken.text;
} else {
tokens.push(token);
}
lastParagraphClipped = cutSrc.length !== src.length;
src = src.substring(token.raw.length);
continue;
}
if (token = this.tokenizer.text(src)) {
src = src.substring(token.raw.length);
const lastToken = tokens.at(-1);
if (lastToken?.type === "text") {
lastToken.raw += `
` + token.raw;
lastToken.text += `
` + token.text;
this.inlineQueue.pop();
this.inlineQueue.at(-1).src = lastToken.text;
} else {
tokens.push(token);
}
continue;
}
if (src) {
const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
if (this.options.silent) {
console.error(errMsg);
break;
} else {
throw new Error(errMsg);
}
}
}
this.state.top = true;
return tokens;
}
inline(src, tokens = []) {
this.inlineQueue.push({ src, tokens });
return tokens;
}
inlineTokens(src, tokens = []) {
let maskedSrc = src;
let match = null;
if (this.tokens.links) {
const links = Object.keys(this.tokens.links);
if (links.length > 0) {
while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
if (links.includes(match[0].slice(match[0].lastIndexOf("[") + 1, -1))) {
maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
}
}
}
}
while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
maskedSrc = maskedSrc.slice(0, match.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
}
while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
}
let keepPrevChar = false;
let prevChar = "";
while (src) {
if (!keepPrevChar) {
prevChar = "";
}
keepPrevChar = false;
let token;
if (this.options.extensions?.inline?.some((extTokenizer) => {
if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
src = src.substring(token.raw.length);
tokens.push(token);
return true;
}
return false;
})) {
continue;
}
if (token = this.tokenizer.escape(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.tag(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.link(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.reflink(src, this.tokens.links)) {
src = src.substring(token.raw.length);
const lastToken = tokens.at(-1);
if (token.type === "text" && lastToken?.type === "text") {
lastToken.raw += token.raw;
lastToken.text += token.text;
} else {
tokens.push(token);
}
continue;
}
if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.codespan(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.br(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.del(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (token = this.tokenizer.autolink(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
if (!this.state.inLink && (token = this.tokenizer.url(src))) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
}
let cutSrc = src;
if (this.options.extensions?.startInline) {
let startIndex = Infinity;
const tempSrc = src.slice(1);
let tempStart;
this.options.extensions.startInline.forEach((getStartIndex) => {
tempStart = getStartIndex.call({ lexer: this }, tempSrc);
if (typeof tempStart === "number" && tempStart >= 0) {
startIndex = Math.min(startIndex, tempStart);
}
});
if (startIndex < Infinity && startIndex >= 0) {
cutSrc = src.substring(0, startIndex + 1);
}
}
if (token = this.tokenizer.inlineText(cutSrc)) {
src = src.substring(token.raw.length);
if (token.raw.slice(-1) !== "_") {
prevChar = token.raw.slice(-1);
}
keepPrevChar = true;
const lastToken = tokens.at(-1);
if (lastToken?.type === "text") {
lastToken.raw += token.raw;
lastToken.text += token.text;
} else {
tokens.push(token);
}
continue;
}
if (src) {
const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
if (this.options.silent) {
console.error(errMsg);
break;
} else {
throw new Error(errMsg);
}
}
}
return tokens;
}
}, _Renderer = class {
options;
parser;
constructor(options2) {
this.options = options2 || _defaults;
}
space(token) {
return "";
}
code({ text, lang, escaped }) {
const langString = (lang || "").match(other.notSpaceStart)?.[0];
const code = text.replace(other.endingNewline, "") + `
`;
if (!langString) {
return "" + (escaped ? code : escape22(code, true)) + `
`;
}
return '' + (escaped ? code : escape22(code, true)) + `
`;
}
blockquote({ tokens }) {
const body = this.parser.parse(tokens);
return `
${body}
`;
}
html({ text }) {
return text;
}
heading({ tokens, depth }) {
return `${this.parser.parseInline(tokens)}
`;
}
hr(token) {
return `
`;
}
list(token) {
const ordered = token.ordered;
const start = token.start;
let body = "";
for (let j = 0;j < token.items.length; j++) {
const item = token.items[j];
body += this.listitem(item);
}
const type = ordered ? "ol" : "ul";
const startAttr = ordered && start !== 1 ? ' start="' + start + '"' : "";
return "<" + type + startAttr + `>
` + body + "" + type + `>
`;
}
listitem(item) {
let itemBody = "";
if (item.task) {
const checkbox = this.checkbox({ checked: !!item.checked });
if (item.loose) {
if (item.tokens[0]?.type === "paragraph") {
item.tokens[0].text = checkbox + " " + item.tokens[0].text;
if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
item.tokens[0].tokens[0].text = checkbox + " " + escape22(item.tokens[0].tokens[0].text);
item.tokens[0].tokens[0].escaped = true;
}
} else {
item.tokens.unshift({
type: "text",
raw: checkbox + " ",
text: checkbox + " ",
escaped: true
});
}
} else {
itemBody += checkbox + " ";
}
}
itemBody += this.parser.parse(item.tokens, !!item.loose);
return `${itemBody}
`;
}
checkbox({ checked }) {
return "';
}
paragraph({ tokens }) {
return `${this.parser.parseInline(tokens)}
`;
}
table(token) {
let header = "";
let cell = "";
for (let j = 0;j < token.header.length; j++) {
cell += this.tablecell(token.header[j]);
}
header += this.tablerow({ text: cell });
let body = "";
for (let j = 0;j < token.rows.length; j++) {
const row = token.rows[j];
cell = "";
for (let k = 0;k < row.length; k++) {
cell += this.tablecell(row[k]);
}
body += this.tablerow({ text: cell });
}
if (body)
body = `${body}`;
return `
` + header + `
` + body + `
`;
}
tablerow({ text }) {
return `
${text}
`;
}
tablecell(token) {
const content = this.parser.parseInline(token.tokens);
const type = token.header ? "th" : "td";
const tag2 = token.align ? `<${type} align="${token.align}">` : `<${type}>`;
return tag2 + content + `${type}>
`;
}
strong({ tokens }) {
return `${this.parser.parseInline(tokens)}`;
}
em({ tokens }) {
return `${this.parser.parseInline(tokens)}`;
}
codespan({ text }) {
return `${escape22(text, true)}`;
}
br(token) {
return "
";
}
del({ tokens }) {
return `${this.parser.parseInline(tokens)}`;
}
link({ href, title, tokens }) {
const text = this.parser.parseInline(tokens);
const cleanHref = cleanUrl(href);
if (cleanHref === null) {
return text;
}
href = cleanHref;
let out = '" + text + "";
return out;
}
image({ href, title, text, tokens }) {
if (tokens) {
text = this.parser.parseInline(tokens, this.parser.textRenderer);
}
const cleanHref = cleanUrl(href);
if (cleanHref === null) {
return escape22(text);
}
href = cleanHref;
let out = `
";
return out;
}
text(token) {
return "tokens" in token && token.tokens ? this.parser.parseInline(token.tokens) : ("escaped" in token) && token.escaped ? token.text : escape22(token.text);
}
}, _TextRenderer = class {
strong({ text }) {
return text;
}
em({ text }) {
return text;
}
codespan({ text }) {
return text;
}
del({ text }) {
return text;
}
html({ text }) {
return text;
}
text({ text }) {
return text;
}
link({ text }) {
return "" + text;
}
image({ text }) {
return "" + text;
}
br() {
return "";
}
}, _Parser = class __Parser {
options;
renderer;
textRenderer;
constructor(options2) {
this.options = options2 || _defaults;
this.options.renderer = this.options.renderer || new _Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
this.renderer.parser = this;
this.textRenderer = new _TextRenderer;
}
static parse(tokens, options2) {
const parser2 = new __Parser(options2);
return parser2.parse(tokens);
}
static parseInline(tokens, options2) {
const parser2 = new __Parser(options2);
return parser2.parseInline(tokens);
}
parse(tokens, top = true) {
let out = "";
for (let i3 = 0;i3 < tokens.length; i3++) {
const anyToken = tokens[i3];
if (this.options.extensions?.renderers?.[anyToken.type]) {
const genericToken = anyToken;
const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
out += ret || "";
continue;
}
}
const token = anyToken;
switch (token.type) {
case "space": {
out += this.renderer.space(token);
continue;
}
case "hr": {
out += this.renderer.hr(token);
continue;
}
case "heading": {
out += this.renderer.heading(token);
continue;
}
case "code": {
out += this.renderer.code(token);
continue;
}
case "table": {
out += this.renderer.table(token);
continue;
}
case "blockquote": {
out += this.renderer.blockquote(token);
continue;
}
case "list": {
out += this.renderer.list(token);
continue;
}
case "html": {
out += this.renderer.html(token);
continue;
}
case "paragraph": {
out += this.renderer.paragraph(token);
continue;
}
case "text": {
let textToken = token;
let body = this.renderer.text(textToken);
while (i3 + 1 < tokens.length && tokens[i3 + 1].type === "text") {
textToken = tokens[++i3];
body += `
` + this.renderer.text(textToken);
}
if (top) {
out += this.renderer.paragraph({
type: "paragraph",
raw: body,
text: body,
tokens: [{ type: "text", raw: body, text: body, escaped: true }]
});
} else {
out += body;
}
continue;
}
default: {
const errMsg = 'Token with "' + token.type + '" type was not found.';
if (this.options.silent) {
console.error(errMsg);
return "";
} else {
throw new Error(errMsg);
}
}
}
}
return out;
}
parseInline(tokens, renderer = this.renderer) {
let out = "";
for (let i3 = 0;i3 < tokens.length; i3++) {
const anyToken = tokens[i3];
if (this.options.extensions?.renderers?.[anyToken.type]) {
const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(anyToken.type)) {
out += ret || "";
continue;
}
}
const token = anyToken;
switch (token.type) {
case "escape": {
out += renderer.text(token);
break;
}
case "html": {
out += renderer.html(token);
break;
}
case "link": {
out += renderer.link(token);
break;
}
case "image": {
out += renderer.image(token);
break;
}
case "strong": {
out += renderer.strong(token);
break;
}
case "em": {
out += renderer.em(token);
break;
}
case "codespan": {
out += renderer.codespan(token);
break;
}
case "br": {
out += renderer.br(token);
break;
}
case "del": {
out += renderer.del(token);
break;
}
case "text": {
out += renderer.text(token);
break;
}
default: {
const errMsg = 'Token with "' + token.type + '" type was not found.';
if (this.options.silent) {
console.error(errMsg);
return "";
} else {
throw new Error(errMsg);
}
}
}
}
return out;
}
}, _Hooks, Marked = class {
defaults = _getDefaults();
options = this.setOptions;
parse = this.parseMarkdown(true);
parseInline = this.parseMarkdown(false);
Parser = _Parser;
Renderer = _Renderer;
TextRenderer = _TextRenderer;
Lexer = _Lexer;
Tokenizer = _Tokenizer;
Hooks = _Hooks;
constructor(...args) {
this.use(...args);
}
walkTokens(tokens, callback) {
let values2 = [];
for (const token of tokens) {
values2 = values2.concat(callback.call(this, token));
switch (token.type) {
case "table": {
const tableToken = token;
for (const cell of tableToken.header) {
values2 = values2.concat(this.walkTokens(cell.tokens, callback));
}
for (const row of tableToken.rows) {
for (const cell of row) {
values2 = values2.concat(this.walkTokens(cell.tokens, callback));
}
}
break;
}
case "list": {
const listToken = token;
values2 = values2.concat(this.walkTokens(listToken.items, callback));
break;
}
default: {
const genericToken = token;
if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
const tokens2 = genericToken[childTokens].flat(Infinity);
values2 = values2.concat(this.walkTokens(tokens2, callback));
});
} else if (genericToken.tokens) {
values2 = values2.concat(this.walkTokens(genericToken.tokens, callback));
}
}
}
}
return values2;
}
use(...args) {
const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
args.forEach((pack) => {
const opts = { ...pack };
opts.async = this.defaults.async || opts.async || false;
if (pack.extensions) {
pack.extensions.forEach((ext) => {
if (!ext.name) {
throw new Error("extension name required");
}
if ("renderer" in ext) {
const prevRenderer = extensions.renderers[ext.name];
if (prevRenderer) {
extensions.renderers[ext.name] = function(...args2) {
let ret = ext.renderer.apply(this, args2);
if (ret === false) {
ret = prevRenderer.apply(this, args2);
}
return ret;
};
} else {
extensions.renderers[ext.name] = ext.renderer;
}
}
if ("tokenizer" in ext) {
if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
throw new Error("extension level must be 'block' or 'inline'");
}
const extLevel = extensions[ext.level];
if (extLevel) {
extLevel.unshift(ext.tokenizer);
} else {
extensions[ext.level] = [ext.tokenizer];
}
if (ext.start) {
if (ext.level === "block") {
if (extensions.startBlock) {
extensions.startBlock.push(ext.start);
} else {
extensions.startBlock = [ext.start];
}
} else if (ext.level === "inline") {
if (extensions.startInline) {
extensions.startInline.push(ext.start);
} else {
extensions.startInline = [ext.start];
}
}
}
}
if ("childTokens" in ext && ext.childTokens) {
extensions.childTokens[ext.name] = ext.childTokens;
}
});
opts.extensions = extensions;
}
if (pack.renderer) {
const renderer = this.defaults.renderer || new _Renderer(this.defaults);
for (const prop in pack.renderer) {
if (!(prop in renderer)) {
throw new Error(`renderer '${prop}' does not exist`);
}
if (["options", "parser"].includes(prop)) {
continue;
}
const rendererProp = prop;
const rendererFunc = pack.renderer[rendererProp];
const prevRenderer = renderer[rendererProp];
renderer[rendererProp] = (...args2) => {
let ret = rendererFunc.apply(renderer, args2);
if (ret === false) {
ret = prevRenderer.apply(renderer, args2);
}
return ret || "";
};
}
opts.renderer = renderer;
}
if (pack.tokenizer) {
const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
for (const prop in pack.tokenizer) {
if (!(prop in tokenizer)) {
throw new Error(`tokenizer '${prop}' does not exist`);
}
if (["options", "rules", "lexer"].includes(prop)) {
continue;
}
const tokenizerProp = prop;
const tokenizerFunc = pack.tokenizer[tokenizerProp];
const prevTokenizer = tokenizer[tokenizerProp];
tokenizer[tokenizerProp] = (...args2) => {
let ret = tokenizerFunc.apply(tokenizer, args2);
if (ret === false) {
ret = prevTokenizer.apply(tokenizer, args2);
}
return ret;
};
}
opts.tokenizer = tokenizer;
}
if (pack.hooks) {
const hooks = this.defaults.hooks || new _Hooks;
for (const prop in pack.hooks) {
if (!(prop in hooks)) {
throw new Error(`hook '${prop}' does not exist`);
}
if (["options", "block"].includes(prop)) {
continue;
}
const hooksProp = prop;
const hooksFunc = pack.hooks[hooksProp];
const prevHook = hooks[hooksProp];
if (_Hooks.passThroughHooks.has(prop)) {
hooks[hooksProp] = (arg) => {
if (this.defaults.async) {
return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
return prevHook.call(hooks, ret2);
});
}
const ret = hooksFunc.call(hooks, arg);
return prevHook.call(hooks, ret);
};
} else {
hooks[hooksProp] = (...args2) => {
let ret = hooksFunc.apply(hooks, args2);
if (ret === false) {
ret = prevHook.apply(hooks, args2);
}
return ret;
};
}
}
opts.hooks = hooks;
}
if (pack.walkTokens) {
const walkTokens2 = this.defaults.walkTokens;
const packWalktokens = pack.walkTokens;
opts.walkTokens = function(token) {
let values2 = [];
values2.push(packWalktokens.call(this, token));
if (walkTokens2) {
values2 = values2.concat(walkTokens2.call(this, token));
}
return values2;
};
}
this.defaults = { ...this.defaults, ...opts };
});
return this;
}
setOptions(opt) {
this.defaults = { ...this.defaults, ...opt };
return this;
}
lexer(src, options2) {
return _Lexer.lex(src, options2 ?? this.defaults);
}
parser(tokens, options2) {
return _Parser.parse(tokens, options2 ?? this.defaults);
}
parseMarkdown(blockType) {
const parse22 = (src, options2) => {
const origOpt = { ...options2 };
const opt = { ...this.defaults, ...origOpt };
const throwError = this.onError(!!opt.silent, !!opt.async);
if (this.defaults.async === true && origOpt.async === false) {
return throwError(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 src === "undefined" || src === null) {
return throwError(new Error("marked(): input parameter is undefined or null"));
}
if (typeof src !== "string") {
return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
}
if (opt.hooks) {
opt.hooks.options = opt;
opt.hooks.block = blockType;
}
const lexer2 = opt.hooks ? opt.hooks.provideLexer() : blockType ? _Lexer.lex : _Lexer.lexInline;
const parser2 = opt.hooks ? opt.hooks.provideParser() : blockType ? _Parser.parse : _Parser.parseInline;
if (opt.async) {
return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser2(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
}
try {
if (opt.hooks) {
src = opt.hooks.preprocess(src);
}
let tokens = lexer2(src, opt);
if (opt.hooks) {
tokens = opt.hooks.processAllTokens(tokens);
}
if (opt.walkTokens) {
this.walkTokens(tokens, opt.walkTokens);
}
let html2 = parser2(tokens, opt);
if (opt.hooks) {
html2 = opt.hooks.postprocess(html2);
}
return html2;
} catch (e) {
return throwError(e);
}
};
return parse22;
}
onError(silent, async) {
return (e) => {
e.message += `
Please report this to https://github.com/markedjs/marked.`;
if (silent) {
const msg = "An error occurred:
" + escape22(e.message + "", true) + "
";
if (async) {
return Promise.resolve(msg);
}
return msg;
}
if (async) {
return Promise.reject(e);
}
throw e;
};
}
}, markedInstance, options, setOptions, use, walkTokens, parseInline, parser, lexer;
var init_marked_esm = __esm(() => {
_defaults = _getDefaults();
noopTest = { exec: () => null };
other = {
codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm,
outputLinkReplace: /\\([\[\]])/g,
indentCodeCompensation: /^(\s+)(?:```)/,
beginningSpace: /^\s+/,
endingHash: /#$/,
startingSpaceChar: /^ /,
endingSpaceChar: / $/,
nonSpaceChar: /[^ ]/,
newLineCharGlobal: /\n/g,
tabCharGlobal: /\t/g,
multipleSpaceGlobal: /\s+/g,
blankLine: /^[ \t]*$/,
doubleBlankLine: /\n[ \t]*\n[ \t]*$/,
blockquoteStart: /^ {0,3}>/,
blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g,
blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm,
listReplaceTabs: /^\t+/,
listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,
listIsTask: /^\[[ xX]\] /,
listReplaceTask: /^\[[ 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,
unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,
caret: /(^|[^\[])\^/g,
percentDecode: /%25/g,
findPipe: /\|/g,
splitPipe: / \|/,
slashPipe: /\\\|/g,
carriageReturn: /\r\n|\r/g,
spaceLine: /^ +$/gm,
notSpaceStart: /^\S*/,
endingNewline: /\n$/,
listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),
nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),
hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),
fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`),
headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),
htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, "i")
};
newline = /^(?:[ \t]*(?:\n|$))+/;
blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
bullet = /(?:[*+-]|\d{1,9}[.)])/;
lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
lheading = edit(lheadingCore).replace(/bull/g, bullet).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();
lheadingGfm = edit(lheadingCore).replace(/bull/g, bullet).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();
_paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
blockText = /^[^\n]+/;
_blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
_comment = /|$))/;
html = edit("^ {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", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
paragraph = edit(_paragraph).replace("hr", hr).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[.)]) ").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
blockNormal = {
blockquote,
code: blockCode,
def,
fences,
heading,
hr,
html,
lheading,
list,
newline,
paragraph,
table: noopTest,
text: blockText
};
gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).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[.)]) ").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
blockGfm = {
...blockNormal,
lheading: lheadingGfm,
table: gfmTable,
paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex()
};
blockPedantic = {
...blockNormal,
html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?\\1> *(?:\\n{2,}|\\s*$)| \\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _comment).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: noopTest,
lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
paragraph: edit(_paragraph).replace("hr", hr).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
};
escape2 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
br = /^( {2,}|\\)\n(?!\s*$)/;
inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g;
emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/;
emStrongLDelim = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuation).getRegex();
emStrongLDelimGfm = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuationGfmStrongEm).getRegex();
emStrongRDelimAst = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm).replace(/punct/g, _punctuationGfmStrongEm).getRegex();
emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
anyPunctuation = edit(/\\(punct)/, "gu").replace(/punct/g, _punctuation).getRegex();
autolink = edit(/^<(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();
_inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
tag = edit("^comment|^[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
_inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
link2 = edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
inlineNormal = {
_backpedal: noopTest,
anyPunctuation,
autolink,
blockSkip,
br,
code: inlineCode,
del: noopTest,
emStrongLDelim,
emStrongRDelimAst,
emStrongRDelimUnd,
escape: escape2,
link: link2,
nolink,
punctuation,
reflink,
reflinkSearch,
tag,
text: inlineText,
url: noopTest
};
inlinePedantic = {
...inlineNormal,
link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
};
inlineGfm = {
...inlineNormal,
emStrongRDelimAst: emStrongRDelimAstGfm,
emStrongLDelim: emStrongLDelimGfm,
url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").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~\\]))\1(?=[^~]|$)/,
text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\": ">",
'"': """,
"'": "'"
};
_Hooks = class {
options;
block;
constructor(options2) {
this.options = options2 || _defaults;
}
static passThroughHooks = /* @__PURE__ */ new Set([
"preprocess",
"postprocess",
"processAllTokens"
]);
preprocess(markdown) {
return markdown;
}
postprocess(html2) {
return html2;
}
processAllTokens(tokens) {
return tokens;
}
provideLexer() {
return this.block ? _Lexer.lex : _Lexer.lexInline;
}
provideParser() {
return this.block ? _Parser.parse : _Parser.parseInline;
}
};
markedInstance = new Marked;
marked.options = marked.setOptions = function(options2) {
markedInstance.setOptions(options2);
marked.defaults = markedInstance.defaults;
changeDefaults(marked.defaults);
return marked;
};
marked.getDefaults = _getDefaults;
marked.defaults = _defaults;
marked.use = function(...args) {
markedInstance.use(...args);
marked.defaults = markedInstance.defaults;
changeDefaults(marked.defaults);
return marked;
};
marked.walkTokens = function(tokens, callback) {
return markedInstance.walkTokens(tokens, callback);
};
marked.parseInline = markedInstance.parseInline;
marked.Parser = _Parser;
marked.parser = _Parser.parse;
marked.Renderer = _Renderer;
marked.TextRenderer = _TextRenderer;
marked.Lexer = _Lexer;
marked.lexer = _Lexer.lex;
marked.Tokenizer = _Tokenizer;
marked.Hooks = _Hooks;
marked.parse = marked;
options = marked.options;
setOptions = marked.setOptions;
use = marked.use;
walkTokens = marked.walkTokens;
parseInline = marked.parseInline;
parser = _Parser.parse;
lexer = _Lexer.lex;
});
// node_modules/picomatch/lib/constants.js
var require_constants9 = __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/picomatch/lib/utils.js
var require_utils2 = __commonJS((exports) => {
var {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = require_constants9();
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 platform2 = navigator.platform.toLowerCase();
return platform2 === "win32" || platform2 === "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, state = {}) => {
let output = input;
if (output.startsWith("./")) {
output = output.slice(2);
state.prefix = "./";
}
return output;
};
exports.wrapOutput = (input, state = {}, options2 = {}) => {
const prepend = options2.contains ? "" : "^";
const append2 = options2.contains ? "" : "$";
let output = `${prepend}(?:${input})${append2}`;
if (state.negated === true) {
output = `(?:^(?!${output}).*$)`;
}
return output;
};
exports.basename = (path11, { windows: windows2 } = {}) => {
const segs = path11.split(windows2 ? /[\\/]/ : "/");
const last2 = segs[segs.length - 1];
if (last2 === "") {
return segs[segs.length - 2];
}
return last2;
};
});
// node_modules/picomatch/lib/scan.js
var require_scan = __commonJS((exports, module) => {
var utils = require_utils2();
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_constants9();
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, options2) => {
const opts = options2 || {};
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 state = {
prefix,
input,
start,
base: base2,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) {
tokens.push(token);
}
state.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 i3 = slashes[idx];
const value = input.slice(n2, i3);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== "") {
parts.push(value);
}
prevIndex = i3;
}
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]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan;
});
// node_modules/picomatch/lib/parse.js
var require_parse4 = __commonJS((exports, module) => {
var constants4 = require_constants9();
var utils = require_utils2();
var {
MAX_LENGTH,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants4;
var expandRange = (args, options2) => {
if (typeof options2.expandRange === "function") {
return options2.expandRange(...args, options2);
}
args.sort();
const value = `[${args.join("-")}]`;
try {
new RegExp(value);
} catch (ex) {
return args.map((v) => utils.escapeRegex(v)).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 i3 = 0;i3 < values2.length; i3++) {
for (let j = i3 + 1;j < values2.length; j++) {
const a2 = values2[i3];
const b = values2[j];
const char = a2[0];
if (!char || a2 !== char.repeat(a2.length) || b !== char.repeat(b.length)) {
continue;
}
if (a2 === b || a2.startsWith(b) || b.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 i3 = 1;i3 < pattern.length; i3++) {
const ch2 = pattern[i3];
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 && i3 !== pattern.length - 1) {
return;
}
return {
type: pattern[0],
body: pattern.slice(2, i3),
end: i3
};
}
}
}
};
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, options2) => {
if (options2.maxExtglobRecursion === false) {
return { risky: false };
}
const max2 = typeof options2.maxExtglobRecursion === "number" ? options2.maxExtglobRecursion : constants4.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 parse7 = (input, options2) => {
if (typeof input !== "string") {
throw new TypeError("Expected a string");
}
input = REPLACEMENTS[input] || input;
const opts = { ...options2 };
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 = constants4.globChars(opts.windows);
const EXTGLOB_CHARS = constants4.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 state = {
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, state);
len = input.length;
const extglobs = [];
const braces = [];
const stack = [];
let prev = bos;
let value;
const eos = () => state.index === len - 1;
const peek = state.peek = (n2 = 1) => input[state.index + n2];
const advance = state.advance = () => input[++state.index] || "";
const remaining = () => input.slice(state.index + 1);
const consume = (value2 = "", num = 0) => {
state.consumed += value2;
state.index += num;
};
const append2 = (token) => {
state.output += token.output != null ? token.output : token.value;
consume(token.value);
};
const negate = () => {
let count3 = 1;
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
advance();
state.start++;
count3++;
}
if (count3 % 2 === 0) {
return false;
}
state.negated = true;
state.start++;
return true;
};
const increment2 = (type) => {
state[type]++;
stack.push(type);
};
const decrement = (type) => {
state[type]--;
stack.pop();
};
const push = (tok) => {
if (prev.type === "globstar") {
const isBrace = state.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) {
state.output = state.output.slice(0, -prev.output.length);
prev.type = "star";
prev.value = "*";
prev.output = star;
state.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 = state.parens;
token.output = state.output;
token.startIndex = state.index;
token.tokensIndex = tokens.length;
const output = (opts.capture ? "(" : "") + token.open;
increment2("parens");
push({ type, value: value2, output: state.output ? "" : ONE_CHAR });
push({ type: "paren", extglob: true, value: advance(), output });
extglobs.push(token);
};
const extglobClose = (token) => {
const literal2 = input.slice(token.startIndex, state.index + 1);
const body = input.slice(token.startIndex + 2, state.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 open5 = tokens[token.tokensIndex];
open5.type = "text";
open5.value = literal2;
open5.output = safeOutput || utils.escapeRegex(literal2);
for (let i3 = token.tokensIndex + 1;i3 < tokens.length; i3++) {
tokens[i3].value = "";
tokens[i3].output = "";
delete tokens[i3].suffix;
}
state.output = token.output + open5.output;
state.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 = parse7(rest, { ...options2, fastpaths: false }).output;
output = token.close = `)${expression})${extglobStar})`;
}
if (token.prev.type === "bos") {
state.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, (m, esc2, chars, first, rest, index) => {
if (first === "\\") {
backslashes = true;
return m;
}
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 ? m : `\\${m}`;
});
if (backslashes === true) {
if (opts.unescape === true) {
output = output.replace(/\\/g, "");
} else {
output = output.replace(/\\+/g, (m) => {
return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
});
}
}
if (output === input && opts.contains === true) {
state.output = input;
return state;
}
state.output = utils.wrapOutput(output, state, options2);
return state;
}
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;
state.index += slashes;
if (slashes % 2 !== 0) {
value += "\\";
}
}
if (opts.unescape === true) {
value = advance();
} else {
value += advance();
}
if (state.brackets === 0) {
push({ type: "text", value });
continue;
}
}
if (state.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;
state.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 (state.quotes === 1 && value !== '"') {
value = utils.escapeRegex(value);
prev.value += value;
append2({ value });
continue;
}
if (value === '"') {
state.quotes = state.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 (state.parens === 0 && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("opening", "("));
}
const extglob = extglobs[extglobs.length - 1];
if (extglob && state.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
}
push({ type: "paren", value, output: state.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 (state.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);
state.output = state.output.slice(0, -prev.value.length);
if (opts.literalBrackets === true) {
state.output += escaped;
prev.value = escaped;
continue;
}
prev.value = `(${capture}${escaped}|${prev.value})`;
state.output += prev.value;
continue;
}
if (value === "{" && opts.nobrace !== true) {
increment2("braces");
const open5 = {
type: "brace",
value,
output: "(",
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces.push(open5);
push(open5);
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 i3 = arr.length - 1;i3 >= 0; i3--) {
tokens.pop();
if (arr[i3].type === "brace") {
break;
}
if (arr[i3].type !== "dots") {
range.unshift(arr[i3].value);
}
}
output = expandRange(range, opts);
state.backtrack = true;
}
if (brace.comma !== true && brace.dots !== true) {
const out = state.output.slice(0, brace.outputIndex);
const toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = "\\{";
value = output = "\\}";
state.output = out;
for (const t of toks) {
state.output += t.output || t.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" && state.index === state.start + 1) {
state.start = state.index + 1;
state.consumed = "";
state.output = "";
tokens.pop();
prev = bos;
continue;
}
push({ type: "slash", value, output: SLASH_LITERAL });
continue;
}
if (value === ".") {
if (state.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 (state.braces + state.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 && state.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") || state.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];
state.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;
state.backtrack = true;
state.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 = state.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[state.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);
state.output = prev.output;
state.globstar = true;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
prev.value += value;
state.globstar = true;
state.output += prior.output + prev.output;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
const end = rest[1] !== undefined ? "|$" : "";
state.output = state.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;
state.output += prior.output + prev.output;
state.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})`;
state.output = prev.output;
state.globstar = true;
consume(value + advance());
push({ type: "slash", value: "/", output: "" });
continue;
}
state.output = state.output.slice(0, -prev.output.length);
prev.type = "globstar";
prev.output = globstar(opts);
prev.value += value;
state.output += prev.output;
state.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 (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
if (prev.type === "dot") {
state.output += NO_DOT_SLASH;
prev.output += NO_DOT_SLASH;
} else if (opts.dot === true) {
state.output += NO_DOTS_SLASH;
prev.output += NO_DOTS_SLASH;
} else {
state.output += nodot;
prev.output += nodot;
}
if (peek() !== "*") {
state.output += ONE_CHAR;
prev.output += ONE_CHAR;
}
}
push(token);
}
while (state.brackets > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", "]"));
state.output = utils.escapeLast(state.output, "[");
decrement("brackets");
}
while (state.parens > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", ")"));
state.output = utils.escapeLast(state.output, "(");
decrement("parens");
}
while (state.braces > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", "}"));
state.output = utils.escapeLast(state.output, "{");
decrement("braces");
}
if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` });
}
if (state.backtrack === true) {
state.output = "";
for (const token of state.tokens) {
state.output += token.output != null ? token.output : token.value;
if (token.suffix) {
state.output += token.suffix;
}
}
}
return state;
};
parse7.fastpaths = (input, options2) => {
const opts = { ...options2 };
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
} = constants4.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 state = { 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, state);
let source = create(output);
if (source && opts.strictSlashes !== true) {
source += `${SLASH_LITERAL}?`;
}
return source;
};
module.exports = parse7;
});
// node_modules/picomatch/lib/picomatch.js
var require_picomatch = __commonJS((exports, module) => {
var scan = require_scan();
var parse7 = require_parse4();
var utils = require_utils2();
var constants4 = require_constants9();
var isObject5 = (val) => val && typeof val === "object" && !Array.isArray(val);
var picomatch = (glob, options2, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map((input) => picomatch(input, options2, returnState));
const arrayMatcher = (str) => {
for (const isMatch of fns) {
const state2 = isMatch(str);
if (state2)
return state2;
}
return false;
};
return arrayMatcher;
}
const isState = isObject5(glob) && glob.tokens && glob.input;
if (glob === "" || typeof glob !== "string" && !isState) {
throw new TypeError("Expected pattern to be a non-empty string");
}
const opts = options2 || {};
const posix = opts.windows;
const regex2 = isState ? picomatch.compileRe(glob, options2) : picomatch.makeRe(glob, options2, false, true);
const state = regex2.state;
delete regex2.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options2, 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, options2, { glob, posix });
const result = { glob, state, 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 = state;
}
return matcher;
};
picomatch.test = (input, regex2, options2, { glob, posix } = {}) => {
if (typeof input !== "string") {
throw new TypeError("Expected input to be a string");
}
if (input === "") {
return { isMatch: false, output: "" };
}
const opts = options2 || {};
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, options2, posix);
} else {
match = regex2.exec(output);
}
}
return { isMatch: Boolean(match), match, output };
};
picomatch.matchBase = (input, glob, options2) => {
const regex2 = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options2);
return regex2.test(utils.basename(input));
};
picomatch.isMatch = (str, patterns, options2) => picomatch(patterns, options2)(str);
picomatch.parse = (pattern, options2) => {
if (Array.isArray(pattern))
return pattern.map((p) => picomatch.parse(p, options2));
return parse7(pattern, { ...options2, fastpaths: false });
};
picomatch.scan = (input, options2) => scan(input, options2);
picomatch.compileRe = (state, options2, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state.output;
}
const opts = options2 || {};
const prepend = opts.contains ? "" : "^";
const append2 = opts.contains ? "" : "$";
let source = `${prepend}(?:${state.output})${append2}`;
if (state && state.negated === true) {
source = `^(?!${source}).*$`;
}
const regex2 = picomatch.toRegex(source, options2);
if (returnState === true) {
regex2.state = state;
}
return regex2;
};
picomatch.makeRe = (input, options2 = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== "string") {
throw new TypeError("Expected a non-empty string");
}
let parsed = { negated: false, fastpaths: true };
if (options2.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
parsed.output = parse7.fastpaths(input, options2);
}
if (!parsed.output) {
parsed = parse7(input, options2);
}
return picomatch.compileRe(parsed, options2, returnOutput, returnState);
};
picomatch.toRegex = (source, options2) => {
try {
const opts = options2 || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err2) {
if (options2 && options2.debug === true)
throw err2;
return /$^/;
}
};
picomatch.constants = constants4;
module.exports = picomatch;
});
// node_modules/picomatch/index.js
var require_picomatch2 = __commonJS((exports, module) => {
var pico = require_picomatch();
var utils = require_utils2();
function picomatch(glob, options2, returnState = false) {
if (options2 && (options2.windows === null || options2.windows === undefined)) {
options2 = { ...options2, windows: utils.isWindows() };
}
return pico(glob, options2, 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 basename9,
dirname as dirname19,
extname as extname4,
isAbsolute as isAbsolute8,
join as join35,
parse as parse7,
relative as relative5,
sep as sep8
} from "path";
function pathInOriginalCwd(path11) {
return pathInWorkingPath(path11, getOriginalCwd());
}
function parseFrontmatterPaths(rawContent) {
const { frontmatter, content } = parseFrontmatter(rawContent);
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(rawContent, 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(rawContent);
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 fs2 = 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 = fs2.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 fs2 = getFsImplementation();
const { resolvedPath: resolvedRulesDir, isSymlink } = safeResolvePath(fs2, rulesDir);
visitedDirs.add(rulesDir);
if (isSymlink) {
visitedDirs.add(resolvedRulesDir);
}
const result = [];
let entries;
try {
entries = await fs2.readdir(resolvedRulesDir);
} catch (e) {
const code = getErrnoCode(e);
if (code === "ENOENT" || code === "EACCES" || code === "ENOTDIR") {
return [];
}
throw e;
}
for (const entry of entries) {
const entryPath = join35(rulesDir, entry.name);
const { resolvedPath: resolvedEntryPath, isSymlink: isSymlink2 } = safeResolvePath(fs2, entryPath);
const stats = isSymlink2 ? await fs2.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((f) => conditionalRule ? f.globs : !f.globs));
}
}
return result;
} catch (error44) {
if (error44 instanceof Error && error44.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((f) => f.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((f) => f.type !== "AutoMem" && f.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 = join35(dir, "CLAUDE.md");
result.push(...await processMemoryFile(projectPath, "Project", processedPaths, false));
const dotClaudePath = join35(dir, ".claude", "CLAUDE.md");
result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, false));
}
if (isSettingSourceEnabled("localSettings")) {
const localPath = join35(dir, "CLAUDE.local.md");
result.push(...await processMemoryFile(localPath, "Local", processedPaths, false));
}
const rulesDir = join35(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 path11 of unconditionalProcessedPaths) {
processedPaths.add(path11);
}
return result;
}
async function getConditionalRulesForCwdLevelDirectory(dir, targetPath, processedPaths) {
const rulesDir = join35(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_config();
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 !== parse7(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 = join35(dir, "CLAUDE.md");
result.push(...await processMemoryFile(projectPath, "Project", processedPaths, includeExternal));
const dotClaudePath = join35(dir, ".claude", "CLAUDE.md");
result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, includeExternal));
const rulesDir = join35(dir, ".claude", "rules");
result.push(...await processMdRules({
rulesDir,
type: "Project",
processedPaths,
includeExternal,
conditionalRule: false
}));
}
if (isSettingSourceEnabled("localSettings")) {
const localPath = join35(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 = join35(dir, "CLAUDE.md");
result.push(...await processMemoryFile(projectPath, "Project", processedPaths, includeExternal));
const dotClaudePath = join35(dir, ".claude", "CLAUDE.md");
result.push(...await processMemoryFile(dotClaudePath, "Project", processedPaths, includeExternal));
const rulesDir = join35(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, f) => sum + f.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 f of result) {
typeCounts[f.type] = (typeCounts[f.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, log2, 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:
${log2}`
].join(`
`);
} catch (error44) {
logForDiagnosticsNoPII("error", "git_status_failed", {
duration_ms: Date.now() - startTime
});
logError2(error44);
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 i3 = messages.length - 1;
while (i3 >= 0) {
const message = messages[i3];
const usage = message ? getTokenUsage(message) : undefined;
if (usage) {
return getTokenCountFromUsage(usage);
}
i3--;
}
return 0;
}
function finalContextTokensFromLastResponse(messages) {
let i3 = messages.length - 1;
while (i3 >= 0) {
const message = messages[i3];
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;
}
i3--;
}
return 0;
}
function getCurrentUsage(messages) {
for (let i3 = messages.length - 1;i3 >= 0; i3--) {
const message = messages[i3];
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((m) => m.type === "assistant");
if (!lastAsst)
return false;
const usage = getTokenUsage(lastAsst);
return usage ? getTokenCountFromUsage(usage) > THRESHOLD : false;
}
function getAssistantMessageContentLength(message) {
let contentLength = 0;
for (const block2 of message.message.content) {
if (block2.type === "text") {
contentLength += block2.text.length;
} else if (block2.type === "thinking") {
contentLength += block2.thinking.length;
} else if (block2.type === "redacted_thinking") {
contentLength += block2.data.length;
} else if (block2.type === "tool_use") {
contentLength += jsonStringify(block2.input).length;
}
}
return contentLength;
}
function tokenCountWithEstimation(messages) {
let i3 = messages.length - 1;
while (i3 >= 0) {
const message = messages[i3];
const usage = message ? getTokenUsage(message) : undefined;
if (message && usage) {
const responseId = getAssistantMessageId(message);
if (responseId) {
let j = i3 - 1;
while (j >= 0) {
const prior = messages[j];
const priorId = prior ? getAssistantMessageId(prior) : undefined;
if (priorId === responseId) {
i3 = j;
} else if (priorId !== undefined) {
break;
}
j--;
}
}
return getTokenCountFromUsage(usage) + roughTokenCountEstimationForMessages(messages.slice(i3 + 1));
}
i3--;
}
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 fs2 = getFsImplementation();
const memoryPath = getSessionMemoryPath();
try {
const content = await fs2.readFile(memoryPath, { encoding: "utf-8" });
logEvent("tengu_session_memory_loaded", {
content_length: content.length
});
return content;
} catch (e) {
if (isFsInaccessible(e))
return null;
throw e;
}
}
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/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/lodash-es/_baseIsNaN.js
function baseIsNaN(value) {
return value !== value;
}
var _baseIsNaN_default;
var init__baseIsNaN = __esm(() => {
_baseIsNaN_default = baseIsNaN;
});
// 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/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/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/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/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/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/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((t) => t.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(name) {
if (name.startsWith("mcp__")) {
const withoutPrefix = name.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 = name.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((t) => t.name.toLowerCase() === queryLower) ?? tools.find((t) => t.name.toLowerCase() === queryLower);
if (exactMatch) {
return [exactMatch.name];
}
if (queryLower.startsWith("mcp__") && queryLower.length > 5) {
const prefixMatches = deferredTools.filter((t) => t.name.toLowerCase().startsWith(queryLower)).slice(0, maxResults).map((t) => t.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((t) => t !== 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, b) => b.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((c7) => c7.type === "pending");
return pending.length > 0 ? pending.map((s) => s.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((s) => s.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((name) => ({
type: "tool_reference",
tool_name: name
}))
};
}
});
});
// 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((block2) => processBlock(block2, msg, stats, toolIdsToToolNames, readToolIdToFilePath, fileReadStats));
}
});
fileReadStats.forEach((data, path11) => {
if (data.count > 1) {
const averageTokensPerRead = Math.floor(data.totalTokens / data.count);
const duplicateTokens = averageTokensPerRead * (data.count - 1);
stats.duplicateFileReads.set(path11, {
count: data.count,
tokens: duplicateTokens
});
}
});
return stats;
}
function processBlock(block2, message, stats, toolIds, readToolPaths, fileReads) {
const tokens = roughTokenCountEstimation(jsonStringify(block2));
stats.total += tokens;
switch (block2.type) {
case "text":
if (message.type === "user" && "text" in block2 && block2.text.includes("local-command-stdout")) {
stats.localCommandOutputs += tokens;
} else {
stats[message.type === "user" ? "humanMessages" : "assistantMessages"] += tokens;
}
break;
case "tool_use": {
if ("name" in block2 && "id" in block2) {
const toolName = block2.name || "unknown";
increment2(stats.toolRequests, toolName, tokens);
toolIds.set(block2.id, toolName);
if (toolName === "Read" && "input" in block2 && block2.input && typeof block2.input === "object" && "file_path" in block2.input) {
const path11 = String(block2.input.file_path);
readToolPaths.set(block2.id, path11);
}
}
break;
}
case "tool_result": {
if ("tool_use_id" in block2) {
const toolName = toolIds.get(block2.tool_use_id) || "unknown";
increment2(stats.toolResults, toolName, tokens);
if (toolName === "Read") {
const path11 = readToolPaths.get(block2.tool_use_id);
if (path11) {
const current = fileReads.get(path11) || { count: 0, totalTokens: 0 };
fileReads.set(path11, {
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, v) => sum + v, 0);
const toolResultTotal = [...stats.toolResults.values()].reduce((sum, v) => sum + v, 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 error44 = new APIError(429, { error: { type: "rate_limit_error", message: "Rate limit exceeded" } }, "Rate limit exceeded", new globalThis.Headers(Object.entries(fastModeHeaders).filter(([_, v]) => v !== undefined)));
return error44;
}
const shouldThrow429 = status === "rejected" && (!overageStatus || overageStatus === "rejected");
if (shouldThrow429) {
const error44 = new APIError(429, { error: { type: "rate_limit_error", message: "Rate limit exceeded" } }, "Rate limit exceeded", new globalThis.Headers(Object.entries(mockHeaders2).filter(([_, v]) => v !== undefined)));
return error44;
}
return null;
}
function isMockRateLimitError(error44) {
return shouldProcessMockLimits() && error44.status === 429;
}
var init_rateLimitMocking = __esm(() => {
init_sdk();
init_mockRateLimits();
});
// src/services/api/errorUtils.ts
function extractConnectionErrorDetails(error44) {
if (!error44 || typeof error44 !== "object") {
return null;
}
let current = error44;
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(error44) {
const details = extractConnectionErrorDetails(error44);
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(error44) {
if (!hasNestedError(error44)) {
return null;
}
const narrowed = error44;
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(error44) {
const connectionDetails = extractConnectionErrorDetails(error44);
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 (error44.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 (!error44.message) {
return extractNestedErrorMessage(error44) ?? `API error (status ${error44.status ?? "unknown"})`;
}
const sanitizedMessage = sanitizeAPIError(error44);
return sanitizedMessage !== error44.message && sanitizedMessage.length > 0 ? sanitizedMessage : error44.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(error44) {
return is529Error(error44) || error44 instanceof APIError && error44.status === 429;
}
function isStaleConnectionError(error44) {
if (!(error44 instanceof APIConnectionError)) {
return false;
}
const details = extractConnectionErrorDetails(error44);
return details?.code === "ECONNRESET" || details?.code === "EPIPE";
}
async function* withRetry(getClient, operation, options2) {
const maxRetries = getMaxRetries(options2);
const retryContext = {
model: options2.model,
thinkingConfig: options2.thinkingConfig,
...isFastModeEnabled() && { fastMode: options2.fastMode }
};
let client5 = null;
let consecutive529Errors = options2.initialConsecutive529Errors ?? 0;
let lastError;
let persistentAttempt = 0;
for (let attempt = 1;attempt <= maxRetries + 1; attempt++) {
if (options2.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 getClient();
}
return await operation(client5, attempt, retryContext);
} catch (error44) {
lastError = error44;
logForDebugging(`API error (attempt ${attempt}/${maxRetries + 1}): ${error44 instanceof APIError ? `${error44.status} ${error44.message}` : errorMessage(error44)}`, { level: "error" });
if (wasFastModeActive && !isPersistentRetryEnabled() && error44 instanceof APIError && (error44.status === 429 || is529Error(error44))) {
const overageReason = error44.headers?.get("anthropic-ratelimit-unified-overage-disabled-reason");
if (overageReason !== null && overageReason !== undefined) {
handleFastModeOverageRejection(overageReason);
retryContext.fastMode = false;
continue;
}
const retryAfterMs = getRetryAfterMs(error44);
if (retryAfterMs !== null && retryAfterMs < SHORT_RETRY_THRESHOLD_MS) {
await sleep3(retryAfterMs, options2.signal, { abortError });
continue;
}
const cooldownMs = Math.max(retryAfterMs ?? DEFAULT_FAST_MODE_FALLBACK_HOLD_MS, MIN_COOLDOWN_MS);
const cooldownReason = is529Error(error44) ? "overloaded" : "rate_limit";
triggerFastModeCooldown(Date.now() + cooldownMs, cooldownReason);
if (isFastModeEnabled()) {
retryContext.fastMode = false;
}
continue;
}
if (wasFastModeActive && isFastModeNotEnabledError(error44)) {
handleFastModeRejectedByAPI();
retryContext.fastMode = false;
continue;
}
if (is529Error(error44) && !shouldRetry529(options2.querySource)) {
logEvent("tengu_api_529_background_dropped", {
query_source: options2.querySource
});
throw new CannotRetryError(error44, retryContext);
}
if (is529Error(error44) && (process.env.FALLBACK_FOR_ALL_PRIMARY_MODELS || !isClaudeAISubscriber() && isNonCustomOpusModel(options2.model))) {
consecutive529Errors++;
if (consecutive529Errors >= MAX_529_RETRIES) {
if (options2.fallbackModel) {
logEvent("tengu_api_opus_fallback_triggered", {
original_model: options2.model,
fallback_model: options2.fallbackModel,
provider: getAPIProviderForStatsig()
});
throw new FallbackTriggeredError(options2.model, options2.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(error44);
if (attempt > maxRetries && !persistent) {
throw new CannotRetryError(error44, retryContext);
}
const handledCloudAuthError = handleAwsCredentialError(error44) || handleGcpCredentialError(error44);
if (!handledCloudAuthError && (!(error44 instanceof APIError) || !shouldRetry(error44))) {
throw new CannotRetryError(error44, retryContext);
}
if (error44 instanceof APIError) {
const overflowData = parseMaxTokensContextOverflowError(error44);
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 error44;
}
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(error44);
let delayMs;
if (persistent && error44 instanceof APIError && error44.status === 429) {
persistentAttempt++;
const resetDelay = getRateLimitResetDelayMs(error44);
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: error44.message,
status: error44.status,
provider: getAPIProviderForStatsig()
});
if (persistent) {
if (delayMs > 60000) {
logEvent("tengu_api_persistent_retry_wait", {
status: error44.status,
delayMs,
attempt: reportedAttempt,
provider: getAPIProviderForStatsig()
});
}
let remaining = delayMs;
while (remaining > 0) {
if (options2.signal?.aborted)
throw new APIUserAbortError;
if (error44 instanceof APIError) {
yield createSystemAPIErrorMessage(error44, remaining, reportedAttempt, maxRetries);
}
const chunk = Math.min(remaining, HEARTBEAT_INTERVAL_MS);
await sleep3(chunk, options2.signal, { abortError });
remaining -= chunk;
}
if (attempt >= maxRetries)
attempt = maxRetries;
} else {
if (error44 instanceof APIError) {
yield createSystemAPIErrorMessage(error44, delayMs, attempt, maxRetries);
}
await sleep3(delayMs, options2.signal, { abortError });
}
}
}
throw new CannotRetryError(lastError, retryContext);
}
function getRetryAfter(error44) {
return (error44.headers?.["retry-after"] || error44.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(error44) {
if (error44.status !== 400 || !error44.message) {
return;
}
if (!error44.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 = error44.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(error44) {
if (!(error44 instanceof APIError)) {
return false;
}
return error44.status === 400 && (error44.message?.includes("Fast mode is not enabled") ?? false);
}
function is529Error(error44) {
if (!(error44 instanceof APIError)) {
return false;
}
return error44.status === 529 || (error44.message?.includes('"type":"overloaded_error"') ?? false);
}
function isOAuthTokenRevokedError(error44) {
return error44 instanceof APIError && error44.status === 403 && (error44.message?.includes("OAuth token has been revoked") ?? false);
}
function isBedrockAuthError(error44) {
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK)) {
if (isAwsCredentialsProviderError(error44) || error44 instanceof APIError && error44.status === 403) {
return true;
}
}
return false;
}
function handleAwsCredentialError(error44) {
if (isBedrockAuthError(error44)) {
clearAwsCredentialsCache();
return true;
}
return false;
}
function isGoogleAuthLibraryCredentialError(error44) {
if (!(error44 instanceof Error))
return false;
const msg = error44.message;
return msg.includes("Could not load the default credentials") || msg.includes("Could not refresh access token") || msg.includes("invalid_grant");
}
function isVertexAuthError(error44) {
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX)) {
if (isGoogleAuthLibraryCredentialError(error44)) {
return true;
}
if (error44 instanceof APIError && error44.status === 401) {
return true;
}
}
return false;
}
function handleGcpCredentialError(error44) {
if (isVertexAuthError(error44)) {
clearGcpCredentialsCache();
return true;
}
return false;
}
function shouldRetry(error44) {
if (isMockRateLimitError(error44)) {
return false;
}
if (isPersistentRetryEnabled() && isTransientCapacityError(error44)) {
return true;
}
if (isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) && (error44.status === 401 || error44.status === 403)) {
return true;
}
if (error44.message?.includes('"type":"overloaded_error"')) {
return true;
}
if (parseMaxTokensContextOverflowError(error44)) {
return true;
}
const shouldRetryHeader = error44.headers?.get("x-should-retry");
if (shouldRetryHeader === "true" && (!isClaudeAISubscriber() || isEnterpriseSubscriber())) {
return true;
}
if (shouldRetryHeader === "false") {
const is5xxError = error44.status !== undefined && error44.status >= 500;
if (!(process.env.USER_TYPE === "ant" && is5xxError)) {
return false;
}
}
if (error44 instanceof APIConnectionError) {
return true;
}
if (!error44.status)
return false;
if (error44.status === 408)
return true;
if (error44.status === 409)
return true;
if (error44.status === 429) {
return !isClaudeAISubscriber() || isEnterpriseSubscriber();
}
if (error44.status === 401) {
clearApiKeyHelperCache();
return true;
}
if (isOAuthTokenRevokedError(error44)) {
return true;
}
if (error44.status && error44.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(options2) {
return options2.maxRetries ?? getDefaultMaxRetries();
}
function getRetryAfterMs(error44) {
const retryAfter = getRetryAfter(error44);
if (retryAfter) {
const seconds = parseInt(retryAfter, 10);
if (!isNaN(seconds)) {
return seconds * 1000;
}
}
return null;
}
function getRateLimitResetDelayMs(error44) {
const resetHeader = error44.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(block2) {
if (typeof block2 !== "object" || block2 === null)
return false;
const b = block2;
if (b.type !== "image")
return false;
if (typeof b.source !== "object" || b.source === null)
return false;
const source = b.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 m = msg;
if (m.type !== "user")
continue;
const innerMessage = m.message;
if (!innerMessage)
continue;
const content = innerMessage.content;
if (typeof content === "string" || !Array.isArray(content))
continue;
for (const block2 of content) {
if (isBase64ImageBlock(block2)) {
imageIndex++;
const base64Size = block2.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";
}
};
});
// native-stub:image-processor-napi
var exports_image_processor_napi = {};
__export(exports_image_processor_napi, {
trace: () => trace3,
resourceFromAttributes: () => resourceFromAttributes3,
plot: () => plot3,
getSyntaxTheme: () => getSyntaxTheme3,
getMcpConfigForManifest: () => getMcpConfigForManifest3,
default: () => image_processor_napi_default,
createComputerUseMcpServer: () => createComputerUseMcpServer3,
createClaudeForChromeMcpServer: () => createClaudeForChromeMcpServer3,
context: () => context3,
__stub: () => __stub3,
SpanStatusCode: () => SpanStatusCode3,
SimpleSpanProcessor: () => SimpleSpanProcessor3,
SimpleLogRecordProcessor: () => SimpleLogRecordProcessor3,
SeverityNumber: () => SeverityNumber3,
SandboxViolationStore: () => SandboxViolationStore4,
SandboxRuntimeConfigSchema: () => SandboxRuntimeConfigSchema4,
SandboxManager: () => SandboxManager7,
SEMRESATTRS_SERVICE_VERSION: () => SEMRESATTRS_SERVICE_VERSION3,
SEMRESATTRS_SERVICE_NAME: () => SEMRESATTRS_SERVICE_NAME3,
Resource: () => Resource3,
PushMetricExporter: () => PushMetricExporter3,
PrometheusExporter: () => PrometheusExporter3,
PeriodicExportingMetricReader: () => PeriodicExportingMetricReader3,
OTLPTraceExporter: () => OTLPTraceExporter3,
OTLPMetricExporter: () => OTLPMetricExporter3,
OTLPLogExporter: () => OTLPLogExporter3,
NodeTracerProvider: () => NodeTracerProvider3,
MeterProvider: () => MeterProvider3,
LoggerProvider: () => LoggerProvider3,
InstrumentType: () => InstrumentType3,
ExportResultCode: () => ExportResultCode3,
DataPointType: () => DataPointType3,
ColorFile: () => ColorFile3,
ColorDiff: () => ColorDiff3,
BatchSpanProcessor: () => BatchSpanProcessor3,
BatchLogRecordProcessor: () => BatchLogRecordProcessor3,
BasicTracerProvider: () => BasicTracerProvider3,
BROWSER_TOOLS: () => BROWSER_TOOLS3,
AggregationTemporality: () => AggregationTemporality3,
ATTR_SERVICE_VERSION: () => ATTR_SERVICE_VERSION3,
ATTR_SERVICE_NAME: () => ATTR_SERVICE_NAME3
});
var noop13 = () => null, noopClass3 = class {
}, handler6, stub6, image_processor_napi_default, __stub3 = true, SandboxViolationStore4 = null, SandboxManager7, SandboxRuntimeConfigSchema4, BROWSER_TOOLS3, getMcpConfigForManifest3, ColorDiff3 = null, ColorFile3 = null, getSyntaxTheme3, plot3, createClaudeForChromeMcpServer3, createComputerUseMcpServer3, ExportResultCode3, resourceFromAttributes3, Resource3, SimpleSpanProcessor3, BatchSpanProcessor3, NodeTracerProvider3, BasicTracerProvider3, OTLPTraceExporter3, OTLPLogExporter3, OTLPMetricExporter3, PrometheusExporter3, LoggerProvider3, SimpleLogRecordProcessor3, BatchLogRecordProcessor3, MeterProvider3, PeriodicExportingMetricReader3, trace3, context3, SpanStatusCode3, ATTR_SERVICE_NAME3 = "service.name", ATTR_SERVICE_VERSION3 = "service.version", SEMRESATTRS_SERVICE_NAME3 = "service.name", SEMRESATTRS_SERVICE_VERSION3 = "service.version", AggregationTemporality3, DataPointType3, InstrumentType3, PushMetricExporter3, SeverityNumber3;
var init_image_processor_napi = __esm(() => {
handler6 = {
get(_, prop) {
if (prop === "__esModule")
return true;
if (prop === "default")
return new Proxy({}, handler6);
if (prop === "ExportResultCode")
return { SUCCESS: 0, FAILED: 1 };
if (prop === "resourceFromAttributes")
return () => ({});
if (prop === "SandboxRuntimeConfigSchema")
return { parse: () => ({}) };
return noop13;
}
};
stub6 = new Proxy(noop13, handler6);
image_processor_napi_default = stub6;
SandboxManager7 = new Proxy({}, { get: () => noop13 });
SandboxRuntimeConfigSchema4 = { parse: () => ({}) };
BROWSER_TOOLS3 = [];
getMcpConfigForManifest3 = noop13;
getSyntaxTheme3 = noop13;
plot3 = noop13;
createClaudeForChromeMcpServer3 = noop13;
createComputerUseMcpServer3 = noop13;
ExportResultCode3 = { SUCCESS: 0, FAILED: 1 };
resourceFromAttributes3 = noop13;
Resource3 = noopClass3;
SimpleSpanProcessor3 = noopClass3;
BatchSpanProcessor3 = noopClass3;
NodeTracerProvider3 = noopClass3;
BasicTracerProvider3 = noopClass3;
OTLPTraceExporter3 = noopClass3;
OTLPLogExporter3 = noopClass3;
OTLPMetricExporter3 = noopClass3;
PrometheusExporter3 = noopClass3;
LoggerProvider3 = noopClass3;
SimpleLogRecordProcessor3 = noopClass3;
BatchLogRecordProcessor3 = noopClass3;
MeterProvider3 = noopClass3;
PeriodicExportingMetricReader3 = noopClass3;
trace3 = { getTracer: () => ({ startSpan: () => ({ end: noop13, setAttribute: noop13, setStatus: noop13, recordException: noop13 }) }) };
context3 = { active: noop13, with: (_, fn) => fn() };
SpanStatusCode3 = { OK: 0, ERROR: 1, UNSET: 2 };
AggregationTemporality3 = { CUMULATIVE: 0, DELTA: 1 };
DataPointType3 = { HISTOGRAM: 0, SUM: 1, GAUGE: 2 };
InstrumentType3 = { COUNTER: 0, HISTOGRAM: 1, UP_DOWN_COUNTER: 2 };
PushMetricExporter3 = noopClass3;
SeverityNumber3 = {};
});
// native-stub:sharp
var exports_sharp = {};
__export(exports_sharp, {
trace: () => trace4,
resourceFromAttributes: () => resourceFromAttributes4,
plot: () => plot4,
getSyntaxTheme: () => getSyntaxTheme4,
getMcpConfigForManifest: () => getMcpConfigForManifest4,
default: () => sharp_default,
createComputerUseMcpServer: () => createComputerUseMcpServer4,
createClaudeForChromeMcpServer: () => createClaudeForChromeMcpServer4,
context: () => context4,
__stub: () => __stub4,
SpanStatusCode: () => SpanStatusCode4,
SimpleSpanProcessor: () => SimpleSpanProcessor4,
SimpleLogRecordProcessor: () => SimpleLogRecordProcessor4,
SeverityNumber: () => SeverityNumber4,
SandboxViolationStore: () => SandboxViolationStore5,
SandboxRuntimeConfigSchema: () => SandboxRuntimeConfigSchema5,
SandboxManager: () => SandboxManager8,
SEMRESATTRS_SERVICE_VERSION: () => SEMRESATTRS_SERVICE_VERSION4,
SEMRESATTRS_SERVICE_NAME: () => SEMRESATTRS_SERVICE_NAME4,
Resource: () => Resource4,
PushMetricExporter: () => PushMetricExporter4,
PrometheusExporter: () => PrometheusExporter4,
PeriodicExportingMetricReader: () => PeriodicExportingMetricReader4,
OTLPTraceExporter: () => OTLPTraceExporter4,
OTLPMetricExporter: () => OTLPMetricExporter4,
OTLPLogExporter: () => OTLPLogExporter4,
NodeTracerProvider: () => NodeTracerProvider4,
MeterProvider: () => MeterProvider4,
LoggerProvider: () => LoggerProvider4,
InstrumentType: () => InstrumentType4,
ExportResultCode: () => ExportResultCode4,
DataPointType: () => DataPointType4,
ColorFile: () => ColorFile4,
ColorDiff: () => ColorDiff4,
BatchSpanProcessor: () => BatchSpanProcessor4,
BatchLogRecordProcessor: () => BatchLogRecordProcessor4,
BasicTracerProvider: () => BasicTracerProvider4,
BROWSER_TOOLS: () => BROWSER_TOOLS4,
AggregationTemporality: () => AggregationTemporality4,
ATTR_SERVICE_VERSION: () => ATTR_SERVICE_VERSION4,
ATTR_SERVICE_NAME: () => ATTR_SERVICE_NAME4
});
var noop14 = () => null, noopClass4 = class {
}, handler7, stub7, sharp_default, __stub4 = true, SandboxViolationStore5 = null, SandboxManager8, SandboxRuntimeConfigSchema5, BROWSER_TOOLS4, getMcpConfigForManifest4, ColorDiff4 = null, ColorFile4 = null, getSyntaxTheme4, plot4, createClaudeForChromeMcpServer4, createComputerUseMcpServer4, ExportResultCode4, resourceFromAttributes4, Resource4, SimpleSpanProcessor4, BatchSpanProcessor4, NodeTracerProvider4, BasicTracerProvider4, OTLPTraceExporter4, OTLPLogExporter4, OTLPMetricExporter4, PrometheusExporter4, LoggerProvider4, SimpleLogRecordProcessor4, BatchLogRecordProcessor4, MeterProvider4, PeriodicExportingMetricReader4, trace4, context4, SpanStatusCode4, ATTR_SERVICE_NAME4 = "service.name", ATTR_SERVICE_VERSION4 = "service.version", SEMRESATTRS_SERVICE_NAME4 = "service.name", SEMRESATTRS_SERVICE_VERSION4 = "service.version", AggregationTemporality4, DataPointType4, InstrumentType4, PushMetricExporter4, SeverityNumber4;
var init_sharp = __esm(() => {
handler7 = {
get(_, prop) {
if (prop === "__esModule")
return true;
if (prop === "default")
return new Proxy({}, handler7);
if (prop === "ExportResultCode")
return { SUCCESS: 0, FAILED: 1 };
if (prop === "resourceFromAttributes")
return () => ({});
if (prop === "SandboxRuntimeConfigSchema")
return { parse: () => ({}) };
return noop14;
}
};
stub7 = new Proxy(noop14, handler7);
sharp_default = stub7;
SandboxManager8 = new Proxy({}, { get: () => noop14 });
SandboxRuntimeConfigSchema5 = { parse: () => ({}) };
BROWSER_TOOLS4 = [];
getMcpConfigForManifest4 = noop14;
getSyntaxTheme4 = noop14;
plot4 = noop14;
createClaudeForChromeMcpServer4 = noop14;
createComputerUseMcpServer4 = noop14;
ExportResultCode4 = { SUCCESS: 0, FAILED: 1 };
resourceFromAttributes4 = noop14;
Resource4 = noopClass4;
SimpleSpanProcessor4 = noopClass4;
BatchSpanProcessor4 = noopClass4;
NodeTracerProvider4 = noopClass4;
BasicTracerProvider4 = noopClass4;
OTLPTraceExporter4 = noopClass4;
OTLPLogExporter4 = noopClass4;
OTLPMetricExporter4 = noopClass4;
PrometheusExporter4 = noopClass4;
LoggerProvider4 = noopClass4;
SimpleLogRecordProcessor4 = noopClass4;
BatchLogRecordProcessor4 = noopClass4;
MeterProvider4 = noopClass4;
PeriodicExportingMetricReader4 = noopClass4;
trace4 = { getTracer: () => ({ startSpan: () => ({ end: noop14, setAttribute: noop14, setStatus: noop14, recordException: noop14 }) }) };
context4 = { active: noop14, with: (_, fn) => fn() };
SpanStatusCode4 = { OK: 0, ERROR: 1, UNSET: 2 };
AggregationTemporality4 = { CUMULATIVE: 0, DELTA: 1 };
DataPointType4 = { HISTOGRAM: 0, SUM: 1, GAUGE: 2 };
InstrumentType4 = { COUNTER: 0, HISTOGRAM: 1, UP_DOWN_COUNTER: 2 };
PushMetricExporter4 = noopClass4;
SeverityNumber4 = {};
});
// src/tools/FileReadTool/imageProcessor.ts
async function getImageProcessor() {
if (imageProcessorModule) {
return imageProcessorModule.default;
}
if (isInBundledMode()) {
try {
const imageProcessor = await Promise.resolve().then(() => (init_image_processor_napi(), exports_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 Promise.resolve().then(() => (init_sharp(), exports_sharp));
const sharp = unwrapDefault(imported);
imageProcessorModule = { default: sharp };
return sharp;
}
function unwrapDefault(mod) {
return typeof mod === "function" ? mod : mod.default;
}
var imageProcessorModule = null;
var init_imageProcessor = () => {};
// src/utils/imageResizer.ts
function classifyImageError(error44) {
if (error44 instanceof Error) {
const errorWithCode = error44;
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(error44);
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 hash2 = 5381;
for (let i3 = 0;i3 < str.length; i3++) {
hash2 = (hash2 << 5) + hash2 + str.charCodeAt(i3) | 0;
}
return hash2 >>> 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 (error44) {
logError2(error44);
const errorType = classifyImageError(error44);
const errorMsg = errorMessage(error44);
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 context5 = {
imageBuffer,
metadata,
format: format4,
maxBytes,
originalSize
};
if (originalSize <= maxBytes) {
return createCompressedImageResult(imageBuffer, format4, originalSize);
}
const resizedResult = await tryProgressiveResizing(context5, sharp);
if (resizedResult) {
return resizedResult;
}
if (format4 === "png") {
const palettizedResult = await tryPalettePNG(context5, sharp);
if (palettizedResult) {
return palettizedResult;
}
}
const jpegResult = await tryJPEGConversion(context5, 50, sharp);
if (jpegResult) {
return jpegResult;
}
return await createUltraCompressedJPEG(context5, sharp);
} catch (error44) {
logError2(error44);
const errorType = classifyImageError(error44);
const errorMsg = errorMessage(error44);
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(context5, sharp) {
const scalingFactors = [1, 0.75, 0.5, 0.25];
for (const scalingFactor of scalingFactors) {
const newWidth = Math.round((context5.metadata.width || 2000) * scalingFactor);
const newHeight = Math.round((context5.metadata.height || 2000) * scalingFactor);
let resizedImage = sharp(context5.imageBuffer).resize(newWidth, newHeight, {
fit: "inside",
withoutEnlargement: true
});
resizedImage = applyFormatOptimizations(resizedImage, context5.format);
const resizedBuffer = await resizedImage.toBuffer();
if (resizedBuffer.length <= context5.maxBytes) {
return createCompressedImageResult(resizedBuffer, context5.format, context5.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(context5, sharp) {
const palettePng = await sharp(context5.imageBuffer).resize(800, 800, {
fit: "inside",
withoutEnlargement: true
}).png({
compressionLevel: 9,
palette: true,
colors: 64
}).toBuffer();
if (palettePng.length <= context5.maxBytes) {
return createCompressedImageResult(palettePng, "png", context5.originalSize);
}
return null;
}
async function tryJPEGConversion(context5, quality, sharp) {
const jpegBuffer = await sharp(context5.imageBuffer).resize(600, 600, {
fit: "inside",
withoutEnlargement: true
}).jpeg({ quality }).toBuffer();
if (jpegBuffer.length <= context5.maxBytes) {
return createCompressedImageResult(jpegBuffer, "jpeg", context5.originalSize);
}
return null;
}
async function createUltraCompressedJPEG(context5, sharp) {
const ultraCompressedBuffer = await sharp(context5.imageBuffer).resize(400, 400, {
fit: "inside",
withoutEnlargement: true
}).jpeg({ quality: 20 }).toBuffer();
return createCompressedImageResult(ultraCompressedBuffer, "jpeg", context5.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((block2) => block2.type === "text").map((block2) => block2.type === "text" ? block2.text : "").join("").trim();
return summary || null;
} catch (error44) {
const err2 = toError(error44);
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 i3 = 0;i3 < commandQueue.length; i3++) {
const cmd = commandQueue[i3];
if (filter2 && !filter2(cmd))
continue;
const priority = PRIORITY_ORDER[cmd.priority ?? "next"];
if (priority < bestPriority) {
bestIdx = i3;
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 i3 = 0;i3 < commandQueue.length; i3++) {
const cmd = commandQueue[i3];
if (filter2 && !filter2(cmd))
continue;
const priority = PRIORITY_ORDER[cmd.priority ?? "next"];
if (priority < bestPriority) {
bestIdx = i3;
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 i3 = commandQueue.length - 1;i3 >= 0; i3--) {
if (commandsToRemove.includes(commandQueue[i3])) {
commandQueue.splice(i3, 1);
}
}
if (commandQueue.length !== before) {
notifySubscribers();
}
for (const _cmd of commandsToRemove) {
logOperation("remove");
}
}
function removeByFilter(predicate) {
const removed = [];
for (let i3 = commandQueue.length - 1;i3 >= 0; i3--) {
if (predicate(commandQueue[i3])) {
removed.unshift(commandQueue.splice(i3, 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 block2 of value) {
if (block2.type === "image" && block2.source.type === "base64") {
images.push({
id: startId + imageIndex,
type: "image",
content: block2.source.data,
mediaType: block2.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(uuid5, state) {
listener?.(uuid5, state);
}
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(name) {
if (!getIsNonInteractiveSession())
return;
if (!SHOULD_PROFILE2)
return;
const perf = getPerformance();
perf.mark(`${MARK_PREFIX}${name}`);
if (DETAILED_PROFILING2) {
logForDebugging(`[headlessProfiler] Checkpoint: ${name} 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 name = mark.name.slice(MARK_PREFIX.length);
checkpointTimes.set(name, 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 context5 = {
messages,
systemPrompt,
userContext,
systemContext,
toolUseContext,
querySource
};
for (const hook of postSamplingHooks) {
try {
await hook(context5);
} catch (error44) {
logError2(toError(error44));
}
}
}
var postSamplingHooks;
var init_postSamplingHooks = __esm(() => {
init_errors();
init_log3();
postSamplingHooks = [];
});
// src/services/api/dumpPrompts.ts
import { createHash as createHash5 } from "crypto";
import { promises as fs2 } from "fs";
import { dirname as dirname20, join as join36 } from "path";
function hashString3(str) {
return createHash5("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 join36(getClaudeConfigHomeDir(), "dump-prompts", `${agentIdOrSessionId ?? getSessionId()}.jsonl`);
}
function appendToFile(filePath, entries) {
if (entries.length === 0)
return;
fs2.mkdir(dirname20(filePath), { recursive: true }).then(() => fs2.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, b) => n2 + (b.text?.length ?? 0), 0) : 0;
const toolNames = tools?.map((t) => t.name ?? "").join(",") ?? "";
return `${req.model}|${toolNames}|${sysLen}`;
}
function dumpRequest(body, ts, state, 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 (!state.initialized || fingerprint !== state.lastInitFingerprint) {
const { messages: _, ...initData } = req;
const initDataStr = jsonStringify(initData);
const initDataHash = hashString3(initDataStr);
state.lastInitFingerprint = fingerprint;
if (!state.initialized) {
state.initialized = true;
state.lastInitDataHash = initDataHash;
entries.push(`{"type":"init","timestamp":"${ts}","data":${initDataStr}}`);
} else if (initDataHash !== state.lastInitDataHash) {
state.lastInitDataHash = initDataHash;
entries.push(`{"type":"system_update","timestamp":"${ts}","data":${initDataStr}}`);
}
}
for (const msg of messages.slice(state.messageCountSeen)) {
if (msg.role === "user") {
entries.push(jsonStringify({ type: "message", timestamp: ts, data: msg }));
}
}
state.messageCountSeen = messages.length;
appendToFile(filePath, entries);
} catch {}
}
function createDumpPromptsFetch(agentIdOrSessionId) {
const filePath = getDumpPromptsPath(agentIdOrSessionId);
return async (input, init) => {
const state = dumpState.get(agentIdOrSessionId) ?? {
initialized: false,
messageCountSeen: 0,
lastInitDataHash: "",
lastInitFingerprint: ""
};
dumpState.set(agentIdOrSessionId, state);
let timestamp;
if (init?.method === "POST" && init.body) {
timestamp = new Date().toISOString();
setImmediate(dumpRequest, init.body, timestamp, state, 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 fs2.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 handler8 = weakHandler.deref();
if (parent && handler8) {
parent.signal.removeEventListener("abort", handler8);
}
}
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 handler8 = propagateAbort.bind(weakParent, weakChild);
parent.signal.addEventListener("abort", handler8, { once: true });
child.signal.addEventListener("abort", removeAbortHandler.bind(weakParent, new WeakRef(handler8)), { once: true });
return child;
}
var DEFAULT_MAX_LISTENERS = 50;
var init_abortController = () => {};
// src/services/tools/toolConcurrency.ts
function getMaxToolUseConcurrency() {
const parsed = parseInt(process.env.CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY || "", 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_TOOL_USE_CONCURRENCY;
}
var DEFAULT_MAX_TOOL_USE_CONCURRENCY = 4;
// 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(function(name) {
var prop = obj[name];
if (typeof prop == "object" && !Object.isFrozen(prop)) {
deepFreeze(prop);
}
});
return obj;
}
var deepFreezeEs6 = deepFreeze;
var _default3 = deepFreeze;
deepFreezeEs6.default = _default3;
class Response2 {
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(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.kind;
};
class HTMLRenderer {
constructor(parseTree2, options2) {
this.buffer = "";
this.classPrefix = options2.classPrefix;
parseTree2.walk(this);
}
addText(text) {
this.buffer += escapeHTML(text);
}
openNode(node) {
if (!emitsWrappingTags(node))
return;
let className = node.kind;
if (!node.sublanguage) {
className = `${this.classPrefix}${className}`;
}
this.span(className);
}
closeNode(node) {
if (!emitsWrappingTags(node))
return;
this.buffer += SPAN_CLOSE;
}
value() {
return this.buffer;
}
span(className) {
this.buffer += ``;
}
}
class TokenTree {
constructor() {
this.rootNode = { children: [] };
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(kind) {
const node = { kind, children: [] };
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(options2) {
super();
this.options = options2;
}
addKeyword(text, kind) {
if (text === "") {
return;
}
this.openNode(kind);
this.addText(text);
this.closeNode();
}
addText(text) {
if (text === "") {
return;
}
this.add(text);
}
addSublanguage(emitter, name) {
const node = emitter.root;
node.kind = name;
node.sublanguage = true;
this.add(node);
}
toHTML() {
const renderer = new HTMLRenderer(this, this.options);
return renderer.value();
}
finalize() {
return true;
}
}
function escape3(value) {
return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"), "m");
}
function source(re) {
if (!re)
return null;
if (typeof re === "string")
return re;
return re.source;
}
function concat(...args) {
const joined = args.map((x3) => source(x3)).join("");
return joined;
}
function either(...args) {
const joined = "(" + args.map((x3) => source(x3)).join("|") + ")";
return joined;
}
function countMatchGroups(re) {
return new RegExp(re.toString() + "|").exec("").length - 1;
}
function startsWith(re, lexeme) {
const match = re && re.exec(lexeme);
return match && match.index === 0;
}
var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
function join37(regexps, separator = "|") {
let numCaptures = 0;
return regexps.map((regex2) => {
numCaptures += 1;
const offset = numCaptures;
let re = source(regex2);
let out = "";
while (re.length > 0) {
const match = BACKREF_RE.exec(re);
if (!match) {
out += re;
break;
}
out += re.substring(0, match.index);
re = re.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((re) => `(${re})`).join(separator);
}
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 = concat(beginShebang, /.*\b/, opts.binary, /\b.*/);
}
return inherit({
className: "meta",
begin: beginShebang,
end: /$/,
relevance: 0,
"on:begin": (m, resp) => {
if (m.index !== 0)
resp.ignoreMatch();
}
}, opts);
};
var BACKSLASH_ESCAPE = {
begin: "\\\\[\\s\\S]",
relevance: 0
};
var APOS_STRING_MODE = {
className: "string",
begin: "'",
end: "'",
illegal: "\\n",
contains: [BACKSLASH_ESCAPE]
};
var QUOTE_STRING_MODE = {
className: "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({
className: "comment",
begin,
end,
contains: []
}, modeOptions);
mode.contains.push(PHRASAL_WORDS_MODE);
mode.contains.push({
className: "doctag",
begin: "(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",
relevance: 0
});
return mode;
};
var C_LINE_COMMENT_MODE = COMMENT("//", "$");
var C_BLOCK_COMMENT_MODE = COMMENT("/\\*", "\\*/");
var HASH_COMMENT_MODE = COMMENT("#", "$");
var NUMBER_MODE = {
className: "number",
begin: NUMBER_RE,
relevance: 0
};
var C_NUMBER_MODE = {
className: "number",
begin: C_NUMBER_RE,
relevance: 0
};
var BINARY_NUMBER_MODE = {
className: "number",
begin: BINARY_NUMBER_RE,
relevance: 0
};
var CSS_NUMBER_MODE = {
className: "number",
begin: NUMBER_RE + "(" + "%|em|ex|ch|rem" + "|vw|vh|vmin|vmax" + "|cm|mm|in|pt|pc|px" + "|deg|grad|rad|turn" + "|s|ms" + "|Hz|kHz" + "|dpi|dpcm|dppx" + ")?",
relevance: 0
};
var REGEXP_MODE = {
begin: /(?=\/[^/\n]*\/)/,
contains: [{
className: "regexp",
begin: /\//,
end: /\/[gimuy]*/,
illegal: /\n/,
contains: [
BACKSLASH_ESCAPE,
{
begin: /\[/,
end: /\]/,
relevance: 0,
contains: [BACKSLASH_ESCAPE]
}
]
}]
};
var TITLE_MODE = {
className: "title",
begin: IDENT_RE,
relevance: 0
};
var UNDERSCORE_TITLE_MODE = {
className: "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": (m, resp) => {
resp.data._beginMatch = m[1];
},
"on:end": (m, resp) => {
if (resp.data._beginMatch !== m[1])
resp.ignoreMatch();
}
});
};
var MODES = /* @__PURE__ */ Object.freeze({
__proto__: null,
MATCH_NOTHING_RE,
IDENT_RE,
UNDERSCORE_IDENT_RE,
NUMBER_RE,
C_NUMBER_RE,
BINARY_NUMBER_RE,
RE_STARTERS_RE,
SHEBANG,
BACKSLASH_ESCAPE,
APOS_STRING_MODE,
QUOTE_STRING_MODE,
PHRASAL_WORDS_MODE,
COMMENT,
C_LINE_COMMENT_MODE,
C_BLOCK_COMMENT_MODE,
HASH_COMMENT_MODE,
NUMBER_MODE,
C_NUMBER_MODE,
BINARY_NUMBER_MODE,
CSS_NUMBER_MODE,
REGEXP_MODE,
TITLE_MODE,
UNDERSCORE_TITLE_MODE,
METHOD_GUARD,
END_SAME_AS_BEGIN
});
function skipIfhasPrecedingDot(match, response) {
const before = match.input[match.index - 1];
if (before === ".") {
response.ignoreMatch();
}
}
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 COMMON_KEYWORDS = [
"of",
"and",
"for",
"in",
"not",
"or",
"if",
"then",
"parent",
"list",
"value"
];
var DEFAULT_KEYWORD_CLASSNAME = "keyword";
function compileKeywords(rawKeywords, caseInsensitive, className = DEFAULT_KEYWORD_CLASSNAME) {
const compiledKeywords = {};
if (typeof rawKeywords === "string") {
compileList(className, rawKeywords.split(" "));
} else if (Array.isArray(rawKeywords)) {
compileList(className, rawKeywords);
} else {
Object.keys(rawKeywords).forEach(function(className2) {
Object.assign(compiledKeywords, compileKeywords(rawKeywords[className2], caseInsensitive, className2));
});
}
return compiledKeywords;
function compileList(className2, keywordList) {
if (caseInsensitive) {
keywordList = keywordList.map((x3) => x3.toLowerCase());
}
keywordList.forEach(function(keyword) {
const pair = keyword.split("|");
compiledKeywords[pair[0]] = [className2, 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());
}
function compileLanguage(language, { plugins }) {
function langRe(value, global3) {
return new RegExp(source(value), "m" + (language.case_insensitive ? "i" : "") + (global3 ? "g" : ""));
}
class MultiRegex {
constructor() {
this.matchIndexes = {};
this.regexes = [];
this.matchAt = 1;
this.position = 0;
}
addRule(re, opts) {
opts.position = this.position++;
this.matchIndexes[this.matchAt] = opts;
this.regexes.push([opts, re]);
this.matchAt += countMatchGroups(re) + 1;
}
compile() {
if (this.regexes.length === 0) {
this.exec = () => null;
}
const terminators = this.regexes.map((el) => el[1]);
this.matcherRe = langRe(join37(terminators), true);
this.lastIndex = 0;
}
exec(s) {
this.matcherRe.lastIndex = this.lastIndex;
const match = this.matcherRe.exec(s);
if (!match) {
return null;
}
const i3 = match.findIndex((el, i4) => i4 > 0 && el !== undefined);
const matchData = this.matchIndexes[i3];
match.splice(0, i3);
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(([re, opts]) => matcher.addRule(re, opts));
matcher.compile();
this.multiRegexes[index] = matcher;
return matcher;
}
resumingScanAtSamePosition() {
return this.regexIndex !== 0;
}
considerAll() {
this.regexIndex = 0;
}
addRule(re, opts) {
this.rules.push([re, opts]);
if (opts.type === "begin")
this.count++;
}
exec(s) {
const m = this.getMatcher(this.regexIndex);
m.lastIndex = this.lastIndex;
let result = m.exec(s);
if (this.resumingScanAtSamePosition()) {
if (result && result.index === this.lastIndex)
;
else {
const m2 = this.getMatcher(0);
m2.lastIndex = this.lastIndex + 1;
result = m2.exec(s);
}
}
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;
[
compileMatch
].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") {
keywordPattern = mode.keywords.$pattern;
delete mode.keywords.$pattern;
}
if (mode.keywords) {
mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
}
if (mode.lexemes && keywordPattern) {
throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");
}
keywordPattern = keywordPattern || mode.lexemes || /\w+/;
cmode.keywordPatternRe = langRe(keywordPattern, true);
if (parent) {
if (!mode.begin)
mode.begin = /\B|\b/;
cmode.beginRe = langRe(mode.begin);
if (mode.endSameAsBegin)
mode.end = mode.begin;
if (!mode.end && !mode.endsWithParent)
mode.end = /\B|\b/;
if (mode.end)
cmode.endRe = langRe(mode.end);
cmode.terminatorEnd = source(mode.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(c7) {
return expandOrCloneMode(c7 === "self" ? mode : c7);
}));
mode.contains.forEach(function(c7) {
compileMode(c7, 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(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(mode, { variants: null }, variant);
});
}
if (mode.cachedVariants) {
return mode.cachedVariants;
}
if (dependencyOnParent(mode)) {
return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null });
}
if (Object.isFrozen(mode)) {
return inherit(mode);
}
return mode;
}
var version2 = "10.7.3";
function hasValueOrEmptyAttribute(value) {
return Boolean(value || value === "");
}
function BuildVuePlugin(hljs) {
const Component = {
props: ["language", "code", "autodetect"],
data: function() {
return {
detectedLanguage: "",
unknownLanguage: false
};
},
computed: {
className() {
if (this.unknownLanguage)
return "";
return "hljs " + this.detectedLanguage;
},
highlighted() {
if (!this.autoDetect && !hljs.getLanguage(this.language)) {
console.warn(`The language "${this.language}" you specified could not be found.`);
this.unknownLanguage = true;
return escapeHTML(this.code);
}
let result = {};
if (this.autoDetect) {
result = hljs.highlightAuto(this.code);
this.detectedLanguage = result.language;
} else {
result = hljs.highlight(this.language, this.code, this.ignoreIllegals);
this.detectedLanguage = this.language;
}
return result.value;
},
autoDetect() {
return !this.language || hasValueOrEmptyAttribute(this.autodetect);
},
ignoreIllegals() {
return true;
}
},
render(createElement2) {
return createElement2("pre", {}, [
createElement2("code", {
class: this.className,
domProps: { innerHTML: this.highlighted }
})
]);
}
};
const VuePlugin = {
install(Vue) {
Vue.component("highlightjs", Component);
}
};
return { Component, VuePlugin };
}
var mergeHTMLPlugin = {
"after:highlightElement": ({ el, result, text }) => {
const originalStream = nodeStream(el);
if (!originalStream.length)
return;
const resultNode = document.createElement("div");
resultNode.innerHTML = result.value;
result.value = mergeStreams2(originalStream, nodeStream(resultNode), text);
}
};
function tag2(node) {
return node.nodeName.toLowerCase();
}
function nodeStream(node) {
const result = [];
(function _nodeStream(node2, offset) {
for (let child = node2.firstChild;child; child = child.nextSibling) {
if (child.nodeType === 3) {
offset += child.nodeValue.length;
} else if (child.nodeType === 1) {
result.push({
event: "start",
offset,
node: child
});
offset = _nodeStream(child, offset);
if (!tag2(child).match(/br|hr|img|input/)) {
result.push({
event: "stop",
offset,
node: child
});
}
}
}
return offset;
})(node, 0);
return result;
}
function mergeStreams2(original, highlighted, value) {
let processed = 0;
let result = "";
const nodeStack = [];
function selectStream() {
if (!original.length || !highlighted.length) {
return original.length ? original : highlighted;
}
if (original[0].offset !== highlighted[0].offset) {
return original[0].offset < highlighted[0].offset ? original : highlighted;
}
return highlighted[0].event === "start" ? original : highlighted;
}
function open5(node) {
function attributeString(attr) {
return " " + attr.nodeName + '="' + escapeHTML(attr.value) + '"';
}
result += "<" + tag2(node) + [].map.call(node.attributes, attributeString).join("") + ">";
}
function close(node) {
result += "" + tag2(node) + ">";
}
function render2(event) {
(event.event === "start" ? open5 : close)(event.node);
}
while (original.length || highlighted.length) {
let stream4 = selectStream();
result += escapeHTML(value.substring(processed, stream4[0].offset));
processed = stream4[0].offset;
if (stream4 === original) {
nodeStack.reverse().forEach(close);
do {
render2(stream4.splice(0, 1)[0]);
stream4 = selectStream();
} while (stream4 === original && stream4.length && stream4[0].offset === processed);
nodeStack.reverse().forEach(open5);
} else {
if (stream4[0].event === "start") {
nodeStack.push(stream4[0].node);
} else {
nodeStack.pop();
}
render2(stream4.splice(0, 1)[0]);
}
}
return result + escapeHTML(value.substr(processed));
}
var seenDeprecations = {};
var error44 = (message) => {
console.error(message);
};
var warn = (message, ...args) => {
console.log(`WARN: ${message}`, ...args);
};
var deprecated = (version3, message) => {
if (seenDeprecations[`${version3}/${message}`])
return;
console.log(`Deprecated as of ${version3}. ${message}`);
seenDeprecations[`${version3}/${message}`] = true;
};
var escape$1 = escapeHTML;
var inherit$1 = inherit;
var NO_MATCH = Symbol("nomatch");
var HLJS = function(hljs) {
const languages = Object.create(null);
const aliases = Object.create(null);
const plugins = [];
let SAFE_MODE = true;
const fixMarkupRe = /(^(<[^>]+>|\t|)+|\n)/gm;
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 options2 = {
noHighlightRe: /^(no-?highlight)$/i,
languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
classPrefix: "hljs-",
tabReplace: null,
useBR: false,
languages: null,
__emitter: TokenTreeEmitter
};
function shouldNotHighlight(languageName) {
return options2.noHighlightRe.test(languageName);
}
function blockLanguage(block2) {
let classes = block2.className + " ";
classes += block2.parentNode ? block2.parentNode.className : "";
const match = options2.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.", block2);
}
return language ? match[1] : "no-highlight";
}
return classes.split(/\s+/).find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
}
function highlight2(codeOrlanguageName, optionsOrCode, ignoreIllegals, continuation) {
let code = "";
let languageName = "";
if (typeof optionsOrCode === "object") {
code = codeOrlanguageName;
ignoreIllegals = optionsOrCode.ignoreIllegals;
languageName = optionsOrCode.language;
continuation = undefined;
} 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;
}
const context5 = {
code,
language: languageName
};
fire("before:highlight", context5);
const result = context5.result ? context5.result : _highlight(context5.language, context5.code, ignoreIllegals, continuation);
result.code = context5.code;
fire("after:highlight", result);
return result;
}
function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
function keywordData(mode, match) {
const matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];
return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && 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 data = keywordData(top, match);
if (data) {
const [kind, keywordRelevance] = data;
emitter.addText(buf);
buf = "";
relevance += keywordRelevance;
if (kind.startsWith("_")) {
buf += match[0];
} else {
const cssClass = language.classNameAliases[kind] || kind;
emitter.addKeyword(match[0], cssClass);
}
} else {
buf += match[0];
}
lastIndex = top.keywordPatternRe.lastIndex;
match = top.keywordPatternRe.exec(modeBuffer);
}
buf += modeBuffer.substr(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 startNewMode(mode) {
if (mode.className) {
emitter.openNode(language.classNameAliases[mode.className] || mode.className);
}
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 Response2(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 Response2(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 && newMode.endSameAsBegin) {
newMode.endRe = escape3(lexeme);
}
if (newMode.skip) {
modeBuffer += lexeme;
} else {
if (newMode.excludeBegin) {
modeBuffer += lexeme;
}
processBuffer();
if (!newMode.returnBegin && !newMode.excludeBegin) {
modeBuffer = lexeme;
}
}
startNewMode(newMode);
return newMode.returnBegin ? 0 : lexeme.length;
}
function doEndMatch(match) {
const lexeme = match[0];
const matchPlusRemainder = codeToHighlight.substr(match.index);
const endMode = endOfMode(top, match, matchPlusRemainder);
if (!endMode) {
return NO_MATCH;
}
const origin2 = top;
if (origin2.skip) {
modeBuffer += lexeme;
} else {
if (!(origin2.returnEnd || origin2.excludeEnd)) {
modeBuffer += lexeme;
}
processBuffer();
if (origin2.excludeEnd) {
modeBuffer = lexeme;
}
}
do {
if (top.className) {
emitter.closeNode();
}
if (!top.skip && !top.subLanguage) {
relevance += top.relevance;
}
top = top.parent;
} while (top !== endMode.parent);
if (endMode.starts) {
if (endMode.endSameAsBegin) {
endMode.starts.endRe = endMode.endRe;
}
startNewMode(endMode.starts);
}
return origin2.returnEnd ? 0 : lexeme.length;
}
function processContinuations() {
const list2 = [];
for (let current = top;current !== language; current = current.parent) {
if (current.className) {
list2.unshift(current.className);
}
}
list2.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");
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.className || "") + '"');
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 === "") {
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) {
error44(LANGUAGE_NOT_FOUND.replace("{}", languageName));
throw new Error('Unknown language: "' + languageName + '"');
}
const md = compileLanguage(language, { plugins });
let result = "";
let top = continuation || md;
const continuations = {};
const emitter = new options2.__emitter(options2);
processContinuations();
let modeBuffer = "";
let relevance = 0;
let index = 0;
let iterations = 0;
let resumeScanAtSamePosition = false;
try {
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.substr(index));
emitter.closeAllNodes();
emitter.finalize();
result = emitter.toHTML();
return {
relevance: Math.floor(relevance),
value: result,
language: languageName,
illegal: false,
emitter,
top
};
} catch (err2) {
if (err2.message && err2.message.includes("Illegal")) {
return {
illegal: true,
illegalBy: {
msg: err2.message,
context: codeToHighlight.slice(index - 100, index + 100),
mode: err2.mode
},
sofar: result,
relevance: 0,
value: escape$1(codeToHighlight),
emitter
};
} else if (SAFE_MODE) {
return {
illegal: false,
relevance: 0,
value: escape$1(codeToHighlight),
emitter,
language: languageName,
top,
errorRaised: err2
};
} else {
throw err2;
}
}
}
function justTextHighlightResult(code) {
const result = {
relevance: 0,
emitter: new options2.__emitter(options2),
value: escape$1(code),
illegal: false,
top: PLAINTEXT_LANGUAGE
};
result.emitter.addText(code);
return result;
}
function highlightAuto(code, languageSubset) {
languageSubset = languageSubset || options2.languages || Object.keys(languages);
const plaintext = justTextHighlightResult(code);
const results = languageSubset.filter(getLanguage).filter(autoDetection).map((name) => _highlight(name, code, false));
results.unshift(plaintext);
const sorted = results.sort((a2, b) => {
if (a2.relevance !== b.relevance)
return b.relevance - a2.relevance;
if (a2.language && b.language) {
if (getLanguage(a2.language).supersetOf === b.language) {
return 1;
} else if (getLanguage(b.language).supersetOf === a2.language) {
return -1;
}
}
return 0;
});
const [best, secondBest] = sorted;
const result = best;
result.second_best = secondBest;
return result;
}
function fixMarkup(html2) {
if (!(options2.tabReplace || options2.useBR)) {
return html2;
}
return html2.replace(fixMarkupRe, (match) => {
if (match === `
`) {
return options2.useBR ? "
" : match;
} else if (options2.tabReplace) {
return match.replace(/\t/g, options2.tabReplace);
}
return match;
});
}
function updateClassName(element, currentLang, resultLang) {
const language = currentLang ? aliases[currentLang] : resultLang;
element.classList.add("hljs");
if (language)
element.classList.add(language);
}
const brPlugin = {
"before:highlightElement": ({ el }) => {
if (options2.useBR) {
el.innerHTML = el.innerHTML.replace(/\n/g, "").replace(/
/g, `
`);
}
},
"after:highlightElement": ({ result }) => {
if (options2.useBR) {
result.value = result.value.replace(/\n/g, "
");
}
}
};
const TAB_REPLACE_RE = /^(<[^>]+>|\t)+/gm;
const tabReplacePlugin = {
"after:highlightElement": ({ result }) => {
if (options2.tabReplace) {
result.value = result.value.replace(TAB_REPLACE_RE, (m) => m.replace(/\t/g, options2.tabReplace));
}
}
};
function highlightElement(element) {
let node = null;
const language = blockLanguage(element);
if (shouldNotHighlight(language))
return;
fire("before:highlightElement", { el: element, language });
node = element;
const text = node.textContent;
const result = language ? highlight2(text, { language, ignoreIllegals: true }) : highlightAuto(text);
fire("after:highlightElement", { el: element, result, text });
element.innerHTML = result.value;
updateClassName(element, language, result.language);
element.result = {
language: result.language,
re: result.relevance,
relavance: result.relevance
};
if (result.second_best) {
element.second_best = {
language: result.second_best.language,
re: result.second_best.relevance,
relavance: result.second_best.relevance
};
}
}
function configure(userOptions) {
if (userOptions.useBR) {
deprecated("10.3.0", "'useBR' will be removed entirely in v11.0");
deprecated("10.3.0", "Please see https://github.com/highlightjs/highlight.js/issues/2559");
}
options2 = inherit$1(options2, userOptions);
}
const initHighlighting = () => {
if (initHighlighting.called)
return;
initHighlighting.called = true;
deprecated("10.6.0", "initHighlighting() is deprecated. Use highlightAll() instead.");
const blocks = document.querySelectorAll("pre code");
blocks.forEach(highlightElement);
};
function initHighlightingOnLoad() {
deprecated("10.6.0", "initHighlightingOnLoad() is deprecated. Use highlightAll() instead.");
wantsHighlight = true;
}
let wantsHighlight = false;
function highlightAll() {
if (document.readyState === "loading") {
wantsHighlight = true;
return;
}
const blocks = document.querySelectorAll("pre code");
blocks.forEach(highlightElement);
}
function boot() {
if (wantsHighlight)
highlightAll();
}
if (typeof window !== "undefined" && window.addEventListener) {
window.addEventListener("DOMContentLoaded", boot, false);
}
function registerLanguage(languageName, languageDefinition) {
let lang = null;
try {
lang = languageDefinition(hljs);
} catch (error$1) {
error44("Language definition for '{}' could not be registered.".replace("{}", languageName));
if (!SAFE_MODE) {
throw error$1;
} else {
error44(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 requireLanguage(name) {
deprecated("10.4.0", "requireLanguage will be removed entirely in v11.");
deprecated("10.4.0", "Please see https://github.com/highlightjs/highlight.js/pull/2844");
const lang = getLanguage(name);
if (lang) {
return lang;
}
const err2 = new Error("The '{}' language is required, but not loaded.".replace("{}", name));
throw err2;
}
function getLanguage(name) {
name = (name || "").toLowerCase();
return languages[name] || languages[aliases[name]];
}
function registerAliases(aliasList, { languageName }) {
if (typeof aliasList === "string") {
aliasList = [aliasList];
}
aliasList.forEach((alias) => {
aliases[alias.toLowerCase()] = languageName;
});
}
function autoDetection(name) {
const lang = getLanguage(name);
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 fire(event, args) {
const cb = event;
plugins.forEach(function(plugin) {
if (plugin[cb]) {
plugin[cb](args);
}
});
}
function deprecateFixMarkup(arg) {
deprecated("10.2.0", "fixMarkup will be removed entirely in v11.0");
deprecated("10.2.0", "Please see https://github.com/highlightjs/highlight.js/issues/2534");
return fixMarkup(arg);
}
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,
fixMarkup: deprecateFixMarkup,
highlightElement,
highlightBlock: deprecateHighlightBlock,
configure,
initHighlighting,
initHighlightingOnLoad,
registerLanguage,
unregisterLanguage,
listLanguages,
getLanguage,
registerAliases,
requireLanguage,
autoDetection,
inherit: inherit$1,
addPlugin,
vuePlugin: BuildVuePlugin(hljs).VuePlugin
});
hljs.debugMode = function() {
SAFE_MODE = false;
};
hljs.safeMode = function() {
SAFE_MODE = true;
};
hljs.versionString = version2;
for (const key in MODES) {
if (typeof MODES[key] === "object") {
deepFreezeEs6(MODES[key]);
}
}
Object.assign(hljs, MODES);
hljs.addPlugin(brPlugin);
hljs.addPlugin(mergeHTMLPlugin);
hljs.addPlugin(tabReplacePlugin);
return hljs;
};
var highlight = HLJS({});
module.exports = highlight;
});
// node_modules/highlight.js/lib/languages/1c.js
var require_1c = __commonJS((exports, module) => {
function _1c(hljs) {
var UNDERSCORE_IDENT_RE = "[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+";
var v7_keywords = "далее ";
var v8_keywords = "возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли " + "конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт ";
var KEYWORD = v7_keywords + v8_keywords;
var v7_meta_keywords = "загрузитьизфайла ";
var v8_meta_keywords = "вебклиент вместо внешнеесоединение клиент конецобласти мобильноеприложениеклиент мобильноеприложениесервер " + "наклиенте наклиентенасервере наклиентенасерверебезконтекста насервере насерверебезконтекста область перед " + "после сервер толстыйклиентобычноеприложение толстыйклиентуправляемоеприложение тонкийклиент ";
var METAKEYWORD = v7_meta_keywords + v8_meta_keywords;
var v7_system_constants = "разделительстраниц разделительстрок символтабуляции ";
var v7_global_context_methods = "ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов " + "датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя " + "кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца " + "коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид " + "назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца " + "начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов " + "основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута " + "получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта " + "префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына " + "рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента " + "счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон ";
var 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 установитьчасовойпоясинформационнойбазы установитьчасовойпояссеанса " + "формат цел час часовойпояс часовойпояссеанса число числопрописью этоадресвременногохранилища ";
var v8_global_context_property = "wsссылки библиотекакартинок библиотекамакетовоформлениякомпоновкиданных библиотекастилей бизнеспроцессы " + "внешниеисточникиданных внешниеобработки внешниеотчеты встроенныепокупки главныйинтерфейс главныйстиль " + "документы доставляемыеуведомления журналыдокументов задачи информацияобинтернетсоединении использованиерабочейдаты " + "историяработыпользователя константы критерииотбора метаданные обработки отображениерекламы отправкадоставляемыхуведомлений " + "отчеты панельзадачос параметрзапуска параметрысеанса перечисления планывидоврасчета планывидовхарактеристик " + "планыобмена планысчетов полнотекстовыйпоиск пользователиинформационнойбазы последовательности проверкавстроенныхпокупок " + "рабочаядата расширенияконфигурации регистрыбухгалтерии регистрынакопления регистрырасчета регистрысведений " + "регламентныезадания сериализаторxdto справочники средствагеопозиционирования средствакриптографии средствамультимедиа " + "средстваотображениярекламы средствапочты средствателефонии фабрикаxdto файловыепотоки фоновыезадания хранилищанастроек " + "хранилищевариантовотчетов хранилищенастроекданныхформ хранилищеобщихнастроек хранилищепользовательскихнастроекдинамическихсписков " + "хранилищепользовательскихнастроекотчетов хранилищесистемныхнастроек ";
var BUILTIN = v7_system_constants + v7_global_context_methods + v8_global_context_methods + v8_global_context_property;
var v8_system_sets_of_values = "webцвета windowsцвета windowsшрифты библиотекакартинок рамкистиля символы цветастиля шрифтыстиля ";
var v8_system_enums_interface = "автоматическоесохранениеданныхформывнастройках автонумерациявформе автораздвижениесерий " + "анимациядиаграммы вариантвыравниванияэлементовизаголовков вариантуправлениявысотойтаблицы " + "вертикальнаяпрокруткаформы вертикальноеположение вертикальноеположениеэлемента видгруппыформы " + "виддекорацииформы виддополненияэлементаформы видизмененияданных видкнопкиформы видпереключателя " + "видподписейкдиаграмме видполяформы видфлажка влияниеразмеранапузырекдиаграммы горизонтальноеположение " + "горизонтальноеположениеэлемента группировкаколонок группировкаподчиненныхэлементовформы " + "группыиэлементы действиеперетаскивания дополнительныйрежимотображения допустимыедействияперетаскивания " + "интервалмеждуэлементамиформы использованиевывода использованиеполосыпрокрутки " + "используемоезначениеточкибиржевойдиаграммы историявыборапривводе источникзначенийоситочекдиаграммы " + "источникзначенияразмерапузырькадиаграммы категориягруппыкоманд максимумсерий начальноеотображениедерева " + "начальноеотображениесписка обновлениетекстаредактирования ориентациядендрограммы ориентациядиаграммы " + "ориентацияметокдиаграммы ориентацияметоксводнойдиаграммы ориентацияэлементаформы отображениевдиаграмме " + "отображениевлегендедиаграммы отображениегруппыкнопок отображениезаголовкашкалыдиаграммы " + "отображениезначенийсводнойдиаграммы отображениезначенияизмерительнойдиаграммы " + "отображениеинтерваладиаграммыганта отображениекнопки отображениекнопкивыбора отображениеобсужденийформы " + "отображениеобычнойгруппы отображениеотрицательныхзначенийпузырьковойдиаграммы отображениепанелипоиска " + "отображениеподсказки отображениепредупрежденияприредактировании отображениеразметкиполосырегулирования " + "отображениестраницформы отображениетаблицы отображениетекстазначениядиаграммыганта " + "отображениеуправленияобычнойгруппы отображениефигурыкнопки палитрацветовдиаграммы поведениеобычнойгруппы " + "поддержкамасштабадендрограммы поддержкамасштабадиаграммыганта поддержкамасштабасводнойдиаграммы " + "поисквтаблицепривводе положениезаголовкаэлементаформы положениекартинкикнопкиформы " + "положениекартинкиэлементаграфическойсхемы положениекоманднойпанелиформы положениекоманднойпанелиэлементаформы " + "положениеопорнойточкиотрисовки положениеподписейкдиаграмме положениеподписейшкалызначенийизмерительнойдиаграммы " + "положениесостоянияпросмотра положениестрокипоиска положениетекстасоединительнойлинии положениеуправленияпоиском " + "положениешкалывремени порядокотображенияточекгоризонтальнойгистограммы порядоксерийвлегендедиаграммы " + "размеркартинки расположениезаголовкашкалыдиаграммы растягиваниеповертикалидиаграммыганта " + "режимавтоотображениясостояния режимвводастроктаблицы режимвыборанезаполненного режимвыделениядаты " + "режимвыделениястрокитаблицы режимвыделениятаблицы режимизмененияразмера режимизменениясвязанногозначения " + "режимиспользованиядиалогапечати режимиспользованияпараметракоманды режиммасштабированияпросмотра " + "режимосновногоокнаклиентскогоприложения режимоткрытияокнаформы режимотображениявыделения " + "режимотображениягеографическойсхемы режимотображениязначенийсерии режимотрисовкисеткиграфическойсхемы " + "режимполупрозрачностидиаграммы режимпробеловдиаграммы режимразмещениянастранице режимредактированияколонки " + "режимсглаживаниядиаграммы режимсглаживанияиндикатора режимсписказадач сквозноевыравнивание " + "сохранениеданныхформывнастройках способзаполнениятекстазаголовкашкалыдиаграммы " + "способопределенияограничивающегозначениядиаграммы стандартнаягруппакоманд стандартноеоформление " + "статусоповещенияпользователя стильстрелки типаппроксимациилиниитрендадиаграммы типдиаграммы " + "типединицышкалывремени типимпортасерийслоягеографическойсхемы типлиниигеографическойсхемы типлиниидиаграммы " + "типмаркерагеографическойсхемы типмаркерадиаграммы типобластиоформления " + "типорганизацииисточникаданныхгеографическойсхемы типотображениясериислоягеографическойсхемы " + "типотображенияточечногообъектагеографическойсхемы типотображенияшкалыэлементалегендыгеографическойсхемы " + "типпоискаобъектовгеографическойсхемы типпроекциигеографическойсхемы типразмещенияизмерений " + "типразмещенияреквизитовизмерений типрамкиэлементауправления типсводнойдиаграммы " + "типсвязидиаграммыганта типсоединениязначенийпосериямдиаграммы типсоединенияточекдиаграммы " + "типсоединительнойлинии типстороныэлементаграфическойсхемы типформыотчета типшкалырадарнойдиаграммы " + "факторлиниитрендадиаграммы фигуракнопки фигурыграфическойсхемы фиксациявтаблице форматдняшкалывремени " + "форматкартинки ширинаподчиненныхэлементовформы ";
var v8_system_enums_objects_properties = "виддвижениябухгалтерии виддвижениянакопления видпериодарегистрарасчета видсчета видточкимаршрутабизнеспроцесса " + "использованиеагрегатарегистранакопления использованиегруппиэлементов использованиережимапроведения " + "использованиесреза периодичностьагрегатарегистранакопления режимавтовремя режимзаписидокумента режимпроведениядокумента ";
var v8_system_enums_exchange_plans = "авторегистрацияизменений допустимыйномерсообщения отправкаэлементаданных получениеэлементаданных ";
var v8_system_enums_tabular_document = "использованиерасшифровкитабличногодокумента ориентациястраницы положениеитоговколоноксводнойтаблицы " + "положениеитоговстроксводнойтаблицы положениетекстаотносительнокартинки расположениезаголовкагруппировкитабличногодокумента " + "способчтениязначенийтабличногодокумента типдвустороннейпечати типзаполненияобластитабличногодокумента " + "типкурсоровтабличногодокумента типлиниирисункатабличногодокумента типлинииячейкитабличногодокумента " + "типнаправленияпереходатабличногодокумента типотображениявыделениятабличногодокумента типотображениялинийсводнойтаблицы " + "типразмещениятекстатабличногодокумента типрисункатабличногодокумента типсмещениятабличногодокумента " + "типузоратабличногодокумента типфайлатабличногодокумента точностьпечати чередованиерасположениястраниц ";
var v8_system_enums_sheduler = "отображениевремениэлементовпланировщика ";
var v8_system_enums_formatted_document = "типфайлаформатированногодокумента ";
var v8_system_enums_query = "обходрезультатазапроса типзаписизапроса ";
var v8_system_enums_report_builder = "видзаполнениярасшифровкипостроителяотчета типдобавленияпредставлений типизмеренияпостроителяотчета типразмещенияитогов ";
var v8_system_enums_files = "доступкфайлу режимдиалогавыборафайла режимоткрытияфайла ";
var v8_system_enums_query_builder = "типизмеренияпостроителязапроса ";
var v8_system_enums_data_analysis = "видданныханализа методкластеризации типединицыинтервалавременианализаданных типзаполнениятаблицырезультатаанализаданных " + "типиспользованиячисловыхзначенийанализаданных типисточникаданныхпоискаассоциаций типколонкианализаданныхдереворешений " + "типколонкианализаданныхкластеризация типколонкианализаданныхобщаястатистика типколонкианализаданныхпоискассоциаций " + "типколонкианализаданныхпоискпоследовательностей типколонкимоделипрогноза типмерырасстоянияанализаданных " + "типотсеченияправилассоциации типполяанализаданных типстандартизациианализаданных типупорядочиванияправилассоциациианализаданных " + "типупорядочиванияшаблоновпоследовательностейанализаданных типупрощениядереварешений ";
var 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 ";
var v8_system_enums_data_composition_system = "видсравнениякомпоновкиданных действиеобработкирасшифровкикомпоновкиданных направлениесортировкикомпоновкиданных " + "расположениевложенныхэлементоврезультатакомпоновкиданных расположениеитоговкомпоновкиданных расположениегруппировкикомпоновкиданных " + "расположениеполейгруппировкикомпоновкиданных расположениеполякомпоновкиданных расположениереквизитовкомпоновкиданных " + "расположениересурсовкомпоновкиданных типбухгалтерскогоостаткакомпоновкиданных типвыводатекстакомпоновкиданных " + "типгруппировкикомпоновкиданных типгруппыэлементовотборакомпоновкиданных типдополненияпериодакомпоновкиданных " + "типзаголовкаполейкомпоновкиданных типмакетагруппировкикомпоновкиданных типмакетаобластикомпоновкиданных типостаткакомпоновкиданных " + "типпериодакомпоновкиданных типразмещениятекстакомпоновкиданных типсвязинаборовданныхкомпоновкиданных типэлементарезультатакомпоновкиданных " + "расположениелегендыдиаграммыкомпоновкиданных типпримененияотборакомпоновкиданных режимотображенияэлементанастройкикомпоновкиданных " + "режимотображениянастроеккомпоновкиданных состояниеэлементанастройкикомпоновкиданных способвосстановлениянастроеккомпоновкиданных " + "режимкомпоновкирезультата использованиепараметракомпоновкиданных автопозицияресурсовкомпоновкиданных " + "вариантиспользованиягруппировкикомпоновкиданных расположениересурсоввдиаграммекомпоновкиданных фиксациякомпоновкиданных " + "использованиеусловногооформлениякомпоновкиданных ";
var v8_system_enums_email = "важностьинтернетпочтовогосообщения обработкатекстаинтернетпочтовогосообщения способкодированияинтернетпочтовоговложения " + "способкодированиянеasciiсимволовинтернетпочтовогосообщения типтекстапочтовогосообщения протоколинтернетпочты " + "статусразборапочтовогосообщения ";
var v8_system_enums_logbook = "режимтранзакциизаписижурналарегистрации статустранзакциизаписижурналарегистрации уровеньжурналарегистрации ";
var v8_system_enums_cryptography = "расположениехранилищасертификатовкриптографии режимвключениясертификатовкриптографии режимпроверкисертификатакриптографии " + "типхранилищасертификатовкриптографии ";
var v8_system_enums_zip = "кодировкаименфайловвzipфайле методсжатияzip методшифрованияzip режимвосстановленияпутейфайловzip режимобработкиподкаталоговzip " + "режимсохраненияпутейzip уровеньсжатияzip ";
var v8_system_enums_other = "звуковоеоповещение направлениепереходакстроке позициявпотоке порядокбайтов режимблокировкиданных режимуправленияблокировкойданных " + "сервисвстроенныхпокупок состояниефоновогозадания типподписчикадоставляемыхуведомлений уровеньиспользованиязащищенногосоединенияftp ";
var v8_system_enums_request_schema = "направлениепорядкасхемызапроса типдополненияпериодамисхемызапроса типконтрольнойточкисхемызапроса типобъединениясхемызапроса " + "типпараметрадоступнойтаблицысхемызапроса типсоединениясхемызапроса ";
var v8_system_enums_properties_of_metadata_objects = "httpметод автоиспользованиеобщегореквизита автопрефиксномеразадачи вариантвстроенногоязыка видиерархии видрегистранакопления " + "видтаблицывнешнегоисточникаданных записьдвиженийприпроведении заполнениепоследовательностей индексирование " + "использованиебазыпланавидоврасчета использованиебыстроговыбора использованиеобщегореквизита использованиеподчинения " + "использованиеполнотекстовогопоиска использованиеразделяемыхданныхобщегореквизита использованиереквизита " + "назначениеиспользованияприложения назначениерасширенияконфигурации направлениепередачи обновлениепредопределенныхданных " + "оперативноепроведение основноепредставлениевидарасчета основноепредставлениевидахарактеристики основноепредставлениезадачи " + "основноепредставлениепланаобмена основноепредставлениесправочника основноепредставлениесчета перемещениеграницыприпроведении " + "периодичностьномерабизнеспроцесса периодичностьномерадокумента периодичностьрегистрарасчета периодичностьрегистрасведений " + "повторноеиспользованиевозвращаемыхзначений полнотекстовыйпоискпривводепостроке принадлежностьобъекта проведение " + "разделениеаутентификацииобщегореквизита разделениеданныхобщегореквизита разделениерасширенийконфигурацииобщегореквизита " + "режимавтонумерацииобъектов режимзаписирегистра режимиспользованиямодальности " + "режимиспользованиясинхронныхвызововрасширенийплатформыивнешнихкомпонент режимповторногоиспользованиясеансов " + "режимполученияданныхвыборапривводепостроке режимсовместимости режимсовместимостиинтерфейса " + "режимуправленияблокировкойданныхпоумолчанию сериикодовпланавидовхарактеристик сериикодовпланасчетов " + "сериикодовсправочника созданиепривводе способвыбора способпоискастрокипривводепостроке способредактирования " + "типданныхтаблицывнешнегоисточникаданных типкодапланавидоврасчета типкодасправочника типмакета типномерабизнеспроцесса " + "типномерадокумента типномеразадачи типформы удалениедвижений ";
var v8_system_enums_differents = "важностьпроблемыприменениярасширенияконфигурации вариантинтерфейсаклиентскогоприложения вариантмасштабаформклиентскогоприложения " + "вариантосновногошрифтаклиентскогоприложения вариантстандартногопериода вариантстандартнойдатыначала видграницы видкартинки " + "видотображенияполнотекстовогопоиска видрамки видсравнения видцвета видчисловогозначения видшрифта допустимаядлина допустимыйзнак " + "использованиеbyteordermark использованиеметаданныхполнотекстовогопоиска источникрасширенийконфигурации клавиша кодвозвратадиалога " + "кодировкаxbase кодировкатекста направлениепоиска направлениесортировки обновлениепредопределенныхданных обновлениеприизмененииданных " + "отображениепанелиразделов проверказаполнения режимдиалогавопрос режимзапускаклиентскогоприложения режимокругления режимоткрытияформприложения " + "режимполнотекстовогопоиска скоростьклиентскогосоединения состояниевнешнегоисточникаданных состояниеобновленияконфигурациибазыданных " + "способвыборасертификатаwindows способкодированиястроки статуссообщения типвнешнейкомпоненты типплатформы типповеденияклавишиenter " + "типэлементаинформацииовыполненииобновленияконфигурациибазыданных уровеньизоляциитранзакций хешфункция частидаты";
var 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;
var 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 шрифт элементрезультатакомпоновкиданных ";
var v8_universal_collection = "comsafearray деревозначений массив соответствие списокзначений структура таблицазначений фиксированнаяструктура " + "фиксированноесоответствие фиксированныймассив ";
var TYPE = v8_shared_object + v8_universal_collection;
var LITERAL = "null истина ложь неопределено";
var NUMBERS = hljs.inherit(hljs.NUMBER_MODE);
var STRINGS = {
className: "string",
begin: '"|\\|',
end: '"|$',
contains: [{ begin: '""' }]
};
var DATE = {
begin: "'",
end: "'",
excludeBegin: true,
excludeEnd: true,
contains: [
{
className: "number",
begin: "\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}"
}
]
};
var COMMENTS = hljs.inherit(hljs.C_LINE_COMMENT_MODE);
var META = {
className: "meta",
begin: "#|&",
end: "$",
keywords: {
$pattern: UNDERSCORE_IDENT_RE,
"meta-keyword": KEYWORD + METAKEYWORD
},
contains: [
COMMENTS
]
};
var SYMBOL = {
className: "symbol",
begin: "~",
end: ";|:",
excludeEnd: true
};
var 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
]
};
}
module.exports = _1c;
});
// node_modules/highlight.js/lib/languages/abnf.js
var require_abnf = __commonJS((exports, module) => {
function source(re) {
if (!re)
return null;
if (typeof re === "string")
return re;
return re.source;
}
function concat(...args) {
const joined = args.map((x3) => source(x3)).join("");
return joined;
}
function abnf(hljs) {
const regexes = {
ruleDeclaration: /^[a-zA-Z][a-zA-Z0-9-]*/,
unexpectedChars: /[!@#$^&',?+~`|:]/
};
const keywords = [
"ALPHA",
"BIT",
"CHAR",
"CR",
"CRLF",
"CTL",
"DIGIT",
"DQUOTE",
"HEXDIG",
"HTAB",
"LF",
"LWSP",
"OCTET",
"SP",
"VCHAR",
"WSP"
];
const commentMode = hljs.COMMENT(/;/, /$/);
const terminalBinaryMode = {
className: "symbol",
begin: /%b[0-1]+(-[0-1]+|(\.[0-1]+)+){0,1}/
};
const terminalDecimalMode = {
className: "symbol",
begin: /%d[0-9]+(-[0-9]+|(\.[0-9]+)+){0,1}/
};
const terminalHexadecimalMode = {
className: "symbol",
begin: /%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+){0,1}/
};
const caseSensitivityIndicatorMode = {
className: "symbol",
begin: /%[si]/
};
const ruleDeclarationMode = {
className: "attribute",
begin: concat(regexes.ruleDeclaration, /(?=\s*=)/)
};
return {
name: "Augmented Backus-Naur Form",
illegal: regexes.unexpectedChars,
keywords,
contains: [
ruleDeclarationMode,
commentMode,
terminalBinaryMode,
terminalDecimalMode,
terminalHexadecimalMode,
caseSensitivityIndicatorMode,
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE
]
};
}
module.exports = abnf;
});
// node_modules/highlight.js/lib/languages/accesslog.js
var require_accesslog = __commonJS((exports, module) => {
function source(re) {
if (!re)
return null;
if (typeof re === "string")
return re;
return re.source;
}
function concat(...args) {
const joined = args.map((x3) => source(x3)).join("");
return joined;
}
function either(...args) {
const joined = "(" + args.map((x3) => source(x3)).join("|") + ")";
return joined;
}
function accesslog(_hljs) {
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: concat(/"/, 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/highlight.js/lib/languages/actionscript.js
var require_actionscript = __commonJS((exports, module) => {
function source(re) {
if (!re)
return null;
if (typeof re === "string")
return re;
return re.source;
}
function concat(...args) {
const joined = args.map((x3) => source(x3)).join("");
return joined;
}
function actionscript(hljs) {
const IDENT_RE = /[a-zA-Z_$][a-zA-Z0-9_$]*/;
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
};
return {
name: "ActionScript",
aliases: ["as"],
keywords: {
keyword: "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",
literal: "true false null undefined"
},
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_NUMBER_MODE,
{
className: "class",
beginKeywords: "package",
end: /\{/,
contains: [hljs.TITLE_MODE]
},
{
className: "class",
beginKeywords: "class interface",
end: /\{/,
excludeEnd: true,
contains: [
{ beginKeywords: "extends implements" },
hljs.TITLE_MODE
]
},
{
className: "meta",
beginKeywords: "import include",
end: /;/,
keywords: { "meta-keyword": "import include" }
},
{
className: "function",
beginKeywords: "function",
end: /[{;]/,
excludeEnd: true,
illegal: /\S/,
contains: [
hljs.TITLE_MODE,
{
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: concat(/:\s*/, IDENT_FUNC_RETURN_TYPE_RE) }
]
},
hljs.METHOD_GUARD
],
illegal: /#/
};
}
module.exports = actionscript;
});
// 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
}
]
};
return {
name: "Ada",
case_insensitive: true,
keywords: {
keyword: "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",
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/highlight.js/lib/languages/angelscript.js
var require_angelscript = __commonJS((exports, module) => {
function angelscript(hljs) {
var builtInTypeMode = {
className: "built_in",
begin: "\\b(void|bool|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|string|ref|array|double|float|auto|dictionary)"
};
var objectHandleMode = {
className: "symbol",
begin: "[a-zA-Z0-9_]+@"
};
var genericMode = {
className: "keyword",
begin: "<",
end: ">",
contains: [builtInTypeMode, objectHandleMode]
};
builtInTypeMode.contains = [genericMode];
objectHandleMode.contains = [genericMode];
return {
name: "AngelScript",
aliases: ["asc"],
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",
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/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: /\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: {
nomarkup: "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: [
{
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/highlight.js/lib/languages/applescript.js
var require_applescript = __commonJS((exports, module) => {
function source(re) {
if (!re)
return null;
if (typeof re === "string")
return re;
return re.source;
}
function concat(...args) {
const joined = args.map((x3) => source(x3)).join("");
return joined;
}
function either(...args) {
const joined = "(" + args.map((x3) => source(x3)).join("|") + ")";
return joined;
}
function applescript(hljs) {
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 paragraph paragraphs rest reverse running time version " + "weekday word words year"
},
contains: [
STRING,
hljs.C_NUMBER_MODE,
{
className: "built_in",
begin: concat(/\b/, 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: concat(/\b/, either(...KEYWORD_PATTERNS), /\b/)
},
{
beginKeywords: "on",
illegal: /[${=;\n]/,
contains: [
hljs.UNDERSCORE_TITLE_MODE,
PARAMS
]
},
...COMMENTS
],
illegal: /\/\/|->|=>|\[\[/
};
}
module.exports = applescript;
});
// node_modules/highlight.js/lib/languages/arcade.js
var require_arcade = __commonJS((exports, module) => {
function arcade(hljs) {
const IDENT_RE = "[A-Za-z_][0-9A-Za-z_]*";
const KEYWORDS = {
keyword: "if for while var new function do return void else break",
literal: "BackSlash DoubleQuote false ForwardSlash Infinity NaN NewLine null PI SingleQuote Tab TextFormatting true undefined",
built_in: "Abs Acos Angle Attachments Area AreaGeodetic Asin Atan Atan2 Average Bearing Boolean Buffer BufferGeodetic " + "Ceil Centroid Clip Console Constrain Contains Cos Count Crosses Cut Date DateAdd " + "DateDiff Day Decode DefaultValue Dictionary Difference Disjoint Distance DistanceGeodetic Distinct " + "DomainCode DomainName Equals Exp Extent Feature FeatureSet FeatureSetByAssociation FeatureSetById FeatureSetByPortalItem " + "FeatureSetByRelationshipName FeatureSetByTitle FeatureSetByUrl Filter First Floor Geometry GroupBy Guid HasKey Hour IIf IndexOf " + "Intersection Intersects IsEmpty IsNan IsSelfIntersecting Length LengthGeodetic Log Max Mean Millisecond Min Minute Month " + "MultiPartToSinglePart Multipoint NextSequenceValue Now Number OrderBy Overlaps Point Polygon " + "Polyline Portal Pow Random Relate Reverse RingIsClockWise Round Second SetGeometry Sin Sort Sqrt Stdev Sum " + "SymmetricDifference Tan Text Timestamp Today ToLocal Top Touches ToUTC TrackCurrentTime " + "TrackGeometryWindow TrackIndex TrackStartTime TrackWindow TypeOf Union UrlEncode Variance " + "Weekday When Within Year "
};
const SYMBOL = {
className: "symbol",
begin: "\\$[datastore|feature|layer|map|measure|sourcefeature|sourcelayer|targetfeature|targetlayer|value|view]+"
};
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",
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
},
{
className: "function",
beginKeywords: "function",
end: /\{/,
excludeEnd: true,
contains: [
hljs.inherit(hljs.TITLE_MODE, {
begin: IDENT_RE
}),
{
className: "params",
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
contains: PARAMS_CONTAINS
}
],
illegal: /\[|%/
},
{
begin: /\$[(.]/
}
],
illegal: /#(?!!)/
};
}
module.exports = arcade;
});
// node_modules/highlight.js/lib/languages/arduino.js
var require_arduino = __commonJS((exports, module) => {
function source(re) {
if (!re)
return null;
if (typeof re === "string")
return re;
return re.source;
}
function lookahead(re) {
return concat("(?=", re, ")");
}
function optional2(re) {
return concat("(", re, ")?");
}
function concat(...args) {
const joined = args.map((x3) => source(x3)).join("");
return joined;
}
function cPlusPlus(hljs) {
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 = "(" + DECLTYPE_AUTO_RE + "|" + optional2(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + optional2(TEMPLATE_ARGUMENT_RE) + ")";
const CPP_PRIMITIVE_TYPES = {
className: "keyword",
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: "\\b(0b[01']+)"
},
{
begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)"
},
{
begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
}
],
relevance: 0
};
const PREPROCESSOR = {
className: "meta",
begin: /#\s*[a-z]+\b/,
end: /$/,
keywords: {
"meta-keyword": "if else elif endif define undef warning error line " + "pragma _Pragma ifdef ifndef include"
},
contains: [
{
begin: /\\\n/,
relevance: 0
},
hljs.inherit(STRINGS, {
className: "meta-string"
}),
{
className: "meta-string",
begin: /<.*?>/
},
C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
};
const TITLE_MODE = {
className: "title",
begin: optional2(NAMESPACE_RE) + hljs.IDENT_RE,
relevance: 0
};
const FUNCTION_TITLE = optional2(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
const COMMON_CPP_HINTS = [
"asin",
"atan2",
"atan",
"calloc",
"ceil",
"cosh",
"cos",
"exit",
"exp",
"fabs",
"floor",
"fmod",
"fprintf",
"fputs",
"free",
"frexp",
"auto_ptr",
"deque",
"list",
"queue",
"stack",
"vector",
"map",
"set",
"pair",
"bitset",
"multiset",
"multimap",
"unordered_set",
"fscanf",
"future",
"isalnum",
"isalpha",
"iscntrl",
"isdigit",
"isgraph",
"islower",
"isprint",
"ispunct",
"isspace",
"isupper",
"isxdigit",
"tolower",
"toupper",
"labs",
"ldexp",
"log10",
"log",
"malloc",
"realloc",
"memchr",
"memcmp",
"memcpy",
"memset",
"modf",
"pow",
"printf",
"putchar",
"puts",
"scanf",
"sinh",
"sin",
"snprintf",
"sprintf",
"sqrt",
"sscanf",
"strcat",
"strchr",
"strcmp",
"strcpy",
"strcspn",
"strlen",
"strncat",
"strncmp",
"strncpy",
"strpbrk",
"strrchr",
"strspn",
"strstr",
"tanh",
"tan",
"unordered_map",
"unordered_multiset",
"unordered_multimap",
"priority_queue",
"make_pair",
"array",
"shared_ptr",
"abort",
"terminate",
"abs",
"acos",
"vfprintf",
"vprintf",
"vsprintf",
"endl",
"initializer_list",
"unique_ptr",
"complex",
"imaginary",
"std",
"string",
"wstring",
"cin",
"cout",
"cerr",
"clog",
"stdin",
"stdout",
"stderr",
"stringstream",
"istringstream",
"ostringstream"
];
const CPP_KEYWORDS = {
keyword: "int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof " + "dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace " + "unsigned long volatile static protected bool template mutable if public friend " + "do goto auto void enum else break extern using asm case typeid wchar_t " + "short reinterpret_cast|10 default double register explicit signed typename try this " + "switch continue inline delete alignas alignof constexpr consteval constinit decltype " + "concept co_await co_return co_yield requires " + "noexcept static_assert thread_local restrict final override " + "atomic_bool atomic_char atomic_schar " + "atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong " + "atomic_ullong new throw return " + "and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq",
built_in: "_Bool _Complex _Imaginary",
_relevance_hints: COMMON_CPP_HINTS,
literal: "true false nullptr NULL"
};
const FUNCTION_DISPATCH = {
className: "function.dispatch",
relevance: 0,
keywords: CPP_KEYWORDS,
begin: concat(/\b/, /(?!decltype)/, /(?!if)/, /(?!for)/, /(?!while)/, hljs.IDENT_RE, 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
]
},
{
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)\\s*<",
end: ">",
keywords: CPP_KEYWORDS,
contains: [
"self",
CPP_PRIMITIVE_TYPES
]
},
{
begin: hljs.IDENT_RE + "::",
keywords: CPP_KEYWORDS
},
{
className: "class",
beginKeywords: "enum class struct union",
end: /[{;:<>=]/,
contains: [
{
beginKeywords: "final class struct"
},
hljs.TITLE_MODE
]
}
]),
exports: {
preprocessor: PREPROCESSOR,
strings: STRINGS,
keywords: CPP_KEYWORDS
}
};
}
function arduino(hljs) {
const ARDUINO_KW = {
keyword: "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 ",
_: "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.keyword += " " + ARDUINO_KW.keyword;
kws.literal += " " + ARDUINO_KW.literal;
kws.built_in += " " + ARDUINO_KW.built_in;
kws._ += " " + ARDUINO_KW._;
ARDUINO.name = "Arduino";
ARDUINO.aliases = ["ino"];
ARDUINO.supersetOf = "cpp";
return ARDUINO;
}
module.exports = arduino;
});
// 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 " + "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/highlight.js/lib/languages/xml.js
var require_xml = __commonJS((exports, module) => {
function source(re) {
if (!re)
return null;
if (typeof re === "string")
return re;
return re.source;
}
function lookahead(re) {
return concat("(?=", re, ")");
}
function optional2(re) {
return concat("(", re, ")?");
}
function concat(...args) {
const joined = args.map((x3) => source(x3)).join("");
return joined;
}
function either(...args) {
const joined = "(" + args.map((x3) => source(x3)).join("|") + ")";
return joined;
}
function xml(hljs) {
const TAG_NAME_RE = concat(/[A-Z_]/, optional2(/[A-Z0-9_.-]*:/), /[A-Z0-9_.-]*/);
const XML_IDENT_RE = /[A-Za-z0-9._:-]+/;
const XML_ENTITIES = {
className: "symbol",
begin: /&[a-z]+;|[0-9]+;|[a-f0-9]+;/
};
const XML_META_KEYWORDS = {
begin: /\s/,
contains: [
{
className: "meta-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: "meta-string"
});
const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
className: "meta-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,
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",
begin: /<\?xml/,
end: /\?>/,
relevance: 10
},
{
className: "tag",
begin: /
Claude Code Insights
${data.total_messages.toLocaleString()} messages across ${data.total_sessions} sessions${data.total_sessions_scanned && data.total_sessions_scanned > data.total_sessions ? ` (${data.total_sessions_scanned.toLocaleString()} total)` : ""} | ${data.date_range.start} to ${data.date_range.end}
${atAGlanceHtml}
${data.total_messages.toLocaleString()}Messages
+${data.total_lines_added.toLocaleString()}/-${data.total_lines_removed.toLocaleString()}Lines
${data.total_files_modified}Files
${data.days_active}Days
${data.messages_per_day}Msgs/Day
${projectAreasHtml}
What You Wanted
${generateBarChart(data.goal_categories, "#2563eb")}
Top Tools Used
${generateBarChart(data.tool_counts, "#0891b2")}
Languages
${generateBarChart(data.languages, "#10b981")}
Session Types
${generateBarChart(data.session_types || {}, "#8b5cf6")}
${interactionHtml}
User Response Time Distribution
${generateResponseTimeHistogram(data.user_response_times)}
Median: ${data.median_response_time.toFixed(1)}s • Average: ${data.avg_response_time.toFixed(1)}s
Multi-Clauding (Parallel Sessions)
${data.multi_clauding.overlap_events === 0 ? `
No parallel session usage detected. You typically work with one Claude Code session at a time.
` : `
${data.multi_clauding.overlap_events}
Overlap Events
${data.multi_clauding.sessions_involved}
Sessions Involved
${data.total_messages > 0 ? Math.round(100 * data.multi_clauding.user_messages_during / data.total_messages) : 0}%
Of Messages
You run multiple Claude Code sessions simultaneously. Multi-clauding is detected when sessions
overlap in time, suggesting parallel workflows.
`}
User Messages by Time of Day
${generateTimeOfDayChart(data.message_hours)}
Tool Errors Encountered
${Object.keys(data.tool_error_categories).length > 0 ? generateBarChart(data.tool_error_categories, "#dc2626") : 'No tool errors
'}
${whatWorksHtml}
What Helped Most (Claude's Capabilities)
${generateBarChart(data.success, "#16a34a")}
Outcomes
${generateBarChart(data.outcomes, "#8b5cf6", 6, OUTCOME_ORDER)}
${frictionHtml}
Primary Friction Types
${generateBarChart(data.friction, "#dc2626")}
Inferred Satisfaction (model-estimated)
${generateBarChart(data.satisfaction, "#eab308", 6, SATISFACTION_ORDER)}
${suggestionsHtml}
${horizonHtml}
${funEndingHtml}
${teamFeedbackHtml}