tsup
Version:
Bundle your TypeScript library with no config, powered by esbuild
10,157 lines • 389 kB
JavaScript
"use strict"; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4;
var _chunk6IOGQ2V3js = require('./chunk-6IOGQ2V3.js');
var _chunkJZ25TPTYjs = require('./chunk-JZ25TPTY.js');
var _chunkYQNCOY6Vjs = require('./chunk-YQNCOY6V.js');
// node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/constants.js
var require_constants = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/constants.js"(exports, module) {
"use strict";
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 SEP = "/";
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
};
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,
// regular expressions
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,
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
__proto__: null,
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
// Digits
CHAR_0: 48,
/* 0 */
CHAR_9: 57,
/* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 65,
/* A */
CHAR_LOWERCASE_A: 97,
/* a */
CHAR_UPPERCASE_Z: 90,
/* Z */
CHAR_LOWERCASE_Z: 122,
/* z */
CHAR_LEFT_PARENTHESES: 40,
/* ( */
CHAR_RIGHT_PARENTHESES: 41,
/* ) */
CHAR_ASTERISK: 42,
/* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: 38,
/* & */
CHAR_AT: 64,
/* @ */
CHAR_BACKWARD_SLASH: 92,
/* \ */
CHAR_CARRIAGE_RETURN: 13,
/* \r */
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,
/* \f */
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,
/* \n */
CHAR_NO_BREAK_SPACE: 160,
/* \u00A0 */
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,
/* \t */
CHAR_UNDERSCORE: 95,
/* _ */
CHAR_VERTICAL_LINE: 124,
/* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
/* \uFEFF */
/**
* Create EXTGLOB_CHARS
*/
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: ")" }
};
},
/**
* Create GLOB_CHARS
*/
globChars(win322) {
return win322 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
}
});
// node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/utils.js
var require_utils = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/utils.js"(exports) {
"use strict";
var {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = require_constants();
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 platform = navigator.platform.toLowerCase();
return platform === "win32" || platform === "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 = {}, options = {}) => {
const prepend = options.contains ? "" : "^";
const append = options.contains ? "" : "$";
let output = `${prepend}(?:${input})${append}`;
if (state.negated === true) {
output = `(?:^(?!${output}).*$)`;
}
return output;
};
exports.basename = (path3, { windows } = {}) => {
const segs = path3.split(windows ? /[\\/]/ : "/");
const last = segs[segs.length - 1];
if (last === "") {
return segs[segs.length - 2];
}
return last;
};
}
});
// node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/scan.js
var require_scan = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/scan.js"(exports, module) {
"use strict";
var utils = require_utils();
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_constants();
var isPathSeparator = (code) => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
var depth = (token) => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
}
};
var scan = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.tokens === 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 finished = 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;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = 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 (finished === 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;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) {
negatedExtglob = true;
}
if (scanToEnd === true) {
let parens = 0;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_PARENTHESES) {
parens++;
continue;
}
if (code === CHAR_RIGHT_PARENTHESES && --parens === 0) {
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = 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;
finished = 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) {
let parens = 1;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_PARENTHESES) {
parens++;
continue;
}
if (code === CHAR_RIGHT_PARENTHESES && --parens === 0) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = "";
let glob = "";
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = "";
glob = str;
} else {
base = str;
}
if (base && base !== "" && base !== "/" && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) {
base = base.slice(0, -1);
}
}
if (opts.unescape === true) {
if (glob) glob = utils.removeBackslashes(glob);
if (base && backslashes === true) {
base = utils.removeBackslashes(base);
}
}
const state = {
prefix,
input,
start,
base,
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 !== void 0 ? prevIndex + 1 : start;
const i = slashes[idx];
const value3 = input.slice(n2, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value3;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (i >= start) {
parts.push(value3);
prevIndex = i;
}
}
const n = prevIndex !== void 0 ? prevIndex + 1 : start;
const value2 = input.slice(n);
parts.push(value2);
if (opts.tokens && prevIndex && prevIndex + 1 < input.length) {
tokens[tokens.length - 1].value = value2;
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/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/parse.js
var require_parse = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/parse.js"(exports, module) {
"use strict";
var constants = require_constants();
var utils = require_utils();
var {
MAX_LENGTH,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants;
var expandRange = (args, options) => {
if (typeof options.expandRange === "function") {
return options.expandRange(...args, options);
}
args.sort();
const value2 = `[${args.join("-")}]`;
try {
new RegExp(value2);
} catch (ex) {
return args.map((v) => utils.escapeRegex(v)).join("..");
}
return value2;
};
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 value2 = "";
let escaped = false;
for (const ch of input) {
if (escaped === true) {
value2 += ch;
escaped = false;
continue;
}
if (ch === "\\") {
value2 += ch;
escaped = true;
continue;
}
if (ch === '"') {
quote = quote === 1 ? 0 : 1;
value2 += ch;
continue;
}
if (quote === 0) {
if (ch === "[") {
bracket++;
} else if (ch === "]" && bracket > 0) {
bracket--;
} else if (bracket === 0) {
if (ch === "(") {
paren++;
} else if (ch === ")" && paren > 0) {
paren--;
} else if (ch === "|" && paren === 0) {
parts.push(value2);
value2 = "";
continue;
}
}
}
value2 += ch;
}
parts.push(value2);
return parts;
};
var isPlainBranch = (branch) => {
let escaped = false;
for (const ch of branch) {
if (escaped === true) {
escaped = false;
continue;
}
if (ch === "\\") {
escaped = true;
continue;
}
if (/[?*+@!()[\]{}]/.test(ch)) {
return false;
}
}
return true;
};
var normalizeSimpleBranch = (branch) => {
let value2 = branch.trim();
let changed = true;
while (changed === true) {
changed = false;
if (/^@\([^\\()[\]{}|]+\)$/.test(value2)) {
value2 = value2.slice(2, -1);
changed = true;
}
}
if (!isPlainBranch(value2)) {
return;
}
return value2.replace(/\\(.)/g, "$1");
};
var hasRepeatedCharPrefixOverlap = (branches) => {
const values = branches.map(normalizeSimpleBranch).filter(Boolean);
for (let i = 0; i < values.length; i++) {
for (let j = i + 1; j < values.length; j++) {
const a = values[i];
const b = values[j];
const char = a[0];
if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
continue;
}
if (a === b || a.startsWith(b) || b.startsWith(a)) {
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 i = 1; i < pattern.length; i++) {
const ch = pattern[i];
if (escaped === true) {
escaped = false;
continue;
}
if (ch === "\\") {
escaped = true;
continue;
}
if (ch === '"') {
quote = quote === 1 ? 0 : 1;
continue;
}
if (quote === 1) {
continue;
}
if (ch === "[") {
bracket++;
continue;
}
if (ch === "]" && bracket > 0) {
bracket--;
continue;
}
if (bracket > 0) {
continue;
}
if (ch === "(") {
paren++;
continue;
}
if (ch === ")") {
paren--;
if (paren === 0) {
if (requireEnd === true && i !== pattern.length - 1) {
return;
}
return {
type: pattern[0],
body: pattern.slice(2, i),
end: i
};
}
}
}
};
var buildCharClassStar = (chars) => {
const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`;
return `${source}*`;
};
var getStarExtglobSequenceChars = (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;
}
return chars;
};
var repeatedExtglobRecursion = (pattern) => {
let depth = 0;
let value2 = pattern.trim();
let match = parseRepeatedExtglob(value2);
while (match) {
depth++;
value2 = match.body.trim();
match = parseRepeatedExtglob(value2);
}
return depth;
};
var analyzeRepeatedExtglob = (body, options) => {
if (options.maxExtglobRecursion === false) {
return { risky: false };
}
const max = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants.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 };
}
}
const safeChars = [];
let sawStarSequence = false;
let combinable = true;
for (const branch of branches) {
const chars = getStarExtglobSequenceChars(branch);
if (chars) {
sawStarSequence = true;
safeChars.push(...chars);
continue;
}
const literal = normalizeSimpleBranch(branch);
if (literal && literal.length === 1) {
safeChars.push(literal);
continue;
}
combinable = false;
if (repeatedExtglobRecursion(branch) > max) {
return { risky: true };
}
}
if (sawStarSequence) {
return combinable ? { risky: true, safeOutput: buildCharClassStar([...new Set(safeChars)]) } : { risky: true };
}
return { risky: false };
};
var parse = (input, options) => {
if (typeof input !== "string") {
throw new TypeError("Expected a string");
}
input = REPLACEMENTS[input] || input;
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
let len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
const bos = { type: "bos", value: "", output: opts.prepend || "" };
const tokens = [bos];
const capture = opts.capture ? "" : "?:";
const PLATFORM_CHARS = constants.globChars(opts.windows);
const EXTGLOB_CHARS = constants.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 value2;
const eos = () => state.index === len - 1;
const peek = state.peek = (n = 1) => input[state.index + n];
const advance = state.advance = () => input[++state.index] || "";
const remaining = () => input.slice(state.index + 1);
const consume = (value3 = "", num = 0) => {
state.consumed += value3;
state.index += num;
};
const append = (token) => {
state.output += token.output != null ? token.output : token.value;
consume(token.value);
};
const negate = () => {
let count = 1;
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
advance();
state.start++;
count++;
}
if (count % 2 === 0) {
return false;
}
state.negated = true;
state.start++;
return true;
};
const increment = (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) append(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, value3) => {
const token = { ...EXTGLOB_CHARS[value3], 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;
increment("parens");
push({ type, value: value3, output: state.output ? "" : ONE_CHAR });
push({ type: "paren", extglob: true, value: advance(), output });
extglobs.push(token);
};
const extglobClose = (token) => {
const literal = 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) : void 0;
const open = tokens[token.tokensIndex];
open.type = "text";
open.value = literal;
open.output = safeOutput || utils.escapeRegex(literal);
for (let i = token.tokensIndex + 1; i < tokens.length; i++) {
tokens[i].value = "";
tokens[i].output = "";
delete tokens[i].suffix;
}
state.output = token.output + open.output;
state.backtrack = true;
push({ type: "paren", extglob: true, value: value2, 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 = parse(rest, { ...options, fastpaths: false }).output;
output = token.close = `)${expression})${extglobStar})`;
}
if (token.prev.type === "bos") {
state.negatedExtglob = true;
}
}
push({ type: "paren", extglob: true, value: value2, output });
decrement("parens");
};
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
if (first === "\\") {
backslashes = true;
return m;
}
if (first === "?") {
if (esc) {
return esc + 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 (esc) {
return esc + first + (rest ? star : "");
}
return star;
}
return esc ? 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, options);
return state;
}
while (!eos()) {
value2 = advance();
if (value2 === "\0") {
continue;
}
if (value2 === "\\") {
const next = peek();
if (next === "/" && opts.bash !== true) {
continue;
}
if (next === "." || next === ";") {
continue;
}
if (!next) {
value2 += "\\";
push({ type: "text", value: value2 });
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) {
value2 += "\\";
}
}
if (opts.unescape === true) {
value2 = advance();
} else {
value2 += advance();
}
if (state.brackets === 0) {
push({ type: "text", value: value2 });
continue;
}
}
if (state.brackets > 0 && (value2 !== "]" || prev.value === "[" || prev.value === "[^")) {
if (opts.posix !== false && value2 === ":") {
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 posix2 = POSIX_REGEX_SOURCE[rest2];
if (posix2) {
prev.value = pre + posix2;
state.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) {
bos.output = ONE_CHAR;
}
continue;
}
}
}
}
if (value2 === "[" && peek() !== ":" || value2 === "-" && peek() === "]") {
value2 = `\\${value2}`;
}
if (value2 === "]" && (prev.value === "[" || prev.value === "[^")) {
value2 = `\\${value2}`;
}
if (opts.posix === true && value2 === "!" && prev.value === "[") {
value2 = "^";
}
prev.value += value2;
append({ value: value2 });
continue;
}
if (state.quotes === 1 && value2 !== '"') {
value2 = utils.escapeRegex(value2);
prev.value += value2;
append({ value: value2 });
continue;
}
if (value2 === '"') {
state.quotes = state.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) {
push({ type: "text", value: value2 });
}
continue;
}
if (value2 === "(") {
increment("parens");
push({ type: "paren", value: value2 });
continue;
}
if (value2 === ")") {
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: value2, output: state.parens ? ")" : "\\)" });
decrement("parens");
continue;
}
if (value2 === "[") {
if (opts.nobracket === true || !remaining().includes("]")) {
if (opts.nobracket !== true && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("closing", "]"));
}
value2 = `\\${value2}`;
} else {
increment("brackets");
}
push({ type: "bracket", value: value2 });
continue;
}
if (value2 === "]") {
if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
push({ type: "text", value: value2, output: `\\${value2}` });
continue;
}
if (state.brackets === 0) {
if (opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("opening", "["));
}
push({ type: "text", value: value2, output: `\\${value2}` });
continue;
}
decrement("brackets");
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
value2 = `/${value2}`;
}
prev.value += value2;
append({ value: value2 });
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 (value2 === "{" && opts.nobrace !== true) {
increment("braces");
const open = {
type: "brace",
value: value2,
output: "(",
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces.push(open);
push(open);
continue;
}
if (value2 === "}") {
const brace = braces[braces.length - 1];
if (opts.nobrace === true || !brace) {
push({ type: "text", value: value2, output: value2 });
continue;
}
let output = ")";
if (brace.dots === true) {
const arr = tokens.slice();
const range = [];
for (let i = arr.length - 1; i >= 0; i--) {
tokens.pop();
if (arr[i].type === "brace") {
break;
}
if (arr[i].type !== "dots") {
range.unshift(arr[i].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 = "\\{";
value2 = output = "\\}";
state.output = out;
for (const t of toks) {
state.output += t.output || t.value;
}
}
push({ type: "brace", value: value2, output });
decrement("braces");
braces.pop();
continue;
}
if (value2 === "|") {
if (extglobs.length > 0) {
extglobs[extglobs.length - 1].conditions++;
}
push({ type: "text", value: value2 });
continue;
}
if (value2 === ",") {
let output = value2;
const brace = braces[braces.length - 1];
if (brace && stack[stack.length - 1] === "braces") {
brace.comma = true;
output = "|";
}
push({ type: "comma", value: value2, output });
continue;
}
if (value2 === "/") {
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: value2, output: SLASH_LITERAL });
continue;
}
if (value2 === ".") {
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 += value2;
prev.value += value2;
brace.dots = true;
continue;
}
if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
push({ type: "text", value: value2, output: DOT_LITERAL });
continue;
}
push({ type: "dot", value: value2, output: DOT_LITERAL });
continue;
}
if (value2 === "?") {
const isGroup = prev && prev.value === "(";
if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("qmark", value2);
continue;
}
if (prev && prev.type === "paren") {
const next = peek();
let output = value2;
if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
output = `\\${value2}`;
}
push({ type: "text", value: value2, output });
continue;
}
if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
push({ type: "qmark", value: value2, output: QMARK_NO_DOT });
continue;
}
push({ type: "qmark", value: value2, output: QMARK });
continue;
}
if (value2 === "!") {
if (opts.noextglob !== true && peek() === "(") {
if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
extglobOpen("negate", value2);
continue;
}
}
if (opts.nonegate !== true && state.index === 0) {
negate();
continue;
}
}
if (value2 === "+") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("plus", value2);
continue;
}
if (prev && prev.value === "(" || opts.regex === false) {
push({ type: "plus", value: value2, output: PLUS_LITERAL });
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
push({ type: "plus", value: value2 });
continue;
}
push({ type: "plus", value: PLUS_LITERAL });
continue;
}
if (value2 === "@") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
push({ type: "at", extglob: true, value: value2, output: "" });
continue;
}
push({ type: "text", value: value2 });
continue;
}
if (value2 !== "*") {
if (value2 === "$" || value2 === "^") {
value2 = `\\${value2}`;
}
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match) {
value2 += match[0];
state.index += match[0].length;
}
push({ type: "text", value: value2 });
continue;
}
if (prev && (prev.type === "globstar" || prev.star === true)) {
prev.type = "star";
prev.star = true;
prev.value += value2;
prev.output = star;
state.backtrack = true;
state.globstar = true;
consume(value2);
continue;
}
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen("star", value2);
continue;
}
if (prev.type === "star") {
if (opts.noglobstar === true) {
consume(value2);
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: value2, 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: value2, output: "" });
continue;
}
while (rest.slice(0, 3) === "/**") {
const after = input[state.index + 4];
if (after && after !== "/") {
break;
}
rest = rest.slice(3);
consume("/**", 3);
}
const isEnd = eos() || state.parens > 0 && rest === ")".repeat(state.parens) && !extglobs.some((extglob) => extglob.type === "negate");
if (prior.type === "bos" && eos()) {
prev.type = "globstar";
prev.value += value2;
prev.output = globstar(opts);
state.output = prev.output;
state.globstar = true;
consume(value2);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && isEnd) {
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 += value2;
state.globstar = true;
state.output += prior.output + prev.output;
consume(value2);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
const end = rest[1] !== void 0 ? "|$" : "";
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 += value2;
state.output += prior.output + prev.output;
state.globstar = true;
consume(value2 + advance());
push({ type: "slash", value: "/", output: "" });
continue;
}
if (prior.type === "bos" && rest[0] === "/") {
prev.type = "globstar";
prev.value += value2;
prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
state.output = prev.output;
state.globstar = true;
consume(value2 + 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 += value2;
state.output += prev.output;
state.globstar = true;
consume(value2);
continue;
}
const token = { type: "star", value: value2, 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 = value2;
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;
};
parse.fastpaths = (input, options) => {
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
const len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
input = REPLACEMENTS[input] || input;
const {
DOT_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOTS_SLASH,
STAR,
START_ANCHOR
} = constants.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 = parse;
}
});
// node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/picomatch.js
var require_picomatch = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/picomatch.js"(exports, module) {
"use strict";
var scan = require_scan();
var parse = require_parse();
var utils = require_utils();
var constants = require_constants();
var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
var picomatch = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map((input) => picomatch(input, options, returnState));
const arrayMatcher = (str) => {
for (const isMatch of fns) {
const state2 = isMatch(str);
if (state2) return state2;
}
return false;
};
return arrayMatcher;
}
const isState = isObject(glob) && glob.tokens && glob.input;
if (glob === "" || typeof glob !== "string" && !isState) {
throw new TypeError("Expected pattern to be a non-empty string");
}
const opts = options || {};
const posix2 = opts.windows;
const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
const state = regex.state;
delete regex.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix: posix2 });
const result = { glob, state, regex, posix: posix2, 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, regex, options, { glob, posix: posix2 } = {}) => {
if (typeof input !== "string") {
throw new TypeError("Expected input to be a string");
}
if (input === "") {
return { isMatch: false, output: "" };
}
const opts = options || {};
const format = opts.format || (posix2 ? utils.toPosixSlashes : null);
let match = input === glob;
let output = match && format ? format(input) : input;
if (match === false) {
output = format ? format(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match = picomatch.matchBase(input, regex, options, posix2);
} else {
match = regex.exec(output);
}
}
return { isMatch: Boolean(match), match, output };
};
picomatch.matchBase = (input, glob, options, posix2 = options && options.windows) => {
const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex.test(utils.basename(input, { windows: posix2 }));
};
picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
picomatch.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map((p) => picomatch.parse(p, options));
return parse(pattern, { ...options, fastpaths: false });
};
picomatch.scan = (input, options) => scan(input, options);
picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state.output;
}
const opts = options || {};
const prepend = opts.contains ? "" : "^";
const append = opts.contains ? "" : "$";
let source = `${prepend}(?:${state.output})${append}`;
if (state && state.negated === true) {
source = `^(?!${source}).*$`;
}
const regex = picomatch.toRegex(source, options);
if (returnState === true) {
regex.state = state;
}
return regex;
};
picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== "string") {
throw new TypeError("Expected a non-empty string");
}
let parsed = { negated: false, fastpaths: true };
if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
parsed.output = parse.fastpaths(input, options);
}
if (!parsed.output) {
parsed = parse(input, options);
}
return picomatch.compileRe(parsed, options, returnOutput, returnState);
};
picomatch.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err) {
if (options && options.debug === true) throw err;
return /$^/;
}
};
picomatch.constants = constants;
module.exports = picomatch;
}
});
// node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/index.js
var require_picomatch2 = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/index.js"(exports, module) {
"use strict";
var pico = require_picomatch();
var utils = require_utils();
function picomatch(glob, options, returnState = false) {
if (options && (options.windows === null || options.windows === void 0)) {
options = { ...options, windows: utils.isWindows() };
}
return pico(glob, options, returnState);
}
Object.assign(picomatch, pico);
module.exports = picomatch;
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/homedir.js
var require_homedir = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/homedir.js"(exports, module) {
"use strict";
var os = _chunkYQNCOY6Vjs.__require.call(void 0, "os");
module.exports = os.homedir || function homedir() {
var home = process.env.HOME;
var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
if (process.platform === "win32") {
return process.env.USERPROFILE || process.env.HOMEDRIVE && process.env.HOMEPATH && process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;
}
if (process.platform === "darwin") {
return home || (user ? "/Users/" + user : null);
}
if (process.platform === "linux") {
return home || (process.getuid() === 0 ? "/root" : user ? "/home/" + user : null);
}
return home || null;
};
}
});
// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js
var require_es_errors = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js"(exports, module) {
"use strict";
module.exports = Error;
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/caller.js
var require_caller = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/caller.js"(exports, module) {
"use strict";
var $Error = require_es_errors();
module.exports = function() {
var origPrepareStackTrace = $Error.prepareStackTrace;
$Error.prepareStackTrace = function(_, stack2) {
return stack2;
};
var stack = new $Error().stack;
$Error.prepareStackTrace = origPrepareStackTrace;
return stack[2].getFileName();
};
}
});
// node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js
var require_path_parse = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js"(exports, module) {
"use strict";
var isWindows = process.platform === "win32";
var splitWindowsRe = /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
var win322 = {};
function win32SplitPath(filename) {
return splitWindowsRe.exec(filename).slice(1);
}
win322.parse = function(pathString) {
if (typeof pathString !== "string") {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = win32SplitPath(pathString);
if (!allParts || allParts.length !== 5) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[1],
dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3]
};
};
var splitPathRe = /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
var posix2 = {};
function posixSplitPath(filename) {
return splitPathRe.exec(filename).slice(1);
}
posix2.parse = function(pathString) {
if (typeof pathString !== "string") {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = posixSplitPath(pathString);
if (!allParts || allParts.length !== 5) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[1],
dir: allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3]
};
};
if (isWindows)
module.exports = win322.parse;
else
module.exports = posix2.parse;
module.exports.posix = posix2.parse;
module.exports.win32 = win322.parse;
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/node-modules-paths.js
var require_node_modules_paths = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/node-modules-paths.js"(exports, module) {
"use strict";
var path3 = _chunkYQNCOY6Vjs.__require.call(void 0, "path");
var parse = path3.parse || require_path_parse();
var driveLetterRegex = /^([A-Za-z]:)/;
var uncPathRegex = /^\\\\/;
function getNodeModulesDirs(absoluteStart, modules) {
var prefix = "/";
if (driveLetterRegex.test(absoluteStart)) {
prefix = "";
} else if (uncPathRegex.test(absoluteStart)) {
prefix = "\\\\";
}
var paths = [absoluteStart];
var parsed = parse(absoluteStart);
while (parsed.dir !== paths[paths.length - 1]) {
paths.push(parsed.dir);
parsed = parse(parsed.dir);
}
return paths.reduce(function(dirs, aPath) {
return dirs.concat(modules.map(function(moduleDir) {
return path3.resolve(prefix, aPath, moduleDir);
}));
}, []);
}
module.exports = function nodeModulesPaths(start, opts, request) {
var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ["node_modules"];
if (opts && typeof opts.paths === "function") {
return opts.paths(
request,
start,
function() {
return getNodeModulesDirs(start, modules);
},
opts
);
}
var dirs = getNodeModulesDirs(start, modules);
return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
};
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/normalize-options.js
var require_normalize_options = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/normalize-options.js"(exports, module) {
"use strict";
module.exports = function(x, opts) {
return opts || {};
};
}
});
// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js
var require_implementation = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js"(exports, module) {
"use strict";
var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = "[object Function]";
var concatty = function concatty2(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy2(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function(arr, joiner) {
var str = "";
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== "function" || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function() {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = "$" + i;
}
bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
if (target.prototype) {
var Empty = function Empty2() {
};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
}
});
// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js
var require_function_bind = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js"(exports, module) {
"use strict";
var implementation = require_implementation();
module.exports = Function.prototype.bind || implementation;
}
});
// node_modules/.pnpm/hasown@2.0.4/node_modules/hasown/index.js
var require_hasown = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/hasown@2.0.4/node_modules/hasown/index.js"(exports, module) {
"use strict";
var call = Function.prototype.call;
var $hasOwn = Object.prototype.hasOwnProperty;
var bind = require_function_bind();
module.exports = bind.call(call, $hasOwn);
}
});
// node_modules/.pnpm/is-core-module@2.17.0/node_modules/is-core-module/core.json
var require_core = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/is-core-module@2.17.0/node_modules/is-core-module/core.json"(exports, module) {
module.exports = {
assert: true,
"node:assert": [">= 14.18 && < 15", ">= 16"],
"assert/strict": ">= 15",
"node:assert/strict": ">= 16",
async_hooks: ">= 8",
"node:async_hooks": [">= 14.18 && < 15", ">= 16"],
buffer_ieee754: ">= 0.5 && < 0.9.7",
buffer: true,
"node:buffer": [">= 14.18 && < 15", ">= 16"],
child_process: true,
"node:child_process": [">= 14.18 && < 15", ">= 16"],
cluster: ">= 0.5",
"node:cluster": [">= 14.18 && < 15", ">= 16"],
console: true,
"node:console": [">= 14.18 && < 15", ">= 16"],
constants: true,
"node:constants": [">= 14.18 && < 15", ">= 16"],
crypto: true,
"node:crypto": [">= 14.18 && < 15", ">= 16"],
_debug_agent: ">= 1 && < 8",
_debugger: "< 8",
dgram: true,
"node:dgram": [">= 14.18 && < 15", ">= 16"],
diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
"node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
dns: true,
"node:dns": [">= 14.18 && < 15", ">= 16"],
"dns/promises": ">= 15",
"node:dns/promises": ">= 16",
domain: ">= 0.7.12",
"node:domain": [">= 14.18 && < 15", ">= 16"],
events: true,
"node:events": [">= 14.18 && < 15", ">= 16"],
"node:ffi": ">= 26.9",
freelist: "< 6",
fs: true,
"node:fs": [">= 14.18 && < 15", ">= 16"],
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"node:fs/promises": [">= 14.18 && < 15", ">= 16"],
_http_agent: ">= 0.11.1",
"node:_http_agent": [">= 14.18 && < 15", ">= 16"],
_http_client: ">= 0.11.1",
"node:_http_client": [">= 14.18 && < 15", ">= 16"],
_http_common: ">= 0.11.1",
"node:_http_common": [">= 14.18 && < 15", ">= 16"],
_http_incoming: ">= 0.11.1",
"node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
_http_outgoing: ">= 0.11.1",
"node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
_http_server: ">= 0.11.1",
"node:_http_server": [">= 14.18 && < 15", ">= 16"],
http: true,
"node:http": [">= 14.18 && < 15", ">= 16"],
http2: ">= 8.8",
"node:http2": [">= 14.18 && < 15", ">= 16"],
https: true,
"node:https": [">= 14.18 && < 15", ">= 16"],
inspector: ">= 8",
"node:inspector": [">= 14.18 && < 15", ">= 16"],
"inspector/promises": [">= 19"],
"node:inspector/promises": [">= 19"],
_linklist: "< 8",
module: true,
"node:module": [">= 14.18 && < 15", ">= 16"],
net: true,
"node:net": [">= 14.18 && < 15", ">= 16"],
"node-inspect/lib/_inspect": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
os: true,
"node:os": [">= 14.18 && < 15", ">= 16"],
path: true,
"node:path": [">= 14.18 && < 15", ">= 16"],
"path/posix": ">= 15.3",
"node:path/posix": ">= 16",
"path/win32": ">= 15.3",
"node:path/win32": ">= 16",
perf_hooks: ">= 8.5",
"node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
process: ">= 1",
"node:process": [">= 14.18 && < 15", ">= 16"],
punycode: ">= 0.5",
"node:punycode": [">= 14.18 && < 15", ">= 16"],
querystring: true,
"node:querystring": [">= 14.18 && < 15", ">= 16"],
readline: true,
"node:readline": [">= 14.18 && < 15", ">= 16"],
"readline/promises": ">= 17",
"node:readline/promises": ">= 17",
repl: true,
"node:repl": [">= 14.18 && < 15", ">= 16"],
"node:sea": [">= 20.12 && < 21", ">= 21.7"],
smalloc: ">= 0.11.5 && < 3",
"node:sqlite": [">= 22.13 && < 23", ">= 23.4"],
_stream_duplex: ">= 0.9.4 && < 26",
"node:_stream_duplex": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_transform: ">= 0.9.4 && < 26",
"node:_stream_transform": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_wrap: ">= 1.4.1 && < 26",
"node:_stream_wrap": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_passthrough: ">= 0.9.4 && < 26",
"node:_stream_passthrough": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_readable: ">= 0.9.4 && < 26",
"node:_stream_readable": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_writable: ">= 0.9.4 && < 26",
"node:_stream_writable": [">= 14.18 && < 15", ">= 16 && < 26"],
stream: true,
"node:stream": [">= 14.18 && < 15", ">= 16"],
"stream/consumers": ">= 16.7",
"node:stream/consumers": ">= 16.7",
"stream/promises": ">= 15",
"node:stream/promises": ">= 16",
"stream/web": ">= 16.5",
"node:stream/web": ">= 16.5",
string_decoder: true,
"node:string_decoder": [">= 14.18 && < 15", ">= 16"],
sys: [">= 0.4 && < 0.7", ">= 0.8"],
"node:sys": [">= 14.18 && < 15", ">= 16"],
"test/reporters": ">= 19.9 && < 20.2",
"node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
"test/mock_loader": ">= 22.3 && < 22.7",
"node:test/mock_loader": ">= 22.3 && < 22.7",
"node:test": [">= 16.17 && < 17", ">= 18"],
timers: true,
"node:timers": [">= 14.18 && < 15", ">= 16"],
"timers/promises": ">= 15",
"node:timers/promises": ">= 16",
_tls_common: ">= 0.11.13",
"node:_tls_common": [">= 14.18 && < 15", ">= 16"],
_tls_legacy: ">= 0.11.3 && < 10",
_tls_wrap: ">= 0.11.3",
"node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
tls: true,
"node:tls": [">= 14.18 && < 15", ">= 16"],
trace_events: ">= 10",
"node:trace_events": [">= 14.18 && < 15", ">= 16"],
tty: true,
"node:tty": [">= 14.18 && < 15", ">= 16"],
url: true,
"node:url": [">= 14.18 && < 15", ">= 16"],
util: true,
"node:util": [">= 14.18 && < 15", ">= 16"],
"util/types": ">= 15.3",
"node:util/types": ">= 16",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
v8: ">= 1",
"node:v8": [">= 14.18 && < 15", ">= 16"],
vm: true,
"node:vm": [">= 14.18 && < 15", ">= 16"],
wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
"node:wasi": [">= 18.17 && < 19", ">= 20"],
worker_threads: ">= 11.7",
"node:worker_threads": [">= 14.18 && < 15", ">= 16"],
zlib: ">= 0.5",
"node:zlib": [">= 14.18 && < 15", ">= 16"]
};
}
});
// node_modules/.pnpm/is-core-module@2.17.0/node_modules/is-core-module/index.js
var require_is_core_module = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/is-core-module@2.17.0/node_modules/is-core-module/index.js"(exports, module) {
"use strict";
var hasOwn = require_hasown();
function specifierIncluded(current, specifier) {
var nodeParts = current.split(".");
var parts = specifier.split(" ");
var op = parts.length > 1 ? parts[0] : "=";
var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split(".");
for (var i = 0; i < 3; ++i) {
var cur = parseInt(nodeParts[i] || "0", 10);
var ver = parseInt(versionParts[i] || "0", 10);
if (cur === ver) {
continue;
}
if (op === "<") {
return cur < ver;
}
if (op === ">=") {
return cur >= ver;
}
return false;
}
return op === ">=";
}
function matchesRange(current, range) {
var specifiers = range.split(/ ?&& ?/);
if (specifiers.length === 0) {
return false;
}
for (var i = 0; i < specifiers.length; ++i) {
if (!specifierIncluded(current, specifiers[i])) {
return false;
}
}
return true;
}
function versionIncluded(nodeVersion, specifierValue) {
if (typeof specifierValue === "boolean") {
return specifierValue;
}
var current = typeof nodeVersion === "undefined" ? process.versions && process.versions.node : nodeVersion;
if (typeof current !== "string") {
throw new TypeError(typeof nodeVersion === "undefined" ? "Unable to determine current node version" : "If provided, a valid node version is required");
}
if (specifierValue && typeof specifierValue === "object") {
for (var i = 0; i < specifierValue.length; ++i) {
if (matchesRange(current, specifierValue[i])) {
return true;
}
}
return false;
}
return matchesRange(current, specifierValue);
}
var data = require_core();
module.exports = function isCore(x, nodeVersion) {
return hasOwn(data, x) && versionIncluded(nodeVersion, data[
/** @type {Module} */
x
]);
};
}
});
// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js
var require_type = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js"(exports, module) {
"use strict";
module.exports = TypeError;
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/async.js
var require_async = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/async.js"(exports, module) {
"use strict";
var fs2 = _chunkYQNCOY6Vjs.__require.call(void 0, "fs");
var getHomedir = require_homedir();
var path3 = _chunkYQNCOY6Vjs.__require.call(void 0, "path");
var caller = require_caller();
var nodeModulesPaths = require_node_modules_paths();
var normalizeOptions = require_normalize_options();
var isCore = require_is_core_module();
var $Error = require_es_errors();
var $TypeError = require_type();
var realpathFS = process.platform !== "win32" && fs2.realpath && typeof fs2.realpath.native === "function" ? fs2.realpath.native : fs2.realpath;
var relativePathRegex = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/;
var windowsDriveRegex = /^\w:[/\\]*$/;
var nodeModulesRegex = /[/\\]node_modules[/\\]*$/;
var homedir = getHomedir();
function defaultPaths() {
if (!homedir) return [];
return [
path3.join(homedir, ".node_modules"),
path3.join(homedir, ".node_libraries")
];
}
var defaultIsFile = function isFile(file, cb) {
fs2.stat(file, function(err, stat) {
if (!err) {
return cb(null, stat.isFile() || stat.isFIFO());
}
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
return cb(err);
});
};
var defaultIsDir = function isDirectory(dir, cb) {
fs2.stat(dir, function(err, stat) {
if (!err) {
return cb(null, stat.isDirectory());
}
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
return cb(err);
});
};
var defaultRealpath = function realpath(x, cb) {
realpathFS(x, function(realpathErr, realPath) {
if (realpathErr && realpathErr.code !== "ENOENT") cb(realpathErr);
else cb(null, realpathErr ? x : realPath);
});
};
function maybeRealpath(realpath, x, opts, cb) {
if (opts && opts.preserveSymlinks === false) {
realpath(x, cb);
} else {
cb(null, x);
}
}
function defaultReadPackage(readFile, pkgfile, cb) {
readFile(pkgfile, function(readFileErr, body) {
if (readFileErr) cb(readFileErr);
else {
try {
var pkg = JSON.parse(body);
cb(null, pkg);
} catch (jsonErr) {
cb(null);
}
}
});
}
function getPackageCandidates(x, start, opts) {
var dirs = nodeModulesPaths(start, opts, x);
for (var i = 0; i < dirs.length; i++) {
dirs[i] = path3.join(dirs[i], x);
}
return dirs;
}
module.exports = function resolve2(x, options, callback) {
var cb = callback;
var opts = options;
if (typeof options === "function") {
cb = opts;
opts = {};
}
if (typeof x !== "string") {
var err = new $TypeError("Path must be a string.");
return process.nextTick(function() {
cb(err);
});
}
opts = normalizeOptions(x, opts);
var isFile = opts.isFile || defaultIsFile;
var isDirectory = opts.isDirectory || defaultIsDir;
var readFile = opts.readFile || fs2.readFile;
var realpath = opts.realpath || defaultRealpath;
var readPackage = opts.readPackage || defaultReadPackage;
if (opts.readFile && opts.readPackage) {
var conflictErr = new $TypeError("`readFile` and `readPackage` are mutually exclusive.");
return process.nextTick(function() {
cb(conflictErr);
});
}
var packageIterator = opts.packageIterator;
var extensions = opts.extensions || [".js"];
var includeCoreModules = opts.includeCoreModules !== false;
var basedir = opts.basedir || path3.dirname(caller());
var parent = opts.filename || basedir;
opts.paths = opts.paths || defaultPaths();
var absoluteStart = path3.resolve(basedir);
maybeRealpath(
realpath,
absoluteStart,
opts,
function(err2, realStart) {
if (err2) cb(err2);
else init(realStart);
}
);
var res;
function init(basedir2) {
if (relativePathRegex.test(x)) {
res = path3.resolve(basedir2, x);
if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
if (x.slice(-1) === "/" && res === basedir2) {
loadAsDirectory(res, opts.package, onfile);
} else loadAsFile(res, opts.package, onfile);
} else if (includeCoreModules && isCore(x)) {
return cb(null, x);
} else loadNodeModules(x, basedir2, function(err2, n, pkg) {
if (err2) cb(err2);
else if (n) {
return maybeRealpath(realpath, n, opts, function(err3, realN) {
if (err3) {
cb(err3);
} else {
cb(null, realN, pkg);
}
});
} else {
var moduleError = new $Error("Cannot find module '" + x + "' from '" + parent + "'");
moduleError.code = "MODULE_NOT_FOUND";
cb(moduleError);
}
});
}
function onfile(err2, m, pkg) {
if (err2) cb(err2);
else if (m) cb(null, m, pkg);
else loadAsDirectory(res, function(err3, d, pkg2) {
if (err3) cb(err3);
else if (d) {
maybeRealpath(realpath, d, opts, function(err4, realD) {
if (err4) {
cb(err4);
} else {
cb(null, realD, pkg2);
}
});
} else {
var moduleError = new $Error("Cannot find module '" + x + "' from '" + parent + "'");
moduleError.code = "MODULE_NOT_FOUND";
cb(moduleError);
}
});
}
function loadAsFile(x2, thePackage, callback2) {
var loadAsFilePackage = thePackage;
var cb2 = callback2;
if (typeof loadAsFilePackage === "function") {
cb2 = loadAsFilePackage;
loadAsFilePackage = void 0;
}
var exts = [""].concat(extensions);
load(exts, x2, loadAsFilePackage);
function load(exts2, x3, loadPackage) {
if (exts2.length === 0) return cb2(null, void 0, loadPackage);
var file = x3 + exts2[0];
var pkg = loadPackage;
if (pkg) onpkg(null, pkg);
else loadpkg(path3.dirname(file), onpkg);
function onpkg(err2, pkg_, dir) {
pkg = pkg_;
if (err2) return cb2(err2);
if (dir && pkg && opts.pathFilter) {
var rfile = path3.relative(dir, file);
var rel = rfile.slice(0, rfile.length - exts2[0].length);
var r = opts.pathFilter(pkg, x3, rel);
if (r) return load(
[""].concat(extensions),
path3.resolve(dir, r),
pkg
);
}
isFile(file, onex);
}
function onex(err2, ex) {
if (err2) return cb2(err2);
if (ex) return cb2(null, file, pkg);
load(exts2.slice(1), x3, pkg);
}
}
}
function loadpkg(dir, cb2) {
if (dir === "" || dir === "/") return cb2(null);
if (process.platform === "win32" && windowsDriveRegex.test(dir)) {
return cb2(null);
}
if (nodeModulesRegex.test(dir)) return cb2(null);
maybeRealpath(realpath, dir, opts, function(unwrapErr, pkgdir) {
if (unwrapErr) return loadpkg(path3.dirname(dir), cb2);
var pkgfile = path3.join(pkgdir, "package.json");
isFile(pkgfile, function(err2, ex) {
if (!ex) return loadpkg(path3.dirname(dir), cb2);
readPackage(readFile, pkgfile, function(err3, pkgParam) {
if (err3) {
return cb2(err3);
}
var pkg = pkgParam;
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(pkg, pkgfile);
}
cb2(null, pkg, dir);
});
});
});
}
function loadAsDirectory(x2, loadAsDirectoryPackage, callback2) {
var cb2 = callback2;
var fpkg = loadAsDirectoryPackage;
if (typeof fpkg === "function") {
cb2 = fpkg;
fpkg = opts.package;
}
maybeRealpath(realpath, x2, opts, function(unwrapErr, pkgdir) {
if (unwrapErr) return cb2(unwrapErr);
var pkgfile = path3.join(pkgdir, "package.json");
isFile(pkgfile, function(err2, ex) {
if (err2) return cb2(err2);
if (!ex) return loadAsFile(path3.join(x2, "index"), fpkg, cb2);
readPackage(readFile, pkgfile, function(err3, pkgParam) {
if (err3) return cb2(err3);
var pkg = pkgParam;
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(pkg, pkgfile);
}
if (pkg && pkg.main) {
if (typeof pkg.main !== "string") {
var mainError = new $TypeError("package \u201C" + pkg.name + "\u201D `main` must be a string");
mainError.code = "INVALID_PACKAGE_MAIN";
return cb2(mainError);
}
if (pkg.main === "." || pkg.main === "./") {
pkg.main = "index";
}
loadAsFile(path3.resolve(x2, pkg.main), pkg, function(err4, m, pkg2) {
if (err4) return cb2(err4);
if (m) return cb2(null, m, pkg2);
if (!pkg2) return loadAsFile(path3.join(x2, "index"), pkg2, cb2);
var dir = path3.resolve(x2, pkg2.main);
loadAsDirectory(dir, pkg2, function(err5, n, pkg3) {
if (err5) return cb2(err5);
if (n) return cb2(null, n, pkg3);
loadAsFile(path3.join(x2, "index"), pkg3, cb2);
});
});
return;
}
loadAsFile(path3.join(x2, "/index"), pkg, cb2);
});
});
});
}
function processDirs(cb2, dirs) {
if (dirs.length === 0) return cb2(null, void 0);
var dir = dirs[0];
isDirectory(path3.dirname(dir), isdir);
function isdir(err2, isdir2) {
if (err2) return cb2(err2);
if (!isdir2) return processDirs(cb2, dirs.slice(1));
loadAsFile(dir, opts.package, onfile2);
}
function onfile2(err2, m, pkg) {
if (err2) return cb2(err2);
if (m) return cb2(null, m, pkg);
loadAsDirectory(dir, opts.package, ondir);
}
function ondir(err2, n, pkg) {
if (err2) return cb2(err2);
if (n) return cb2(null, n, pkg);
processDirs(cb2, dirs.slice(1));
}
}
function loadNodeModules(x2, start, cb2) {
var thunk = function() {
return getPackageCandidates(x2, start, opts);
};
processDirs(
cb2,
packageIterator ? packageIterator(x2, start, thunk, opts) : thunk()
);
}
};
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/core.json
var require_core2 = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/core.json"(exports, module) {
module.exports = {
assert: true,
"node:assert": [">= 14.18 && < 15", ">= 16"],
"assert/strict": ">= 15",
"node:assert/strict": ">= 16",
async_hooks: ">= 8",
"node:async_hooks": [">= 14.18 && < 15", ">= 16"],
buffer_ieee754: ">= 0.5 && < 0.9.7",
buffer: true,
"node:buffer": [">= 14.18 && < 15", ">= 16"],
child_process: true,
"node:child_process": [">= 14.18 && < 15", ">= 16"],
cluster: ">= 0.5",
"node:cluster": [">= 14.18 && < 15", ">= 16"],
console: true,
"node:console": [">= 14.18 && < 15", ">= 16"],
constants: true,
"node:constants": [">= 14.18 && < 15", ">= 16"],
crypto: true,
"node:crypto": [">= 14.18 && < 15", ">= 16"],
_debug_agent: ">= 1 && < 8",
_debugger: "< 8",
dgram: true,
"node:dgram": [">= 14.18 && < 15", ">= 16"],
diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
"node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
dns: true,
"node:dns": [">= 14.18 && < 15", ">= 16"],
"dns/promises": ">= 15",
"node:dns/promises": ">= 16",
domain: ">= 0.7.12",
"node:domain": [">= 14.18 && < 15", ">= 16"],
events: true,
"node:events": [">= 14.18 && < 15", ">= 16"],
"node:ffi": ">= 26.9",
freelist: "< 6",
fs: true,
"node:fs": [">= 14.18 && < 15", ">= 16"],
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"node:fs/promises": [">= 14.18 && < 15", ">= 16"],
_http_agent: ">= 0.11.1",
"node:_http_agent": [">= 14.18 && < 15", ">= 16"],
_http_client: ">= 0.11.1",
"node:_http_client": [">= 14.18 && < 15", ">= 16"],
_http_common: ">= 0.11.1",
"node:_http_common": [">= 14.18 && < 15", ">= 16"],
_http_incoming: ">= 0.11.1",
"node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
_http_outgoing: ">= 0.11.1",
"node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
_http_server: ">= 0.11.1",
"node:_http_server": [">= 14.18 && < 15", ">= 16"],
http: true,
"node:http": [">= 14.18 && < 15", ">= 16"],
http2: ">= 8.8",
"node:http2": [">= 14.18 && < 15", ">= 16"],
https: true,
"node:https": [">= 14.18 && < 15", ">= 16"],
inspector: ">= 8",
"node:inspector": [">= 14.18 && < 15", ">= 16"],
"inspector/promises": [">= 19"],
"node:inspector/promises": [">= 19"],
_linklist: "< 8",
module: true,
"node:module": [">= 14.18 && < 15", ">= 16"],
net: true,
"node:net": [">= 14.18 && < 15", ">= 16"],
"node-inspect/lib/_inspect": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
os: true,
"node:os": [">= 14.18 && < 15", ">= 16"],
path: true,
"node:path": [">= 14.18 && < 15", ">= 16"],
"path/posix": ">= 15.3",
"node:path/posix": ">= 16",
"path/win32": ">= 15.3",
"node:path/win32": ">= 16",
perf_hooks: ">= 8.5",
"node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
process: ">= 1",
"node:process": [">= 14.18 && < 15", ">= 16"],
punycode: ">= 0.5",
"node:punycode": [">= 14.18 && < 15", ">= 16"],
querystring: true,
"node:querystring": [">= 14.18 && < 15", ">= 16"],
readline: true,
"node:readline": [">= 14.18 && < 15", ">= 16"],
"readline/promises": ">= 17",
"node:readline/promises": ">= 17",
repl: true,
"node:repl": [">= 14.18 && < 15", ">= 16"],
"node:sea": [">= 20.12 && < 21", ">= 21.7"],
smalloc: ">= 0.11.5 && < 3",
"node:sqlite": [">= 22.13 && < 23", ">= 23.4"],
_stream_duplex: ">= 0.9.4 && < 26",
"node:_stream_duplex": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_transform: ">= 0.9.4 && < 26",
"node:_stream_transform": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_wrap: ">= 1.4.1 && < 26",
"node:_stream_wrap": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_passthrough: ">= 0.9.4 && < 26",
"node:_stream_passthrough": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_readable: ">= 0.9.4 && < 26",
"node:_stream_readable": [">= 14.18 && < 15", ">= 16 && < 26"],
_stream_writable: ">= 0.9.4 && < 26",
"node:_stream_writable": [">= 14.18 && < 15", ">= 16 && < 26"],
stream: true,
"node:stream": [">= 14.18 && < 15", ">= 16"],
"stream/consumers": ">= 16.7",
"node:stream/consumers": ">= 16.7",
"stream/promises": ">= 15",
"node:stream/promises": ">= 16",
"stream/web": ">= 16.5",
"node:stream/web": ">= 16.5",
string_decoder: true,
"node:string_decoder": [">= 14.18 && < 15", ">= 16"],
sys: [">= 0.4 && < 0.7", ">= 0.8"],
"node:sys": [">= 14.18 && < 15", ">= 16"],
"test/reporters": ">= 19.9 && < 20.2",
"node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
"test/mock_loader": ">= 22.3 && < 22.7",
"node:test/mock_loader": ">= 22.3 && < 22.7",
"node:test": [">= 16.17 && < 17", ">= 18"],
timers: true,
"node:timers": [">= 14.18 && < 15", ">= 16"],
"timers/promises": ">= 15",
"node:timers/promises": ">= 16",
_tls_common: ">= 0.11.13",
"node:_tls_common": [">= 14.18 && < 15", ">= 16"],
_tls_legacy: ">= 0.11.3 && < 10",
_tls_wrap: ">= 0.11.3",
"node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
tls: true,
"node:tls": [">= 14.18 && < 15", ">= 16"],
trace_events: ">= 10",
"node:trace_events": [">= 14.18 && < 15", ">= 16"],
tty: true,
"node:tty": [">= 14.18 && < 15", ">= 16"],
url: true,
"node:url": [">= 14.18 && < 15", ">= 16"],
util: true,
"node:util": [">= 14.18 && < 15", ">= 16"],
"util/types": ">= 15.3",
"node:util/types": ">= 16",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
v8: ">= 1",
"node:v8": [">= 14.18 && < 15", ">= 16"],
vm: true,
"node:vm": [">= 14.18 && < 15", ">= 16"],
wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
"node:wasi": [">= 18.17 && < 19", ">= 20"],
worker_threads: ">= 11.7",
"node:worker_threads": [">= 14.18 && < 15", ">= 16"],
zlib: ">= 0.5",
"node:zlib": [">= 14.18 && < 15", ">= 16"]
};
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/core.js
var require_core3 = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/core.js"(exports, module) {
"use strict";
var isCoreModule = require_is_core_module();
var data = require_core2();
var core = {};
for (mod in data) {
if (Object.prototype.hasOwnProperty.call(data, mod)) {
core[mod] = isCoreModule(mod);
}
}
var mod;
module.exports = core;
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/is-core.js
var require_is_core = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/is-core.js"(exports, module) {
"use strict";
var isCoreModule = require_is_core_module();
module.exports = function isCore(x) {
return isCoreModule(x);
};
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/sync.js
var require_sync = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/lib/sync.js"(exports, module) {
"use strict";
var isCore = require_is_core_module();
var fs2 = _chunkYQNCOY6Vjs.__require.call(void 0, "fs");
var path3 = _chunkYQNCOY6Vjs.__require.call(void 0, "path");
var $Error = require_es_errors();
var $TypeError = require_type();
var getHomedir = require_homedir();
var caller = require_caller();
var nodeModulesPaths = require_node_modules_paths();
var normalizeOptions = require_normalize_options();
var realpathFS = process.platform !== "win32" && fs2.realpathSync && typeof fs2.realpathSync.native === "function" ? fs2.realpathSync.native : fs2.realpathSync;
var relativePathRegex = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/;
var windowsDriveRegex = /^\w:[/\\]*$/;
var nodeModulesRegex = /[/\\]node_modules[/\\]*$/;
var homedir = getHomedir();
function defaultPaths() {
if (!homedir) return [];
return [
path3.join(homedir, ".node_modules"),
path3.join(homedir, ".node_libraries")
];
}
var defaultIsFile = function isFile(file) {
try {
var stat = fs2.statSync(file, { throwIfNoEntry: false });
} catch (e) {
if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false;
throw e;
}
return !!stat && (stat.isFile() || stat.isFIFO());
};
var defaultIsDir = function isDirectory(dir) {
try {
var stat = fs2.statSync(dir, { throwIfNoEntry: false });
} catch (e) {
if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false;
throw e;
}
return !!stat && stat.isDirectory();
};
var defaultRealpathSync = function realpathSync(x) {
try {
return realpathFS(x);
} catch (realpathErr) {
if (realpathErr.code !== "ENOENT") {
throw realpathErr;
}
}
return x;
};
function maybeRealpathSync(realpathSync, x, opts) {
if (opts && opts.preserveSymlinks === false) {
return realpathSync(x);
}
return x;
}
function defaultReadPackageSync(readFileSync, pkgfile) {
var body = readFileSync(pkgfile);
try {
var pkg = JSON.parse(body);
return pkg;
} catch (jsonErr) {
}
}
function getPackageCandidates(x, start, opts) {
var dirs = nodeModulesPaths(start, opts, x);
for (var i = 0; i < dirs.length; i++) {
dirs[i] = path3.join(dirs[i], x);
}
return dirs;
}
module.exports = function resolveSync(x, options) {
if (typeof x !== "string") {
throw new $TypeError("Path must be a string.");
}
var opts = normalizeOptions(x, options);
var isFile = opts.isFile || defaultIsFile;
var readFileSync = opts.readFileSync || fs2.readFileSync;
var isDirectory = opts.isDirectory || defaultIsDir;
var realpathSync = opts.realpathSync || defaultRealpathSync;
var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
if (opts.readFileSync && opts.readPackageSync) {
throw new $TypeError("`readFileSync` and `readPackageSync` are mutually exclusive.");
}
var packageIterator = opts.packageIterator;
var extensions = opts.extensions || [".js"];
var includeCoreModules = opts.includeCoreModules !== false;
var basedir = opts.basedir || path3.dirname(caller());
var parent = opts.filename || basedir;
opts.paths = opts.paths || defaultPaths();
var absoluteStart = maybeRealpathSync(realpathSync, path3.resolve(basedir), opts);
if (relativePathRegex.test(x)) {
var res = path3.resolve(absoluteStart, x);
if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
var m = loadAsFileSync(res) || loadAsDirectorySync(res);
if (m) return maybeRealpathSync(realpathSync, m, opts);
} else if (includeCoreModules && isCore(x)) {
return x;
} else {
var n = loadNodeModulesSync(x, absoluteStart);
if (n) return maybeRealpathSync(realpathSync, n, opts);
}
var err = new $Error("Cannot find module '" + x + "' from '" + parent + "'");
err.code = "MODULE_NOT_FOUND";
throw err;
function loadAsFileSync(x2) {
var pkg = loadpkg(path3.dirname(x2));
if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
var rfile = path3.relative(pkg.dir, x2);
var r = opts.pathFilter(pkg.pkg, x2, rfile);
if (r) {
x2 = path3.resolve(pkg.dir, r);
}
}
if (isFile(x2)) {
return x2;
}
for (var i = 0; i < extensions.length; i++) {
var file = x2 + extensions[i];
if (isFile(file)) {
return file;
}
}
}
function loadpkg(dir) {
if (dir === "" || dir === "/") return;
if (process.platform === "win32" && windowsDriveRegex.test(dir)) {
return;
}
if (nodeModulesRegex.test(dir)) return;
var pkgfile = path3.join(maybeRealpathSync(realpathSync, dir, opts), "package.json");
if (!isFile(pkgfile)) {
return loadpkg(path3.dirname(dir));
}
var pkg = readPackageSync(readFileSync, pkgfile);
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(
pkg,
/*pkgfile,*/
dir
);
}
return { pkg, dir };
}
function loadAsDirectorySync(x2) {
var pkgfile = path3.join(maybeRealpathSync(realpathSync, x2, opts), "/package.json");
if (isFile(pkgfile)) {
try {
var pkg = readPackageSync(readFileSync, pkgfile);
} catch (e) {
}
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(
pkg,
/*pkgfile,*/
x2
);
}
if (pkg && pkg.main) {
if (typeof pkg.main !== "string") {
var mainError = new $TypeError("package \u201C" + pkg.name + "\u201D `main` must be a string");
mainError.code = "INVALID_PACKAGE_MAIN";
throw mainError;
}
if (pkg.main === "." || pkg.main === "./") {
pkg.main = "index";
}
try {
var m2 = loadAsFileSync(path3.resolve(x2, pkg.main));
if (m2) return m2;
var n2 = loadAsDirectorySync(path3.resolve(x2, pkg.main));
if (n2) return n2;
} catch (e) {
}
}
}
return loadAsFileSync(path3.join(x2, "/index"));
}
function loadNodeModulesSync(x2, start) {
var thunk = function() {
return getPackageCandidates(x2, start, opts);
};
var dirs = packageIterator ? packageIterator(x2, start, thunk, opts) : thunk();
for (var i = 0; i < dirs.length; i++) {
var dir = dirs[i];
if (isDirectory(path3.dirname(dir))) {
var m2 = loadAsFileSync(dir);
if (m2) return m2;
var n2 = loadAsDirectorySync(dir);
if (n2) return n2;
}
}
}
};
}
});
// node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/index.js
var require_resolve = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/resolve@1.22.13/node_modules/resolve/index.js"(exports, module) {
"use strict";
var async = require_async();
async.core = require_core3();
async.isCore = require_is_core();
async.sync = require_sync();
module.exports = async;
}
});
// node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js
var require_sourcemap_codec_umd = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js"(exports, module) {
"use strict";
(function(global, factory) {
if (typeof exports === "object" && typeof module !== "undefined") {
factory(module);
module.exports = def(module);
} else if (typeof define === "function" && define.amd) {
define(["module"], function(mod) {
factory.apply(this, arguments);
mod.exports = def(mod);
});
} else {
const mod = { exports: {} };
factory(mod);
global = typeof globalThis !== "undefined" ? globalThis : global || self;
global.sourcemapCodec = def(mod);
}
function def(m) {
return "default" in m.exports ? m.exports.default : m.exports;
}
})(exports, (function(module2) {
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export2 = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS2 = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var sourcemap_codec_exports = {};
__export2(sourcemap_codec_exports, {
decode: () => decode,
decodeGeneratedRanges: () => decodeGeneratedRanges,
decodeOriginalScopes: () => decodeOriginalScopes,
decodeRangeMappings: () => decodeRangeMappings,
encode: () => encode,
encodeGeneratedRanges: () => encodeGeneratedRanges,
encodeOriginalScopes: () => encodeOriginalScopes,
encodeRangeMappings: () => encodeRangeMappings
});
module2.exports = __toCommonJS2(sourcemap_codec_exports);
var comma = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
function decodeInteger(reader) {
let value2 = 0;
let shift = 0;
let integer = 0;
do {
const c = reader.next();
integer = charToInt[c];
value2 |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
return value2;
}
function decodeSign(num) {
return num & 1 ? -2147483648 | -(num >>> 1) : num >>> 1;
}
function encodeInteger(builder, num) {
do {
let clamped = num & 31;
num >>>= 5;
if (num > 0) clamped |= 32;
builder.write(intToChar[clamped]);
} while (num > 0);
}
function encodeSign(num) {
return num < 0 ? -num << 1 | 1 : num << 1;
}
function hasMoreVlq(reader, max) {
if (reader.pos >= max) return false;
return reader.peek() !== comma;
}
var bufLength = 1024 * 16;
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
decode(buf) {
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return out.toString();
}
} : {
decode(buf) {
let out = "";
for (let i = 0; i < buf.length; i++) {
out += String.fromCharCode(buf[i]);
}
return out;
}
};
var StringWriter = class {
constructor() {
this.pos = 0;
this.out = "";
this.buffer = new Uint8Array(bufLength);
}
write(v) {
const { buffer } = this;
buffer[this.pos++] = v;
if (this.pos === bufLength) {
this.out += td.decode(buffer);
this.pos = 0;
}
}
flush() {
const { buffer, out, pos } = this;
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
}
};
var StringReader = class {
constructor(buffer) {
this.pos = 0;
this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
const { buffer, pos } = this;
const idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
};
var EMPTY = [];
function decodeOriginalScopes(input) {
const { length } = input;
const reader = new StringReader(input);
const scopes = [];
const stack = [];
let line = 0;
for (; reader.pos < length; reader.pos++) {
line += decodeSign(decodeInteger(reader));
const column = decodeSign(decodeInteger(reader));
if (!hasMoreVlq(reader, length)) {
const last = stack.pop();
last[2] = line;
last[3] = column;
continue;
}
const kind = decodeSign(decodeInteger(reader));
const fields = decodeSign(decodeInteger(reader));
const hasName = fields & 1;
const scope = hasName ? [line, column, 0, 0, kind, decodeSign(decodeInteger(reader))] : [line, column, 0, 0, kind];
let vars = EMPTY;
if (hasMoreVlq(reader, length)) {
vars = [];
do {
const varsIndex = decodeSign(decodeInteger(reader));
vars.push(varsIndex);
} while (hasMoreVlq(reader, length));
}
scope.vars = vars;
scopes.push(scope);
stack.push(scope);
}
return scopes;
}
function encodeOriginalScopes(scopes) {
const writer = new StringWriter();
for (let i = 0; i < scopes.length; ) {
i = _encodeOriginalScopes(scopes, i, writer, [0]);
}
return writer.flush();
}
function _encodeOriginalScopes(scopes, index, writer, state) {
const scope = scopes[index];
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
if (index > 0) writer.write(comma);
encodeInteger(writer, encodeSign(startLine - state[0]));
state[0] = startLine;
encodeInteger(writer, encodeSign(startColumn));
encodeInteger(writer, encodeSign(kind));
const fields = scope.length === 6 ? 1 : 0;
encodeInteger(writer, encodeSign(fields));
if (scope.length === 6) encodeInteger(writer, encodeSign(scope[5]));
for (const v of vars) {
encodeInteger(writer, encodeSign(v));
}
for (index++; index < scopes.length; ) {
const next = scopes[index];
const { 0: l, 1: c } = next;
if (l > endLine || l === endLine && c >= endColumn) {
break;
}
index = _encodeOriginalScopes(scopes, index, writer, state);
}
writer.write(comma);
encodeInteger(writer, encodeSign(endLine - state[0]));
state[0] = endLine;
encodeInteger(writer, encodeSign(endColumn));
return index;
}
function decodeGeneratedRanges(input) {
const { length } = input;
const reader = new StringReader(input);
const ranges = [];
const stack = [];
let genLine = 0;
let definitionSourcesIndex = 0;
let definitionScopeIndex = 0;
let callsiteSourcesIndex = 0;
let callsiteLine = 0;
let callsiteColumn = 0;
let bindingLine = 0;
let bindingColumn = 0;
do {
const semi = reader.indexOf(";");
let genColumn = 0;
for (; reader.pos < semi; reader.pos++) {
genColumn += decodeSign(decodeInteger(reader));
if (!hasMoreVlq(reader, semi)) {
const last = stack.pop();
last[2] = genLine;
last[3] = genColumn;
continue;
}
const fields = decodeSign(decodeInteger(reader));
const hasDefinition = fields & 1;
const hasCallsite = fields & 2;
const hasScope = fields & 4;
let callsite = null;
let bindings = EMPTY;
let range;
if (hasDefinition) {
const defSourcesIndex = definitionSourcesIndex + decodeSign(decodeInteger(reader));
definitionScopeIndex = decodeSign(decodeInteger(reader)) + (definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0);
definitionSourcesIndex = defSourcesIndex;
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
} else {
range = [genLine, genColumn, 0, 0];
}
range.isScope = !!hasScope;
if (hasCallsite) {
const prevCsi = callsiteSourcesIndex;
const prevLine = callsiteLine;
callsiteSourcesIndex += decodeSign(decodeInteger(reader));
const sameSource = prevCsi === callsiteSourcesIndex;
callsiteLine = (sameSource ? callsiteLine : 0) + decodeSign(decodeInteger(reader));
callsiteColumn = (sameSource && prevLine === callsiteLine ? callsiteColumn : 0) + decodeSign(decodeInteger(reader));
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
}
range.callsite = callsite;
if (hasMoreVlq(reader, semi)) {
bindings = [];
do {
bindingLine = genLine;
bindingColumn = genColumn;
const expressionsCount = decodeSign(decodeInteger(reader));
let expressionRanges;
if (expressionsCount < -1) {
expressionRanges = [[decodeSign(decodeInteger(reader))]];
for (let i = -1; i > expressionsCount; i--) {
const prevBl = bindingLine;
bindingLine += decodeSign(decodeInteger(reader));
bindingColumn = (bindingLine === prevBl ? bindingColumn : 0) + decodeSign(decodeInteger(reader));
const expression = decodeSign(decodeInteger(reader));
expressionRanges.push([expression, bindingLine, bindingColumn]);
}
} else {
expressionRanges = [[expressionsCount]];
}
bindings.push(expressionRanges);
} while (hasMoreVlq(reader, semi));
}
range.bindings = bindings;
ranges.push(range);
stack.push(range);
}
genLine++;
reader.pos = semi + 1;
} while (reader.pos < length);
return ranges;
}
function encodeGeneratedRanges(ranges) {
if (ranges.length === 0) return "";
const writer = new StringWriter();
for (let i = 0; i < ranges.length; ) {
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
}
return writer.flush();
}
function _encodeGeneratedRanges(ranges, index, writer, state) {
const range = ranges[index];
const {
0: startLine,
1: startColumn,
2: endLine,
3: endColumn,
isScope,
callsite,
bindings
} = range;
if (state[0] < startLine) {
catchupLine(writer, state[0], startLine);
state[0] = startLine;
state[1] = 0;
} else if (index > 0) {
writer.write(comma);
}
encodeInteger(writer, encodeSign(range[1] - state[1]));
state[1] = range[1];
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
encodeInteger(writer, encodeSign(fields));
if (range.length === 6) {
const { 4: sourcesIndex, 5: scopesIndex } = range;
if (sourcesIndex !== state[2]) {
state[3] = 0;
}
encodeInteger(writer, encodeSign(sourcesIndex - state[2]));
state[2] = sourcesIndex;
encodeInteger(writer, encodeSign(scopesIndex - state[3]));
state[3] = scopesIndex;
}
if (callsite) {
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
if (sourcesIndex !== state[4]) {
state[5] = 0;
state[6] = 0;
} else if (callLine !== state[5]) {
state[6] = 0;
}
encodeInteger(writer, encodeSign(sourcesIndex - state[4]));
state[4] = sourcesIndex;
encodeInteger(writer, encodeSign(callLine - state[5]));
state[5] = callLine;
encodeInteger(writer, encodeSign(callColumn - state[6]));
state[6] = callColumn;
}
if (bindings) {
for (const binding of bindings) {
if (binding.length > 1) encodeInteger(writer, encodeSign(-binding.length));
const expression = binding[0][0];
encodeInteger(writer, encodeSign(expression));
let bindingStartLine = startLine;
let bindingStartColumn = startColumn;
for (let i = 1; i < binding.length; i++) {
const expRange = binding[i];
encodeInteger(writer, encodeSign(expRange[1] - bindingStartLine));
bindingStartLine = expRange[1];
encodeInteger(writer, encodeSign(expRange[2] - bindingStartColumn));
bindingStartColumn = expRange[2];
encodeInteger(writer, encodeSign(expRange[0]));
}
}
}
for (index++; index < ranges.length; ) {
const next = ranges[index];
const { 0: l, 1: c } = next;
if (l > endLine || l === endLine && c >= endColumn) {
break;
}
index = _encodeGeneratedRanges(ranges, index, writer, state);
}
if (state[0] < endLine) {
catchupLine(writer, state[0], endLine);
state[0] = endLine;
state[1] = 0;
} else {
writer.write(comma);
}
encodeInteger(writer, encodeSign(endColumn - state[1]));
state[1] = endColumn;
return index;
}
function catchupLine(writer, lastLine, line) {
do {
writer.write(semicolon);
} while (++lastLine < line);
}
function decodeRangeMappings(input) {
const { length } = input;
const reader = new StringReader(input);
const rangeMappings = [];
do {
const semi = reader.indexOf(";");
const indices = [];
let index = 0;
while (reader.pos < semi) {
index += decodeInteger(reader);
indices.push(index);
}
rangeMappings.push(indices);
reader.pos = semi + 1;
} while (reader.pos <= length);
return rangeMappings;
}
function encodeRangeMappings(decoded) {
if (decoded.length === 0) return "";
const writer = new StringWriter();
for (let i = 0; i < decoded.length; i++) {
const indices = decoded[i];
if (i > 0) writer.write(semicolon);
let index = 0;
for (let j = 0; j < indices.length; j++) {
const offset = indices[j];
encodeInteger(writer, offset - index);
index = offset;
}
}
return writer.flush();
}
function decode(mappings) {
const { length } = mappings;
const reader = new StringReader(mappings);
const decoded = [];
let genColumn = 0;
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
do {
const semi = reader.indexOf(";");
const line = [];
let sorted = true;
let lastCol = 0;
genColumn = 0;
while (reader.pos < semi) {
let seg;
genColumn += decodeSign(decodeInteger(reader));
if (genColumn < lastCol) sorted = false;
lastCol = genColumn;
if (hasMoreVlq(reader, semi)) {
sourcesIndex += decodeSign(decodeInteger(reader));
sourceLine += decodeSign(decodeInteger(reader));
sourceColumn += decodeSign(decodeInteger(reader));
if (hasMoreVlq(reader, semi)) {
namesIndex += decodeSign(decodeInteger(reader));
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
} else {
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
}
} else {
seg = [genColumn];
}
line.push(seg);
reader.pos++;
}
if (!sorted) sort(line);
decoded.push(line);
reader.pos = semi + 1;
} while (reader.pos <= length);
return decoded;
}
function sort(line) {
line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[0] - b[0];
}
function encode(decoded) {
const writer = new StringWriter();
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) writer.write(semicolon);
if (line.length === 0) continue;
let genColumn = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
if (j > 0) writer.write(comma);
encodeInteger(writer, encodeSign(segment[0] - genColumn));
genColumn = segment[0];
if (segment.length === 1) continue;
encodeInteger(writer, encodeSign(segment[1] - sourcesIndex));
encodeInteger(writer, encodeSign(segment[2] - sourceLine));
encodeInteger(writer, encodeSign(segment[3] - sourceColumn));
sourcesIndex = segment[1];
sourceLine = segment[2];
sourceColumn = segment[3];
if (segment.length === 4) continue;
encodeInteger(writer, encodeSign(segment[4] - namesIndex));
namesIndex = segment[4];
}
}
return writer.flush();
}
}));
}
});
// node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
var require_resolve_uri_umd = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js"(exports, module) {
"use strict";
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.resolveURI = factory());
})(exports, (function() {
"use strict";
const schemeRegex = /^[\w+.-]+:\/\//;
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
function isAbsoluteUrl(input) {
return schemeRegex.test(input);
}
function isSchemeRelativeUrl(input) {
return input.startsWith("//");
}
function isAbsolutePath(input) {
return input.startsWith("/");
}
function isFileUrl(input) {
return input.startsWith("file:");
}
function isRelative(input) {
return /^[.?#]/.test(input);
}
function parseAbsoluteUrl(input) {
const match = urlRegex.exec(input);
return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
}
function parseFileUrl(input) {
const match = fileRegex.exec(input);
const path3 = match[2];
return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path3) ? path3 : "/" + path3, match[3] || "", match[4] || "");
}
function makeUrl(scheme, user, host, port, path3, query, hash) {
return {
scheme,
user,
host,
port,
path: path3,
query,
hash,
type: 7
};
}
function parseUrl(input) {
if (isSchemeRelativeUrl(input)) {
const url2 = parseAbsoluteUrl("http:" + input);
url2.scheme = "";
url2.type = 6;
return url2;
}
if (isAbsolutePath(input)) {
const url2 = parseAbsoluteUrl("http://foo.com" + input);
url2.scheme = "";
url2.host = "";
url2.type = 5;
return url2;
}
if (isFileUrl(input))
return parseFileUrl(input);
if (isAbsoluteUrl(input))
return parseAbsoluteUrl(input);
const url = parseAbsoluteUrl("http://foo.com/" + input);
url.scheme = "";
url.host = "";
url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
return url;
}
function stripPathFilename(path3) {
if (path3.endsWith("/.."))
return path3;
const index = path3.lastIndexOf("/");
return path3.slice(0, index + 1);
}
function mergePaths(url, base) {
normalizePath3(base, base.type);
if (url.path === "/") {
url.path = base.path;
} else {
url.path = stripPathFilename(base.path) + url.path;
}
}
function normalizePath3(url, type) {
const rel = type <= 4;
const pieces = url.path.split("/");
let pointer = 1;
let positive = 0;
let addTrailingSlash = false;
for (let i = 1; i < pieces.length; i++) {
const piece = pieces[i];
if (!piece) {
addTrailingSlash = true;
continue;
}
addTrailingSlash = false;
if (piece === ".")
continue;
if (piece === "..") {
if (positive) {
addTrailingSlash = true;
positive--;
pointer--;
} else if (rel) {
pieces[pointer++] = piece;
}
continue;
}
pieces[pointer++] = piece;
positive++;
}
let path3 = "";
for (let i = 1; i < pointer; i++) {
path3 += "/" + pieces[i];
}
if (!path3 || addTrailingSlash && !path3.endsWith("/..")) {
path3 += "/";
}
url.path = path3;
}
function resolve2(input, base) {
if (!input && !base)
return "";
const url = parseUrl(input);
let inputType = url.type;
if (base && inputType !== 7) {
const baseUrl = parseUrl(base);
const baseType = baseUrl.type;
switch (inputType) {
case 1:
url.hash = baseUrl.hash;
// fall through
case 2:
url.query = baseUrl.query;
// fall through
case 3:
case 4:
mergePaths(url, baseUrl);
// fall through
case 5:
url.user = baseUrl.user;
url.host = baseUrl.host;
url.port = baseUrl.port;
// fall through
case 6:
url.scheme = baseUrl.scheme;
}
if (baseType > inputType)
inputType = baseType;
}
normalizePath3(url, inputType);
const queryHash = url.query + url.hash;
switch (inputType) {
// This is impossible, because of the empty checks at the start of the function.
// case UrlType.Empty:
case 2:
case 3:
return queryHash;
case 4: {
const path3 = url.path.slice(1);
if (!path3)
return queryHash || ".";
if (isRelative(base || input) && !isRelative(path3)) {
return "./" + path3 + queryHash;
}
return path3 + queryHash;
}
case 5:
return url.path + queryHash;
default:
return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
}
}
return resolve2;
}));
}
});
// node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js
var require_trace_mapping_umd = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js"(exports, module) {
"use strict";
(function(global, factory) {
if (typeof exports === "object" && typeof module !== "undefined") {
factory(module, require_resolve_uri_umd(), require_sourcemap_codec_umd());
module.exports = def(module);
} else if (typeof define === "function" && define.amd) {
define(["module", "@jridgewell/resolve-uri", "@jridgewell/sourcemap-codec"], function(mod) {
factory.apply(this, arguments);
mod.exports = def(mod);
});
} else {
const mod = { exports: {} };
factory(mod, global.resolveURI, global.sourcemapCodec);
global = typeof globalThis !== "undefined" ? globalThis : global || self;
global.traceMapping = def(mod);
}
function def(m) {
return "default" in m.exports ? m.exports.default : m.exports;
}
})(exports, (function(module2, require_resolveURI, require_sourcemapCodec) {
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS2 = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export2 = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS2 = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var require_sourcemap_codec = __commonJS2({
"umd:@jridgewell/sourcemap-codec"(exports2, module22) {
module22.exports = require_sourcemapCodec;
}
});
var require_resolve_uri = __commonJS2({
"umd:@jridgewell/resolve-uri"(exports2, module22) {
module22.exports = require_resolveURI;
}
});
var trace_mapping_exports = {};
__export2(trace_mapping_exports, {
AnyMap: () => FlattenMap,
FlattenMap: () => FlattenMap,
GREATEST_LOWER_BOUND: () => GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND: () => LEAST_UPPER_BOUND,
TraceMap: () => TraceMap,
allGeneratedPositionsFor: () => allGeneratedPositionsFor,
decodedMap: () => decodedMap,
decodedMappings: () => decodedMappings,
eachMapping: () => eachMapping,
encodedMap: () => encodedMap,
encodedMappings: () => encodedMappings,
generatedPositionFor: () => generatedPositionFor,
isIgnored: () => isIgnored,
originalPositionFor: () => originalPositionFor,
presortedDecodedMap: () => presortedDecodedMap,
sourceContentFor: () => sourceContentFor,
traceSegment: () => traceSegment
});
module2.exports = __toCommonJS2(trace_mapping_exports);
var import_sourcemap_codec = __toESM2(require_sourcemap_codec());
var import_resolve_uri = __toESM2(require_resolve_uri());
function stripFilename(path3) {
if (!path3) return "";
const index = path3.lastIndexOf("/");
return path3.slice(0, index + 1);
}
function resolver(mapUrl, sourceRoot) {
const from = stripFilename(mapUrl);
const prefix = sourceRoot ? sourceRoot + "/" : "";
return (source) => (0, import_resolve_uri.default)(prefix + (source || ""), from);
}
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
var REV_GENERATED_LINE = 1;
var REV_GENERATED_COLUMN = 2;
function maybeSort(mappings, owned) {
const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
if (unsortedIndex === mappings.length) return mappings;
if (!owned) mappings = mappings.slice();
for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
mappings[i] = sortSegments(mappings[i], owned);
}
return mappings;
}
function nextUnsortedSegmentLine(mappings, start) {
for (let i = start; i < mappings.length; i++) {
if (!isSorted(mappings[i])) return i;
}
return mappings.length;
}
function isSorted(line) {
for (let j = 1; j < line.length; j++) {
if (line[j][COLUMN] < line[j - 1][COLUMN]) {
return false;
}
}
return true;
}
function sortSegments(line, owned) {
if (!owned) line = line.slice();
return line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[COLUMN] - b[COLUMN];
}
function buildBySources(decoded, memos) {
const sources = memos.map(() => []);
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
for (let j = 0; j < line.length; j++) {
const seg = line[j];
if (seg.length === 1) continue;
const sourceIndex2 = seg[SOURCES_INDEX];
const sourceLine = seg[SOURCE_LINE];
const sourceColumn = seg[SOURCE_COLUMN];
const source = sources[sourceIndex2];
const segs = source[sourceLine] || (source[sourceLine] = []);
segs.push([sourceColumn, i, seg[COLUMN]]);
}
}
for (let i = 0; i < sources.length; i++) {
const source = sources[i];
for (let j = 0; j < source.length; j++) {
const line = source[j];
if (line) line.sort(sortComparator);
}
}
return sources;
}
var found = false;
function binarySearch(haystack, needle, low, high) {
while (low <= high) {
const mid = low + (high - low >> 1);
const cmp = haystack[mid][COLUMN] - needle;
if (cmp === 0) {
found = true;
return mid;
}
if (cmp < 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
found = false;
return low - 1;
}
function upperBound(haystack, needle, index) {
for (let i = index + 1; i < haystack.length; index = i++) {
if (haystack[i][COLUMN] !== needle) break;
}
return index;
}
function lowerBound(haystack, needle, index) {
for (let i = index - 1; i >= 0; index = i--) {
if (haystack[i][COLUMN] !== needle) break;
}
return index;
}
function memoizedState() {
return {
lastKey: -1,
lastNeedle: -1,
lastIndex: -1
};
}
function memoizedBinarySearch(haystack, needle, state, key) {
const { lastKey, lastNeedle, lastIndex } = state;
let low = 0;
let high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle) {
found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
return lastIndex;
}
if (needle >= lastNeedle) {
low = lastIndex === -1 ? 0 : lastIndex;
} else {
high = lastIndex;
}
}
state.lastKey = key;
state.lastNeedle = needle;
return state.lastIndex = binarySearch(haystack, needle, low, high);
}
function parse(map) {
return typeof map === "string" ? JSON.parse(map) : map;
}
var FlattenMap = function(map, mapUrl) {
const parsed = parse(map);
if (!("sections" in parsed)) {
return new TraceMap(parsed, mapUrl);
}
const mappings = [];
const sources = [];
const sourcesContent = [];
const names = [];
const ignoreList = [];
recurse(
parsed,
mapUrl,
mappings,
sources,
sourcesContent,
names,
ignoreList,
0,
0,
Infinity,
Infinity
);
const joined = {
version: 3,
file: parsed.file,
names,
sources,
sourcesContent,
mappings,
ignoreList
};
return presortedDecodedMap(joined);
};
function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
const { sections } = input;
for (let i = 0; i < sections.length; i++) {
const { map, offset } = sections[i];
let sl = stopLine;
let sc = stopColumn;
if (i + 1 < sections.length) {
const nextOffset = sections[i + 1].offset;
sl = Math.min(stopLine, lineOffset + nextOffset.line);
if (sl === stopLine) {
sc = Math.min(stopColumn, columnOffset + nextOffset.column);
} else if (sl < stopLine) {
sc = columnOffset + nextOffset.column;
}
}
addSection(
map,
mapUrl,
mappings,
sources,
sourcesContent,
names,
ignoreList,
lineOffset + offset.line,
columnOffset + offset.column,
sl,
sc
);
}
}
function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
const parsed = parse(input);
if ("sections" in parsed) return recurse(...arguments);
const map = new TraceMap(parsed, mapUrl);
const sourcesOffset = sources.length;
const namesOffset = names.length;
const decoded = decodedMappings(map);
const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map;
append(sources, resolvedSources);
append(names, map.names);
if (contents) append(sourcesContent, contents);
else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);
if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset);
for (let i = 0; i < decoded.length; i++) {
const lineI = lineOffset + i;
if (lineI > stopLine) return;
const out = getLine(mappings, lineI);
const cOffset = i === 0 ? columnOffset : 0;
const line = decoded[i];
for (let j = 0; j < line.length; j++) {
const seg = line[j];
const column = cOffset + seg[COLUMN];
if (lineI === stopLine && column >= stopColumn) return;
if (seg.length === 1) {
out.push([column]);
continue;
}
const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];
const sourceLine = seg[SOURCE_LINE];
const sourceColumn = seg[SOURCE_COLUMN];
out.push(
seg.length === 4 ? [column, sourcesIndex, sourceLine, sourceColumn] : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]
);
}
}
}
function append(arr, other) {
for (let i = 0; i < other.length; i++) arr.push(other[i]);
}
function getLine(arr, index) {
for (let i = arr.length; i <= index; i++) arr[i] = [];
return arr[index];
}
var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
var LEAST_UPPER_BOUND = -1;
var GREATEST_LOWER_BOUND = 1;
var TraceMap = class {
constructor(map, mapUrl) {
const isString = typeof map === "string";
if (!isString && map._decodedMemo) return map;
const parsed = parse(map);
const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
this.version = version;
this.file = file;
this.names = names || [];
this.sourceRoot = sourceRoot;
this.sources = sources;
this.sourcesContent = sourcesContent;
this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
const resolve2 = resolver(mapUrl, sourceRoot);
this.resolvedSources = sources.map(resolve2);
const { mappings } = parsed;
if (typeof mappings === "string") {
this._encoded = mappings;
this._decoded = void 0;
} else if (Array.isArray(mappings)) {
this._encoded = void 0;
this._decoded = maybeSort(mappings, isString);
} else if (parsed.sections) {
throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
} else {
throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
}
this._decodedMemo = memoizedState();
this._bySources = void 0;
this._bySourceMemos = void 0;
}
};
function cast(map) {
return map;
}
function encodedMappings(map) {
var _a, _b;
return (_b = (_a = cast(map))._encoded) != null ? _b : _a._encoded = (0, import_sourcemap_codec.encode)(cast(map)._decoded);
}
function decodedMappings(map) {
var _a;
return (_a = cast(map))._decoded || (_a._decoded = (0, import_sourcemap_codec.decode)(cast(map)._encoded));
}
function traceSegment(map, line, column) {
const decoded = decodedMappings(map);
if (line >= decoded.length) return null;
const segments = decoded[line];
const index = traceSegmentInternal(
segments,
cast(map)._decodedMemo,
line,
column,
GREATEST_LOWER_BOUND
);
return index === -1 ? null : segments[index];
}
function originalPositionFor(map, needle) {
let { line, column, bias } = needle;
line--;
if (line < 0) throw new Error(LINE_GTR_ZERO);
if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
const decoded = decodedMappings(map);
if (line >= decoded.length) return OMapping(null, null, null, null);
const segments = decoded[line];
const index = traceSegmentInternal(
segments,
cast(map)._decodedMemo,
line,
column,
bias || GREATEST_LOWER_BOUND
);
if (index === -1) return OMapping(null, null, null, null);
const segment = segments[index];
if (segment.length === 1) return OMapping(null, null, null, null);
const { names, resolvedSources } = map;
return OMapping(
resolvedSources[segment[SOURCES_INDEX]],
segment[SOURCE_LINE] + 1,
segment[SOURCE_COLUMN],
segment.length === 5 ? names[segment[NAMES_INDEX]] : null
);
}
function generatedPositionFor(map, needle) {
const { source, line, column, bias } = needle;
return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);
}
function allGeneratedPositionsFor(map, needle) {
const { source, line, column, bias } = needle;
return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);
}
function eachMapping(map, cb) {
const decoded = decodedMappings(map);
const { names, resolvedSources } = map;
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
for (let j = 0; j < line.length; j++) {
const seg = line[j];
const generatedLine = i + 1;
const generatedColumn = seg[0];
let source = null;
let originalLine = null;
let originalColumn = null;
let name = null;
if (seg.length !== 1) {
source = resolvedSources[seg[1]];
originalLine = seg[2] + 1;
originalColumn = seg[3];
}
if (seg.length === 5) name = names[seg[4]];
cb({
generatedLine,
generatedColumn,
source,
originalLine,
originalColumn,
name
});
}
}
}
function sourceIndex(map, source) {
const { sources, resolvedSources } = map;
let index = sources.indexOf(source);
if (index === -1) index = resolvedSources.indexOf(source);
return index;
}
function sourceContentFor(map, source) {
const { sourcesContent } = map;
if (sourcesContent == null) return null;
const index = sourceIndex(map, source);
return index === -1 ? null : sourcesContent[index];
}
function isIgnored(map, source) {
const { ignoreList } = map;
if (ignoreList == null) return false;
const index = sourceIndex(map, source);
return index === -1 ? false : ignoreList.includes(index);
}
function presortedDecodedMap(map, mapUrl) {
const tracer = new TraceMap(clone(map, []), mapUrl);
cast(tracer)._decoded = map.mappings;
return tracer;
}
function decodedMap(map) {
return clone(map, decodedMappings(map));
}
function encodedMap(map) {
return clone(map, encodedMappings(map));
}
function clone(map, mappings) {
return {
version: map.version,
file: map.file,
names: map.names,
sourceRoot: map.sourceRoot,
sources: map.sources,
sourcesContent: map.sourcesContent,
mappings,
ignoreList: map.ignoreList || map.x_google_ignoreList
};
}
function OMapping(source, line, column, name) {
return { source, line, column, name };
}
function GMapping(line, column) {
return { line, column };
}
function traceSegmentInternal(segments, memo, line, column, bias) {
let index = memoizedBinarySearch(segments, column, memo, line);
if (found) {
index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
} else if (bias === LEAST_UPPER_BOUND) index++;
if (index === -1 || index === segments.length) return -1;
return index;
}
function sliceGeneratedPositions(segments, memo, line, column, bias) {
let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);
if (!found && bias === LEAST_UPPER_BOUND) min++;
if (min === -1 || min === segments.length) return [];
const matchedColumn = found ? column : segments[min][COLUMN];
if (!found) min = lowerBound(segments, matchedColumn, min);
const max = upperBound(segments, matchedColumn, min);
const result = [];
for (; min <= max; min++) {
const segment = segments[min];
result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));
}
return result;
}
function generatedPosition(map, source, line, column, bias, all) {
var _a, _b;
line--;
if (line < 0) throw new Error(LINE_GTR_ZERO);
if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
const { sources, resolvedSources } = map;
let sourceIndex2 = sources.indexOf(source);
if (sourceIndex2 === -1) sourceIndex2 = resolvedSources.indexOf(source);
if (sourceIndex2 === -1) return all ? [] : GMapping(null, null);
const bySourceMemos = (_a = cast(map))._bySourceMemos || (_a._bySourceMemos = sources.map(memoizedState));
const generated = (_b = cast(map))._bySources || (_b._bySources = buildBySources(decodedMappings(map), bySourceMemos));
const segments = generated[sourceIndex2][line];
if (segments == null) return all ? [] : GMapping(null, null);
const memo = bySourceMemos[sourceIndex2];
if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);
const index = traceSegmentInternal(segments, memo, line, column, bias);
if (index === -1) return GMapping(null, null);
const segment = segments[index];
return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
}
}));
}
});
// node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js
var require_gen_mapping_umd = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js"(exports, module) {
"use strict";
(function(global, factory) {
if (typeof exports === "object" && typeof module !== "undefined") {
factory(module, require_sourcemap_codec_umd(), require_trace_mapping_umd());
module.exports = def(module);
} else if (typeof define === "function" && define.amd) {
define(["module", "@jridgewell/sourcemap-codec", "@jridgewell/trace-mapping"], function(mod) {
factory.apply(this, arguments);
mod.exports = def(mod);
});
} else {
const mod = { exports: {} };
factory(mod, global.sourcemapCodec, global.traceMapping);
global = typeof globalThis !== "undefined" ? globalThis : global || self;
global.genMapping = def(mod);
}
function def(m) {
return "default" in m.exports ? m.exports.default : m.exports;
}
})(exports, (function(module2, require_sourcemapCodec, require_traceMapping) {
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS2 = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export2 = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS2 = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var require_sourcemap_codec = __commonJS2({
"umd:@jridgewell/sourcemap-codec"(exports2, module22) {
module22.exports = require_sourcemapCodec;
}
});
var require_trace_mapping = __commonJS2({
"umd:@jridgewell/trace-mapping"(exports2, module22) {
module22.exports = require_traceMapping;
}
});
var gen_mapping_exports = {};
__export2(gen_mapping_exports, {
GenMapping: () => GenMapping,
addMapping: () => addMapping,
addSegment: () => addSegment,
allMappings: () => allMappings,
fromMap: () => fromMap,
maybeAddMapping: () => maybeAddMapping,
maybeAddSegment: () => maybeAddSegment,
setIgnore: () => setIgnore,
setSourceContent: () => setSourceContent,
toDecodedMap: () => toDecodedMap,
toEncodedMap: () => toEncodedMap
});
module2.exports = __toCommonJS2(gen_mapping_exports);
var SetArray = class {
constructor() {
this._indexes = { __proto__: null };
this.array = [];
}
};
function cast(set) {
return set;
}
function get(setarr, key) {
return cast(setarr)._indexes[key];
}
function put(setarr, key) {
const index = get(setarr, key);
if (index !== void 0) return index;
const { array, _indexes: indexes } = cast(setarr);
const length = array.push(key);
return indexes[key] = length - 1;
}
function remove(setarr, key) {
const index = get(setarr, key);
if (index === void 0) return;
const { array, _indexes: indexes } = cast(setarr);
for (let i = index + 1; i < array.length; i++) {
const k = array[i];
array[i - 1] = k;
indexes[k]--;
}
indexes[key] = void 0;
array.pop();
}
var import_sourcemap_codec = __toESM2(require_sourcemap_codec());
var import_trace_mapping = __toESM2(require_trace_mapping());
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
var NO_NAME = -1;
var GenMapping = class {
constructor({ file, sourceRoot } = {}) {
this._names = new SetArray();
this._sources = new SetArray();
this._sourcesContent = [];
this._mappings = [];
this.file = file;
this.sourceRoot = sourceRoot;
this._ignoreList = new SetArray();
}
};
function cast2(map) {
return map;
}
function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
return addSegmentInternal(
false,
map,
genLine,
genColumn,
source,
sourceLine,
sourceColumn,
name,
content
);
}
function addMapping(map, mapping) {
return addMappingInternal(false, map, mapping);
}
var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
return addSegmentInternal(
true,
map,
genLine,
genColumn,
source,
sourceLine,
sourceColumn,
name,
content
);
};
var maybeAddMapping = (map, mapping) => {
return addMappingInternal(true, map, mapping);
};
function setSourceContent(map, source, content) {
const {
_sources: sources,
_sourcesContent: sourcesContent
// _originalScopes: originalScopes,
} = cast2(map);
const index = put(sources, source);
sourcesContent[index] = content;
}
function setIgnore(map, source, ignore = true) {
const {
_sources: sources,
_sourcesContent: sourcesContent,
_ignoreList: ignoreList
// _originalScopes: originalScopes,
} = cast2(map);
const index = put(sources, source);
if (index === sourcesContent.length) sourcesContent[index] = null;
if (ignore) put(ignoreList, index);
else remove(ignoreList, index);
}
function toDecodedMap(map) {
const {
_mappings: mappings,
_sources: sources,
_sourcesContent: sourcesContent,
_names: names,
_ignoreList: ignoreList
// _originalScopes: originalScopes,
// _generatedRanges: generatedRanges,
} = cast2(map);
removeEmptyFinalLines(mappings);
return {
version: 3,
file: map.file || void 0,
names: names.array,
sourceRoot: map.sourceRoot || void 0,
sources: sources.array,
sourcesContent,
mappings,
// originalScopes,
// generatedRanges,
ignoreList: ignoreList.array
};
}
function toEncodedMap(map) {
const decoded = toDecodedMap(map);
return Object.assign({}, decoded, {
// originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)),
// generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]),
mappings: (0, import_sourcemap_codec.encode)(decoded.mappings)
});
}
function fromMap(input) {
const map = new import_trace_mapping.TraceMap(input);
const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });
putAll(cast2(gen)._names, map.names);
putAll(cast2(gen)._sources, map.sources);
cast2(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);
cast2(gen)._mappings = (0, import_trace_mapping.decodedMappings)(map);
if (map.ignoreList) putAll(cast2(gen)._ignoreList, map.ignoreList);
return gen;
}
function allMappings(map) {
const out = [];
const { _mappings: mappings, _sources: sources, _names: names } = cast2(map);
for (let i = 0; i < mappings.length; i++) {
const line = mappings[i];
for (let j = 0; j < line.length; j++) {
const seg = line[j];
const generated = { line: i + 1, column: seg[COLUMN] };
let source = void 0;
let original = void 0;
let name = void 0;
if (seg.length !== 1) {
source = sources.array[seg[SOURCES_INDEX]];
original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };
if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];
}
out.push({ generated, source, original, name });
}
}
return out;
}
function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
const {
_mappings: mappings,
_sources: sources,
_sourcesContent: sourcesContent,
_names: names
// _originalScopes: originalScopes,
} = cast2(map);
const line = getIndex(mappings, genLine);
const index = getColumnIndex(line, genColumn);
if (!source) {
if (skipable && skipSourceless(line, index)) return;
return insert(line, index, [genColumn]);
}
assert(sourceLine);
assert(sourceColumn);
const sourcesIndex = put(sources, source);
const namesIndex = name ? put(names, name) : NO_NAME;
if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
return;
}
return insert(
line,
index,
name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]
);
}
function assert(_val) {
}
function getIndex(arr, index) {
for (let i = arr.length; i <= index; i++) {
arr[i] = [];
}
return arr[index];
}
function getColumnIndex(line, genColumn) {
let index = line.length;
for (let i = index - 1; i >= 0; index = i--) {
const current = line[i];
if (genColumn >= current[COLUMN]) break;
}
return index;
}
function insert(array, index, value2) {
for (let i = array.length; i > index; i--) {
array[i] = array[i - 1];
}
array[index] = value2;
}
function removeEmptyFinalLines(mappings) {
const { length } = mappings;
let len = length;
for (let i = len - 1; i >= 0; len = i, i--) {
if (mappings[i].length > 0) break;
}
if (len < length) mappings.length = len;
}
function putAll(setarr, array) {
for (let i = 0; i < array.length; i++) put(setarr, array[i]);
}
function skipSourceless(line, index) {
if (index === 0) return true;
const prev = line[index - 1];
return prev.length === 1;
}
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
if (index === 0) return false;
const prev = line[index - 1];
if (prev.length === 1) return false;
return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
}
function addMappingInternal(skipable, map, mapping) {
const { generated, source, original, name, content } = mapping;
if (!source) {
return addSegmentInternal(
skipable,
map,
generated.line - 1,
generated.column,
null,
null,
null,
null,
null
);
}
assert(original);
return addSegmentInternal(
skipable,
map,
generated.line - 1,
generated.column,
source,
original.line - 1,
original.column,
name,
content
);
}
}));
}
});
// node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.umd.js
var require_remapping_umd = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.umd.js"(exports, module) {
"use strict";
(function(global, factory) {
if (typeof exports === "object" && typeof module !== "undefined") {
factory(module, require_gen_mapping_umd(), require_trace_mapping_umd());
module.exports = def(module);
} else if (typeof define === "function" && define.amd) {
define(["module", "@jridgewell/gen-mapping", "@jridgewell/trace-mapping"], function(mod) {
factory.apply(this, arguments);
mod.exports = def(mod);
});
} else {
const mod = { exports: {} };
factory(mod, global.genMapping, global.traceMapping);
global = typeof globalThis !== "undefined" ? globalThis : global || self;
global.remapping = def(mod);
}
function def(m) {
return "default" in m.exports ? m.exports.default : m.exports;
}
})(exports, (function(module2, require_genMapping, require_traceMapping) {
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS2 = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export2 = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS2 = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var require_trace_mapping = __commonJS2({
"umd:@jridgewell/trace-mapping"(exports2, module22) {
module22.exports = require_traceMapping;
}
});
var require_gen_mapping = __commonJS2({
"umd:@jridgewell/gen-mapping"(exports2, module22) {
module22.exports = require_genMapping;
}
});
var remapping_exports = {};
__export2(remapping_exports, {
default: () => remapping
});
module2.exports = __toCommonJS2(remapping_exports);
var import_trace_mapping2 = __toESM2(require_trace_mapping());
var import_gen_mapping = __toESM2(require_gen_mapping());
var import_trace_mapping = __toESM2(require_trace_mapping());
var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
var EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name, content, ignore) {
return { source, line, column, name, content, ignore };
}
function Source(map, sources, source, content, ignore) {
return {
map,
sources,
source,
content,
ignore
};
}
function MapSource(map, sources) {
return Source(map, sources, "", null, false);
}
function OriginalSource(source, content, ignore) {
return Source(null, EMPTY_SOURCES, source, content, ignore);
}
function traceMappings(tree) {
const gen = new import_gen_mapping.GenMapping({ file: tree.map.file });
const { sources: rootSources, map } = tree;
const rootNames = map.names;
const rootMappings = (0, import_trace_mapping.decodedMappings)(map);
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
const genCol = segment[0];
let traced = SOURCELESS_MAPPING;
if (segment.length !== 1) {
const source2 = rootSources[segment[1]];
traced = originalPositionFor(
source2,
segment[2],
segment[3],
segment.length === 5 ? rootNames[segment[4]] : ""
);
if (traced == null) continue;
}
const { column, line, name, content, source, ignore } = traced;
(0, import_gen_mapping.maybeAddSegment)(gen, i, genCol, source, line, column, name);
if (source && content != null) (0, import_gen_mapping.setSourceContent)(gen, source, content);
if (ignore) (0, import_gen_mapping.setIgnore)(gen, source, true);
}
}
return gen;
}
function originalPositionFor(source, line, column, name) {
if (!source.map) {
return SegmentObject(source.source, line, column, name, source.content, source.ignore);
}
const segment = (0, import_trace_mapping.traceSegment)(source.map, line, column);
if (segment == null) return null;
if (segment.length === 1) return SOURCELESS_MAPPING;
return originalPositionFor(
source.sources[segment[1]],
segment[2],
segment[3],
segment.length === 5 ? source.map.names[segment[4]] : name
);
}
function asArray(value2) {
if (Array.isArray(value2)) return value2;
return [value2];
}
function buildSourceMapTree(input, loader) {
const maps = asArray(input).map((m) => new import_trace_mapping2.TraceMap(m, ""));
const map = maps.pop();
for (let i = 0; i < maps.length; i++) {
if (maps[i].sources.length > 1) {
throw new Error(
`Transformation map ${i} must have exactly one source file.
Did you specify these with the most recent transformation maps first?`
);
}
}
let tree = build(map, loader, "", 0);
for (let i = maps.length - 1; i >= 0; i--) {
tree = MapSource(maps[i], [tree]);
}
return tree;
}
function build(map, loader, importer, importerDepth) {
const { resolvedSources, sourcesContent, ignoreList } = map;
const depth = importerDepth + 1;
const children = resolvedSources.map((sourceFile, i) => {
const ctx = {
importer,
depth,
source: sourceFile || "",
content: void 0,
ignore: void 0
};
const sourceMap = loader(ctx.source, ctx);
const { source, content, ignore } = ctx;
if (sourceMap) return build(new import_trace_mapping2.TraceMap(sourceMap, source), loader, source, depth);
const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null;
const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false;
return OriginalSource(source, sourceContent, ignored);
});
return MapSource(map, children);
}
var import_gen_mapping2 = __toESM2(require_gen_mapping());
var SourceMap = class {
constructor(map, options) {
const out = options.decodedMappings ? (0, import_gen_mapping2.toDecodedMap)(map) : (0, import_gen_mapping2.toEncodedMap)(map);
this.version = out.version;
this.file = out.file;
this.mappings = out.mappings;
this.names = out.names;
this.ignoreList = out.ignoreList;
this.sourceRoot = out.sourceRoot;
this.sources = out.sources;
if (!options.excludeContent) {
this.sourcesContent = out.sourcesContent;
}
}
toString() {
return JSON.stringify(this);
}
};
function remapping(input, loader, options) {
const opts = typeof options === "object" ? options : { excludeContent: !!options, decodedMappings: false };
const tree = buildSourceMapTree(input, loader);
return new SourceMap(traceMappings(tree), opts);
}
}));
}
});
// node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.cjs.js
var require_magic_string_cjs = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.cjs.js"(exports, module) {
"use strict";
var sourcemapCodec = require_sourcemap_codec_umd();
var BitSet = class _BitSet {
constructor(arg) {
this.bits = arg instanceof _BitSet ? arg.bits.slice() : [];
}
add(n2) {
this.bits[n2 >> 5] |= 1 << (n2 & 31);
}
has(n2) {
return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
}
};
var Chunk = class _Chunk {
constructor(start, end, content) {
this.start = start;
this.end = end;
this.original = content;
this.intro = "";
this.outro = "";
this.content = content;
this.storeName = false;
this.edited = false;
{
this.previous = null;
this.next = null;
}
}
appendLeft(content) {
this.outro += content;
}
appendRight(content) {
this.intro = this.intro + content;
}
clone() {
const chunk = new _Chunk(this.start, this.end, this.original);
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
}
contains(index) {
return this.start < index && index < this.end;
}
eachNext(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.next;
}
}
eachPrevious(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.previous;
}
}
edit(content, storeName, contentOnly) {
this.content = content;
if (!contentOnly) {
this.intro = "";
this.outro = "";
}
this.storeName = storeName;
this.edited = true;
return this;
}
prependLeft(content) {
this.outro = content + this.outro;
}
prependRight(content) {
this.intro = content + this.intro;
}
reset() {
this.intro = "";
this.outro = "";
if (this.edited) {
this.content = this.original;
this.storeName = false;
this.edited = false;
}
}
split(index) {
const sliceIndex = index - this.start;
const originalBefore = this.original.slice(0, sliceIndex);
const originalAfter = this.original.slice(sliceIndex);
this.original = originalBefore;
const newChunk = new _Chunk(index, this.end, originalAfter);
newChunk.outro = this.outro;
this.outro = "";
this.end = index;
if (this.edited) {
newChunk.edit("", false);
this.content = "";
} else {
this.content = originalBefore;
}
newChunk.next = this.next;
if (newChunk.next) newChunk.next.previous = newChunk;
newChunk.previous = this;
this.next = newChunk;
return newChunk;
}
toString() {
return this.intro + this.content + this.outro;
}
trimEnd(rx) {
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.start + trimmed.length).edit("", void 0, true);
if (this.edited) {
this.edit(trimmed, this.storeName, true);
}
}
return true;
} else {
this.edit("", void 0, true);
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
}
}
trimStart(rx) {
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
const newChunk = this.split(this.end - trimmed.length);
if (this.edited) {
newChunk.edit(trimmed, this.storeName, true);
}
this.edit("", void 0, true);
}
return true;
} else {
this.edit("", void 0, true);
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
}
}
};
function getBtoa() {
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
} else if (typeof Buffer === "function") {
return (str) => Buffer.from(str, "utf-8").toString("base64");
} else {
return () => {
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
};
}
}
var btoa2 = /* @__PURE__ */ getBtoa();
var SourceMap = class {
constructor(properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = sourcemapCodec.encode(properties.mappings);
if (typeof properties.x_google_ignoreList !== "undefined") {
this.x_google_ignoreList = properties.x_google_ignoreList;
}
if (typeof properties.debugId !== "undefined") {
this.debugId = properties.debugId;
}
}
toString() {
return JSON.stringify(this);
}
toUrl() {
return "data:application/json;charset=utf-8;base64," + btoa2(this.toString());
}
};
function guessIndent(code) {
const lines = code.split("\n");
const tabbed = lines.filter((line) => /^\t+/.test(line));
const spaced = lines.filter((line) => /^ {2,}/.test(line));
if (tabbed.length === 0 && spaced.length === 0) {
return null;
}
if (tabbed.length >= spaced.length) {
return " ";
}
const min = spaced.reduce((previous, current) => {
const numSpaces = /^ +/.exec(current)[0].length;
return Math.min(numSpaces, previous);
}, Infinity);
return new Array(min + 1).join(" ");
}
function getRelativePath(from, to) {
const fromParts = from.split(/[/\\]/);
const toParts = to.split(/[/\\]/);
fromParts.pop();
while (fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
if (fromParts.length) {
let i = fromParts.length;
while (i--) fromParts[i] = "..";
}
return fromParts.concat(toParts).join("/");
}
var toString = Object.prototype.toString;
function isObject(thing) {
return toString.call(thing) === "[object Object]";
}
function getLocator(source) {
const originalLines = source.split("\n");
const lineOffsets = [];
for (let i = 0, pos = 0; i < originalLines.length; i++) {
lineOffsets.push(pos);
pos += originalLines[i].length + 1;
}
return function locate(index) {
let i = 0;
let j = lineOffsets.length;
while (i < j) {
const m = i + j >> 1;
if (index < lineOffsets[m]) {
j = m;
} else {
i = m + 1;
}
}
const line = i - 1;
const column = index - lineOffsets[line];
return { line, column };
};
}
var wordRegex = /\w/;
var Mappings = class {
constructor(hires) {
this.hires = hires;
this.generatedCodeLine = 0;
this.generatedCodeColumn = 0;
this.raw = [];
this.rawSegments = this.raw[this.generatedCodeLine] = [];
this.pending = null;
}
addEdit(sourceIndex, content, loc, nameIndex) {
if (content.length) {
const contentLengthMinusOne = content.length - 1;
let contentLineEnd = content.indexOf("\n", 0);
let previousContentLineEnd = -1;
while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (nameIndex >= 0) {
segment2.push(nameIndex);
}
this.rawSegments.push(segment2);
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
previousContentLineEnd = contentLineEnd;
contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
}
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (nameIndex >= 0) {
segment.push(nameIndex);
}
this.rawSegments.push(segment);
this.advance(content.slice(previousContentLineEnd + 1));
} else if (this.pending) {
this.rawSegments.push(this.pending);
this.advance(content);
}
this.pending = null;
}
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
let originalCharIndex = chunk.start;
let first = true;
let charInHiresBoundary = false;
while (originalCharIndex < chunk.end) {
if (original[originalCharIndex] === "\n") {
loc.line += 1;
loc.column = 0;
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
first = true;
charInHiresBoundary = false;
} else {
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (this.hires === "boundary") {
if (wordRegex.test(original[originalCharIndex])) {
if (!charInHiresBoundary) {
this.rawSegments.push(segment);
charInHiresBoundary = true;
}
} else {
this.rawSegments.push(segment);
charInHiresBoundary = false;
}
} else {
this.rawSegments.push(segment);
}
}
loc.column += 1;
this.generatedCodeColumn += 1;
first = false;
}
originalCharIndex += 1;
}
this.pending = null;
}
advance(str) {
if (!str) return;
const lines = str.split("\n");
if (lines.length > 1) {
for (let i = 0; i < lines.length - 1; i++) {
this.generatedCodeLine++;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
}
this.generatedCodeColumn = 0;
}
this.generatedCodeColumn += lines[lines.length - 1].length;
}
};
var n = "\n";
var warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
var MagicString = class _MagicString {
constructor(string, options = {}) {
const chunk = new Chunk(0, string.length, string);
Object.defineProperties(this, {
original: { writable: true, value: string },
outro: { writable: true, value: "" },
intro: { writable: true, value: "" },
firstChunk: { writable: true, value: chunk },
lastChunk: { writable: true, value: chunk },
lastSearchedChunk: { writable: true, value: chunk },
byStart: { writable: true, value: {} },
byEnd: { writable: true, value: {} },
filename: { writable: true, value: options.filename },
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
sourcemapLocations: { writable: true, value: new BitSet() },
storedNames: { writable: true, value: {} },
indentStr: { writable: true, value: void 0 },
ignoreList: { writable: true, value: options.ignoreList },
offset: { writable: true, value: options.offset || 0 }
});
this.byStart[0] = chunk;
this.byEnd[string.length] = chunk;
}
addSourcemapLocation(char) {
this.sourcemapLocations.add(char);
}
append(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.outro += content;
return this;
}
appendLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) {
chunk.appendLeft(content);
} else {
this.intro += content;
}
return this;
}
appendRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) {
chunk.appendRight(content);
} else {
this.outro += content;
}
return this;
}
clone() {
const cloned = new _MagicString(this.original, { filename: this.filename, offset: this.offset });
let originalChunk = this.firstChunk;
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while (originalChunk) {
cloned.byStart[clonedChunk.start] = clonedChunk;
cloned.byEnd[clonedChunk.end] = clonedChunk;
const nextOriginalChunk = originalChunk.next;
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if (nextClonedChunk) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if (this.indentExclusionRanges) {
cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
}
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
cloned.intro = this.intro;
cloned.outro = this.outro;
return cloned;
}
generateDecodedMap(options) {
options = options || {};
const sourceIndex = 0;
const names = Object.keys(this.storedNames);
const mappings = new Mappings(options.hires);
const locate = getLocator(this.original);
if (this.intro) {
mappings.advance(this.intro);
}
this.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length) mappings.advance(chunk.intro);
if (chunk.edited) {
mappings.addEdit(
sourceIndex,
chunk.content,
loc,
chunk.storeName ? names.indexOf(chunk.original) : -1
);
} else {
mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
}
if (chunk.outro.length) mappings.advance(chunk.outro);
});
if (this.outro) {
mappings.advance(this.outro);
}
return {
file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
sources: [
options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
],
sourcesContent: options.includeContent ? [this.original] : void 0,
names,
mappings: mappings.raw,
x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
};
}
generateMap(options) {
return new SourceMap(this.generateDecodedMap(options));
}
_ensureindentStr() {
if (this.indentStr === void 0) {
this.indentStr = guessIndent(this.original);
}
}
_getRawIndentString() {
this._ensureindentStr();
return this.indentStr;
}
getIndentString() {
this._ensureindentStr();
return this.indentStr === null ? " " : this.indentStr;
}
indent(indentStr, options) {
const pattern = /^[^\r\n]/gm;
if (isObject(indentStr)) {
options = indentStr;
indentStr = void 0;
}
if (indentStr === void 0) {
this._ensureindentStr();
indentStr = this.indentStr || " ";
}
if (indentStr === "") return this;
options = options || {};
const isExcluded = {};
if (options.exclude) {
const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
exclusions.forEach((exclusion) => {
for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
isExcluded[i] = true;
}
});
}
let shouldIndentNextCharacter = options.indentStart !== false;
const replacer = (match) => {
if (shouldIndentNextCharacter) return `${indentStr}${match}`;
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace(pattern, replacer);
let charIndex = 0;
let chunk = this.firstChunk;
while (chunk) {
const end = chunk.end;
if (chunk.edited) {
if (!isExcluded[charIndex]) {
chunk.content = chunk.content.replace(pattern, replacer);
if (chunk.content.length) {
shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
}
}
} else {
charIndex = chunk.start;
while (charIndex < end) {
if (!isExcluded[charIndex]) {
const char = this.original[charIndex];
if (char === "\n") {
shouldIndentNextCharacter = true;
} else if (char !== "\r" && shouldIndentNextCharacter) {
shouldIndentNextCharacter = false;
if (charIndex === chunk.start) {
chunk.prependRight(indentStr);
} else {
this._splitChunk(chunk, charIndex);
chunk = chunk.next;
chunk.prependRight(indentStr);
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace(pattern, replacer);
return this;
}
insert() {
throw new Error(
"magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
);
}
insertLeft(index, content) {
if (!warned.insertLeft) {
console.warn(
"magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
);
warned.insertLeft = true;
}
return this.appendLeft(index, content);
}
insertRight(index, content) {
if (!warned.insertRight) {
console.warn(
"magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
);
warned.insertRight = true;
}
return this.prependRight(index, content);
}
move(start, end, index) {
start = start + this.offset;
end = end + this.offset;
index = index + this.offset;
if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
this._split(start);
this._split(end);
this._split(index);
const first = this.byStart[start];
const last = this.byEnd[end];
const oldLeft = first.previous;
const oldRight = last.next;
const newRight = this.byStart[index];
if (!newRight && last === this.lastChunk) return this;
const newLeft = newRight ? newRight.previous : this.lastChunk;
if (oldLeft) oldLeft.next = oldRight;
if (oldRight) oldRight.previous = oldLeft;
if (newLeft) newLeft.next = first;
if (newRight) newRight.previous = last;
if (!first.previous) this.firstChunk = last.next;
if (!last.next) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight || null;
if (!newLeft) this.firstChunk = first;
if (!newRight) this.lastChunk = last;
return this;
}
overwrite(start, end, content, options) {
options = options || {};
return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
}
update(start, end, content, options) {
start = start + this.offset;
end = end + this.offset;
if (typeof content !== "string") throw new TypeError("replacement content must be a string");
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (end > this.original.length) throw new Error("end is out of bounds");
if (start === end)
throw new Error(
"Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead"
);
this._split(start);
this._split(end);
if (options === true) {
if (!warned.storeName) {
console.warn(
"The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
);
warned.storeName = true;
}
options = { storeName: true };
}
const storeName = options !== void 0 ? options.storeName : false;
const overwrite = options !== void 0 ? options.overwrite : false;
if (storeName) {
const original = this.original.slice(start, end);
Object.defineProperty(this.storedNames, original, {
writable: true,
value: true,
enumerable: true
});
}
const first = this.byStart[start];
const last = this.byEnd[end];
if (first) {
let chunk = first;
while (chunk !== last) {
if (chunk.next !== this.byStart[chunk.end]) {
throw new Error("Cannot overwrite across a split point");
}
chunk = chunk.next;
chunk.edit("", false);
}
first.edit(content, storeName, !overwrite);
} else {
const newChunk = new Chunk(start, end, "").edit(content, storeName);
last.next = newChunk;
newChunk.previous = last;
}
return this;
}
prepend(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.intro = content + this.intro;
return this;
}
prependLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) {
chunk.prependLeft(content);
} else {
this.intro = content + this.intro;
}
return this;
}
prependRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) {
chunk.prependRight(content);
} else {
this.outro = content + this.outro;
}
return this;
}
remove(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.intro = "";
chunk.outro = "";
chunk.edit("");
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
reset(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.reset();
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
lastChar() {
if (this.outro.length) return this.outro[this.outro.length - 1];
let chunk = this.lastChunk;
do {
if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
if (chunk.content.length) return chunk.content[chunk.content.length - 1];
if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
} while (chunk = chunk.previous);
if (this.intro.length) return this.intro[this.intro.length - 1];
return "";
}
lastLine() {
let lineIndex = this.outro.lastIndexOf(n);
if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
let lineStr = this.outro;
let chunk = this.lastChunk;
do {
if (chunk.outro.length > 0) {
lineIndex = chunk.outro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.outro + lineStr;
}
if (chunk.content.length > 0) {
lineIndex = chunk.content.lastIndexOf(n);
if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
lineStr = chunk.content + lineStr;
}
if (chunk.intro.length > 0) {
lineIndex = chunk.intro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.intro + lineStr;
}
} while (chunk = chunk.previous);
lineIndex = this.intro.lastIndexOf(n);
if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
return this.intro + lineStr;
}
slice(start = 0, end = this.original.length - this.offset) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
let result = "";
let chunk = this.firstChunk;
while (chunk && (chunk.start > start || chunk.end <= start)) {
if (chunk.start < end && chunk.end >= end) {
return result;
}
chunk = chunk.next;
}
if (chunk && chunk.edited && chunk.start !== start)
throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
const startChunk = chunk;
while (chunk) {
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
result += chunk.intro;
}
const containsEnd = chunk.start < end && chunk.end >= end;
if (containsEnd && chunk.edited && chunk.end !== end)
throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice(sliceStart, sliceEnd);
if (chunk.outro && (!containsEnd || chunk.end === end)) {
result += chunk.outro;
}
if (containsEnd) {
break;
}
chunk = chunk.next;
}
return result;
}
// TODO deprecate this? not really very useful
snip(start, end) {
const clone = this.clone();
clone.remove(0, start);
clone.remove(end, clone.original.length);
return clone;
}
_split(index) {
if (this.byStart[index] || this.byEnd[index]) return;
let chunk = this.lastSearchedChunk;
let previousChunk = chunk;
const searchForward = index > chunk.end;
while (chunk) {
if (chunk.contains(index)) return this._splitChunk(chunk, index);
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
if (chunk === previousChunk) return;
previousChunk = chunk;
}
}
_splitChunk(chunk, index) {
if (chunk.edited && chunk.content.length) {
const loc = getLocator(this.original)(index);
throw new Error(
`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`
);
}
const newChunk = chunk.split(index);
this.byEnd[index] = chunk;
this.byStart[index] = newChunk;
this.byEnd[newChunk.end] = newChunk;
if (chunk === this.lastChunk) this.lastChunk = newChunk;
this.lastSearchedChunk = chunk;
return true;
}
toString() {
let str = this.intro;
let chunk = this.firstChunk;
while (chunk) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
}
isEmpty() {
let chunk = this.firstChunk;
do {
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
return false;
} while (chunk = chunk.next);
return true;
}
length() {
let chunk = this.firstChunk;
let length = 0;
do {
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
} while (chunk = chunk.next);
return length;
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimEndAborted(charType) {
const rx = new RegExp((charType || "\\s") + "+$");
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
let chunk = this.lastChunk;
do {
const end = chunk.end;
const aborted = chunk.trimEnd(rx);
if (chunk.end !== end) {
if (this.lastChunk === chunk) {
this.lastChunk = chunk.next;
}
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.previous;
} while (chunk);
return false;
}
trimEnd(charType) {
this.trimEndAborted(charType);
return this;
}
trimStartAborted(charType) {
const rx = new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
let chunk = this.firstChunk;
do {
const end = chunk.end;
const aborted = chunk.trimStart(rx);
if (chunk.end !== end) {
if (chunk === this.lastChunk) this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.next;
} while (chunk);
return false;
}
trimStart(charType) {
this.trimStartAborted(charType);
return this;
}
hasChanged() {
return this.original !== this.toString();
}
_replaceRegexp(searchValue, replacement) {
function getReplacement(match, str) {
if (typeof replacement === "string") {
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
if (i === "$") return "$";
if (i === "&") return match[0];
const num = +i;
if (num < match.length) return match[+i];
return `$${i}`;
});
} else {
return replacement(...match, match.index, str, match.groups);
}
}
function matchAll(re, str) {
let match;
const matches = [];
while (match = re.exec(str)) {
matches.push(match);
}
return matches;
}
if (searchValue.global) {
const matches = matchAll(searchValue, this.original);
matches.forEach((match) => {
if (match.index != null) {
const replacement2 = getReplacement(match, this.original);
if (replacement2 !== match[0]) {
this.overwrite(match.index, match.index + match[0].length, replacement2);
}
}
});
} else {
const match = this.original.match(searchValue);
if (match && match.index != null) {
const replacement2 = getReplacement(match, this.original);
if (replacement2 !== match[0]) {
this.overwrite(match.index, match.index + match[0].length, replacement2);
}
}
}
return this;
}
_replaceString(string, replacement) {
const { original } = this;
const index = original.indexOf(string);
if (index !== -1) {
if (typeof replacement === "function") {
replacement = replacement(string, index, original);
}
if (string !== replacement) {
this.overwrite(index, index + string.length, replacement);
}
}
return this;
}
replace(searchValue, replacement) {
if (typeof searchValue === "string") {
return this._replaceString(searchValue, replacement);
}
return this._replaceRegexp(searchValue, replacement);
}
_replaceAllString(string, replacement) {
const { original } = this;
const stringLength = string.length;
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
const previous = original.slice(index, index + stringLength);
let _replacement = replacement;
if (typeof replacement === "function") {
_replacement = replacement(previous, index, original);
}
if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
}
return this;
}
replaceAll(searchValue, replacement) {
if (typeof searchValue === "string") {
return this._replaceAllString(searchValue, replacement);
}
if (!searchValue.global) {
throw new TypeError(
"MagicString.prototype.replaceAll called with a non-global RegExp argument"
);
}
return this._replaceRegexp(searchValue, replacement);
}
};
var hasOwnProp = Object.prototype.hasOwnProperty;
var Bundle = class _Bundle {
constructor(options = {}) {
this.intro = options.intro || "";
this.separator = options.separator !== void 0 ? options.separator : "\n";
this.sources = [];
this.uniqueSources = [];
this.uniqueSourceIndexByFilename = {};
}
addSource(source) {
if (source instanceof MagicString) {
return this.addSource({
content: source,
filename: source.filename,
separator: this.separator
});
}
if (!isObject(source) || !source.content) {
throw new Error(
"bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`"
);
}
["filename", "ignoreList", "indentExclusionRanges", "separator"].forEach((option) => {
if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
});
if (source.separator === void 0) {
source.separator = this.separator;
}
if (source.filename) {
if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
this.uniqueSources.push({ filename: source.filename, content: source.content.original });
} else {
const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
if (source.content.original !== uniqueSource.content) {
throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
}
}
}
this.sources.push(source);
return this;
}
append(str, options) {
this.addSource({
content: new MagicString(str),
separator: options && options.separator || ""
});
return this;
}
clone() {
const bundle = new _Bundle({
intro: this.intro,
separator: this.separator
});
this.sources.forEach((source) => {
bundle.addSource({
filename: source.filename,
content: source.content.clone(),
separator: source.separator
});
});
return bundle;
}
generateDecodedMap(options = {}) {
const names = [];
let x_google_ignoreList = void 0;
this.sources.forEach((source) => {
Object.keys(source.content.storedNames).forEach((name) => {
if (!~names.indexOf(name)) names.push(name);
});
});
const mappings = new Mappings(options.hires);
if (this.intro) {
mappings.advance(this.intro);
}
this.sources.forEach((source, i) => {
if (i > 0) {
mappings.advance(this.separator);
}
const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
const magicString = source.content;
const locate = getLocator(magicString.original);
if (magicString.intro) {
mappings.advance(magicString.intro);
}
magicString.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length) mappings.advance(chunk.intro);
if (source.filename) {
if (chunk.edited) {
mappings.addEdit(
sourceIndex,
chunk.content,
loc,
chunk.storeName ? names.indexOf(chunk.original) : -1
);
} else {
mappings.addUneditedChunk(
sourceIndex,
chunk,
magicString.original,
loc,
magicString.sourcemapLocations
);
}
} else {
mappings.advance(chunk.content);
}
if (chunk.outro.length) mappings.advance(chunk.outro);
});
if (magicString.outro) {
mappings.advance(magicString.outro);
}
if (source.ignoreList && sourceIndex !== -1) {
if (x_google_ignoreList === void 0) {
x_google_ignoreList = [];
}
x_google_ignoreList.push(sourceIndex);
}
});
return {
file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
sources: this.uniqueSources.map((source) => {
return options.file ? getRelativePath(options.file, source.filename) : source.filename;
}),
sourcesContent: this.uniqueSources.map((source) => {
return options.includeContent ? source.content : null;
}),
names,
mappings: mappings.raw,
x_google_ignoreList
};
}
generateMap(options) {
return new SourceMap(this.generateDecodedMap(options));
}
getIndentString() {
const indentStringCounts = {};
this.sources.forEach((source) => {
const indentStr = source.content._getRawIndentString();
if (indentStr === null) return;
if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
indentStringCounts[indentStr] += 1;
});
return Object.keys(indentStringCounts).sort((a, b) => {
return indentStringCounts[a] - indentStringCounts[b];
})[0] || " ";
}
indent(indentStr) {
if (!arguments.length) {
indentStr = this.getIndentString();
}
if (indentStr === "") return this;
let trailingNewline = !this.intro || this.intro.slice(-1) === "\n";
this.sources.forEach((source, i) => {
const separator = source.separator !== void 0 ? source.separator : this.separator;
const indentStart = trailingNewline || i > 0 && /\r?\n$/.test(separator);
source.content.indent(indentStr, {
exclude: source.indentExclusionRanges,
indentStart
//: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
});
trailingNewline = source.content.lastChar() === "\n";
});
if (this.intro) {
this.intro = indentStr + this.intro.replace(/^[^\n]/gm, (match, index) => {
return index > 0 ? indentStr + match : match;
});
}
return this;
}
prepend(str) {
this.intro = str + this.intro;
return this;
}
toString() {
const body = this.sources.map((source, i) => {
const separator = source.separator !== void 0 ? source.separator : this.separator;
const str = (i > 0 ? separator : "") + source.content.toString();
return str;
}).join("");
return this.intro + body;
}
isEmpty() {
if (this.intro.length && this.intro.trim()) return false;
if (this.sources.some((source) => !source.content.isEmpty())) return false;
return true;
}
length() {
return this.sources.reduce(
(length, source) => length + source.content.length(),
this.intro.length
);
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimStart(charType) {
const rx = new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (!this.intro) {
let source;
let i = 0;
do {
source = this.sources[i++];
if (!source) {
break;
}
} while (!source.content.trimStartAborted(charType));
}
return this;
}
trimEnd(charType) {
const rx = new RegExp((charType || "\\s") + "+$");
let source;
let i = this.sources.length - 1;
do {
source = this.sources[i--];
if (!source) {
this.intro = this.intro.replace(rx, "");
break;
}
} while (!source.content.trimEndAborted(charType));
return this;
}
};
MagicString.Bundle = Bundle;
MagicString.SourceMap = SourceMap;
MagicString.default = MagicString;
module.exports = MagicString;
}
});
// node_modules/.pnpm/convert-source-map@2.0.0/node_modules/convert-source-map/index.js
var require_convert_source_map = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/convert-source-map@2.0.0/node_modules/convert-source-map/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "commentRegex", {
get: function getCommentRegex() {
return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
}
});
Object.defineProperty(exports, "mapFileCommentRegex", {
get: function getMapFileCommentRegex() {
return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
}
});
var decodeBase64;
if (typeof Buffer !== "undefined") {
if (typeof Buffer.from === "function") {
decodeBase64 = decodeBase64WithBufferFrom;
} else {
decodeBase64 = decodeBase64WithNewBuffer;
}
} else {
decodeBase64 = decodeBase64WithAtob;
}
function decodeBase64WithBufferFrom(base64) {
return Buffer.from(base64, "base64").toString();
}
function decodeBase64WithNewBuffer(base64) {
if (typeof value === "number") {
throw new TypeError("The value to decode must not be of type number.");
}
return new Buffer(base64, "base64").toString();
}
function decodeBase64WithAtob(base64) {
return decodeURIComponent(escape(atob(base64)));
}
function stripComment(sm) {
return sm.split(",").pop();
}
function readFromFileMap(sm, read) {
var r = exports.mapFileCommentRegex.exec(sm);
var filename = r[1] || r[2];
try {
var sm = read(filename);
if (sm != null && typeof sm.catch === "function") {
return sm.catch(throwError);
} else {
return sm;
}
} catch (e) {
throwError(e);
}
function throwError(e) {
throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e.stack);
}
}
function Converter(sm, opts) {
opts = opts || {};
if (opts.hasComment) {
sm = stripComment(sm);
}
if (opts.encoding === "base64") {
sm = decodeBase64(sm);
} else if (opts.encoding === "uri") {
sm = decodeURIComponent(sm);
}
if (opts.isJSON || opts.encoding) {
sm = JSON.parse(sm);
}
this.sourcemap = sm;
}
Converter.prototype.toJSON = function(space) {
return JSON.stringify(this.sourcemap, null, space);
};
if (typeof Buffer !== "undefined") {
if (typeof Buffer.from === "function") {
Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
} else {
Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
}
} else {
Converter.prototype.toBase64 = encodeBase64WithBtoa;
}
function encodeBase64WithBufferFrom() {
var json2 = this.toJSON();
return Buffer.from(json2, "utf8").toString("base64");
}
function encodeBase64WithNewBuffer() {
var json2 = this.toJSON();
if (typeof json2 === "number") {
throw new TypeError("The json to encode must not be of type number.");
}
return new Buffer(json2, "utf8").toString("base64");
}
function encodeBase64WithBtoa() {
var json2 = this.toJSON();
return btoa(unescape(encodeURIComponent(json2)));
}
Converter.prototype.toURI = function() {
var json2 = this.toJSON();
return encodeURIComponent(json2);
};
Converter.prototype.toComment = function(options) {
var encoding, content, data;
if (options != null && options.encoding === "uri") {
encoding = "";
content = this.toURI();
} else {
encoding = ";base64";
content = this.toBase64();
}
data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content;
return options != null && options.multiline ? "/*# " + data + " */" : "//# " + data;
};
Converter.prototype.toObject = function() {
return JSON.parse(this.toJSON());
};
Converter.prototype.addProperty = function(key, value2) {
if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
return this.setProperty(key, value2);
};
Converter.prototype.setProperty = function(key, value2) {
this.sourcemap[key] = value2;
return this;
};
Converter.prototype.getProperty = function(key) {
return this.sourcemap[key];
};
exports.fromObject = function(obj) {
return new Converter(obj);
};
exports.fromJSON = function(json2) {
return new Converter(json2, { isJSON: true });
};
exports.fromURI = function(uri) {
return new Converter(uri, { encoding: "uri" });
};
exports.fromBase64 = function(base64) {
return new Converter(base64, { encoding: "base64" });
};
exports.fromComment = function(comment) {
var m, encoding;
comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, "");
m = exports.commentRegex.exec(comment);
encoding = m && m[4] || "uri";
return new Converter(comment, { encoding, hasComment: true });
};
function makeConverter(sm) {
return new Converter(sm, { isJSON: true });
}
exports.fromMapFileComment = function(comment, read) {
if (typeof read === "string") {
throw new Error(
"String directory paths are no longer supported with `fromMapFileComment`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"
);
}
var sm = readFromFileMap(comment, read);
if (sm != null && typeof sm.then === "function") {
return sm.then(makeConverter);
} else {
return makeConverter(sm);
}
};
exports.fromSource = function(content) {
var m = content.match(exports.commentRegex);
return m ? exports.fromComment(m.pop()) : null;
};
exports.fromMapFileSource = function(content, read) {
if (typeof read === "string") {
throw new Error(
"String directory paths are no longer supported with `fromMapFileSource`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"
);
}
var m = content.match(exports.mapFileCommentRegex);
return m ? exports.fromMapFileComment(m.pop(), read) : null;
};
exports.removeComments = function(src) {
return src.replace(exports.commentRegex, "");
};
exports.removeMapFileComments = function(src) {
return src.replace(exports.mapFileCommentRegex, "");
};
exports.generateMapFileComment = function(file, options) {
var data = "sourceMappingURL=" + file;
return options && options.multiline ? "/*# " + data + " */" : "//# " + data;
};
}
});
// node_modules/.pnpm/@babel+code-frame@8.0.6/node_modules/@babel/code-frame/lib/common-shared.js
function getMarkerLines(loc, source, opts, startLineBaseZero) {
const startLoc = {
column: null,
line: -1,
...loc.start
};
const endLoc = {
...startLoc,
...loc.end
};
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line - startLineBaseZero;
const startColumn = startLoc.column;
const endLine = endLoc.line - startLineBaseZero;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (startColumn == null) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn != null) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
const safeStart = _nullishCoalesce(startColumn, () => ( 0));
const safeEnd = _nullishCoalesce(endColumn, () => ( safeStart));
markerLines[startLine] = [safeStart, safeEnd - safeStart];
}
}
return {
start,
end,
markerLines
};
}
function _codeFrameColumns(rawLines, loc, opts = {}, colorOpts) {
const {
defs: defs2,
highlight: highlight2
} = colorOpts || {
defs: {
gutter: String,
marker: String,
message: String,
reset: String
},
highlight: String
};
const startLineBaseZero = (opts.startLine || 1) - 1;
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts, startLineBaseZero);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end + startLineBaseZero).length;
const highlightedLines = highlight2(rawLines);
let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number + startLineBaseZero}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} |`;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, hasMarker[0]).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", defs2.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs2.marker("^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + defs2.message(opts.message);
}
}
return [defs2.marker(">"), defs2.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else {
return ` ${defs2.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}
${frame}`;
}
return defs2.reset(frame);
}
var NEWLINE;
var init_common_shared = _chunkYQNCOY6Vjs.__esm.call(void 0, {
"node_modules/.pnpm/@babel+code-frame@8.0.6/node_modules/@babel/code-frame/lib/common-shared.js"() {
"use strict";
NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
}
});
// node_modules/.pnpm/js-tokens@10.0.0/node_modules/js-tokens/index.js
var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace, jsTokens, js_tokens_default;
var init_js_tokens = _chunkYQNCOY6Vjs.__esm.call(void 0, {
"node_modules/.pnpm/js-tokens@10.0.0/node_modules/js-tokens/index.js"() {
"use strict";
RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
SingleLineComment = /\/\/.*/y;
HashbangComment = /^#!.*/;
JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
JSXText = /[^<>{}]+/y;
TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
Newline = RegExp(LineTerminatorSequence.source);
jsTokens = function* (input, { jsx = false } = {}) {
var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
({ length } = input);
lastIndex = 0;
lastSignificantToken = "";
stack = [
{ tag: "JS" }
];
braces = [];
parenNesting = 0;
postfixIncDec = false;
if (match = HashbangComment.exec(input)) {
yield {
type: "HashbangComment",
value: match[0]
};
lastIndex = match[0].length;
}
while (lastIndex < length) {
mode = stack[stack.length - 1];
switch (mode.tag) {
case "JS":
case "JSNonExpressionParen":
case "InterpolationInTemplate":
case "InterpolationInJSX":
if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
RegularExpressionLiteral.lastIndex = lastIndex;
if (match = RegularExpressionLiteral.exec(input)) {
lastIndex = RegularExpressionLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield {
type: "RegularExpressionLiteral",
value: match[0],
closed: match[1] !== void 0 && match[1] !== "\\"
};
continue;
}
}
Punctuator.lastIndex = lastIndex;
if (match = Punctuator.exec(input)) {
punctuator = match[0];
nextLastIndex = Punctuator.lastIndex;
nextLastSignificantToken = punctuator;
switch (punctuator) {
case "(":
if (lastSignificantToken === "?NonExpressionParenKeyword") {
stack.push({
tag: "JSNonExpressionParen",
nesting: parenNesting
});
}
parenNesting++;
postfixIncDec = false;
break;
case ")":
parenNesting--;
postfixIncDec = true;
if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
stack.pop();
nextLastSignificantToken = "?NonExpressionParenEnd";
postfixIncDec = false;
}
break;
case "{":
Punctuator.lastIndex = 0;
isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
braces.push(isExpression);
postfixIncDec = false;
break;
case "}":
switch (mode.tag) {
case "InterpolationInTemplate":
if (braces.length === mode.nesting) {
Template.lastIndex = lastIndex;
match = Template.exec(input);
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
postfixIncDec = false;
yield {
type: "TemplateMiddle",
value: match[0]
};
} else {
stack.pop();
postfixIncDec = true;
yield {
type: "TemplateTail",
value: match[0],
closed: match[1] === "`"
};
}
continue;
}
break;
case "InterpolationInJSX":
if (braces.length === mode.nesting) {
stack.pop();
lastIndex += 1;
lastSignificantToken = "}";
yield {
type: "JSXPunctuator",
value: "}"
};
continue;
}
}
postfixIncDec = braces.pop();
nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
break;
case "]":
postfixIncDec = true;
break;
case "++":
case "--":
nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
break;
case "<":
if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
stack.push({ tag: "JSXTag" });
lastIndex += 1;
lastSignificantToken = "<";
yield {
type: "JSXPunctuator",
value: punctuator
};
continue;
}
postfixIncDec = false;
break;
default:
postfixIncDec = false;
}
lastIndex = nextLastIndex;
lastSignificantToken = nextLastSignificantToken;
yield {
type: "Punctuator",
value: punctuator
};
continue;
}
Identifier.lastIndex = lastIndex;
if (match = Identifier.exec(input)) {
lastIndex = Identifier.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "for":
case "if":
case "while":
case "with":
if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
nextLastSignificantToken = "?NonExpressionParenKeyword";
}
}
lastSignificantToken = nextLastSignificantToken;
postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
yield {
type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
value: match[0]
};
continue;
}
StringLiteral.lastIndex = lastIndex;
if (match = StringLiteral.exec(input)) {
lastIndex = StringLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield {
type: "StringLiteral",
value: match[0],
closed: match[2] !== void 0
};
continue;
}
NumericLiteral.lastIndex = lastIndex;
if (match = NumericLiteral.exec(input)) {
lastIndex = NumericLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield {
type: "NumericLiteral",
value: match[0]
};
continue;
}
Template.lastIndex = lastIndex;
if (match = Template.exec(input)) {
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
stack.push({
tag: "InterpolationInTemplate",
nesting: braces.length
});
postfixIncDec = false;
yield {
type: "TemplateHead",
value: match[0]
};
} else {
postfixIncDec = true;
yield {
type: "NoSubstitutionTemplate",
value: match[0],
closed: match[1] === "`"
};
}
continue;
}
break;
case "JSXTag":
case "JSXTagEnd":
JSXPunctuator.lastIndex = lastIndex;
if (match = JSXPunctuator.exec(input)) {
lastIndex = JSXPunctuator.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "<":
stack.push({ tag: "JSXTag" });
break;
case ">":
stack.pop();
if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
nextLastSignificantToken = "?JSX";
postfixIncDec = true;
} else {
stack.push({ tag: "JSXChildren" });
}
break;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
nextLastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
break;
case "/":
if (lastSignificantToken === "<") {
stack.pop();
if (stack[stack.length - 1].tag === "JSXChildren") {
stack.pop();
}
stack.push({ tag: "JSXTagEnd" });
}
}
lastSignificantToken = nextLastSignificantToken;
yield {
type: "JSXPunctuator",
value: match[0]
};
continue;
}
JSXIdentifier.lastIndex = lastIndex;
if (match = JSXIdentifier.exec(input)) {
lastIndex = JSXIdentifier.lastIndex;
lastSignificantToken = match[0];
yield {
type: "JSXIdentifier",
value: match[0]
};
continue;
}
JSXString.lastIndex = lastIndex;
if (match = JSXString.exec(input)) {
lastIndex = JSXString.lastIndex;
lastSignificantToken = match[0];
yield {
type: "JSXString",
value: match[0],
closed: match[2] !== void 0
};
continue;
}
break;
case "JSXChildren":
JSXText.lastIndex = lastIndex;
if (match = JSXText.exec(input)) {
lastIndex = JSXText.lastIndex;
lastSignificantToken = match[0];
yield {
type: "JSXText",
value: match[0]
};
continue;
}
switch (input[lastIndex]) {
case "<":
stack.push({ tag: "JSXTag" });
lastIndex++;
lastSignificantToken = "<";
yield {
type: "JSXPunctuator",
value: "<"
};
continue;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
lastIndex++;
lastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
yield {
type: "JSXPunctuator",
value: "{"
};
continue;
}
}
WhiteSpace.lastIndex = lastIndex;
if (match = WhiteSpace.exec(input)) {
lastIndex = WhiteSpace.lastIndex;
yield {
type: "WhiteSpace",
value: match[0]
};
continue;
}
LineTerminatorSequence.lastIndex = lastIndex;
if (match = LineTerminatorSequence.exec(input)) {
lastIndex = LineTerminatorSequence.lastIndex;
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
yield {
type: "LineTerminatorSequence",
value: match[0]
};
continue;
}
MultiLineComment.lastIndex = lastIndex;
if (match = MultiLineComment.exec(input)) {
lastIndex = MultiLineComment.lastIndex;
if (Newline.test(match[0])) {
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
}
yield {
type: "MultiLineComment",
value: match[0],
closed: match[1] !== void 0
};
continue;
}
SingleLineComment.lastIndex = lastIndex;
if (match = SingleLineComment.exec(input)) {
lastIndex = SingleLineComment.lastIndex;
postfixIncDec = false;
yield {
type: "SingleLineComment",
value: match[0]
};
continue;
}
firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
lastIndex += firstCodePoint.length;
lastSignificantToken = firstCodePoint;
postfixIncDec = false;
yield {
type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
value: firstCodePoint
};
}
return void 0;
};
js_tokens_default = jsTokens;
}
});
// node_modules/.pnpm/@babel+helper-validator-identifier@8.0.6/node_modules/@babel/helper-validator-identifier/lib/identifier.js
var init_identifier = _chunkYQNCOY6Vjs.__esm.call(void 0, {
"node_modules/.pnpm/@babel+helper-validator-identifier@8.0.6/node_modules/@babel/helper-validator-identifier/lib/identifier.js"() {
"use strict";
}
});
// node_modules/.pnpm/@babel+helper-validator-identifier@8.0.6/node_modules/@babel/helper-validator-identifier/lib/index.js
function isReservedWord(word, inModule) {
return inModule && word === "await" || word === "enum";
}
function isStrictReservedWord(word, inModule) {
return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
}
function isKeyword(word) {
return keywords.has(word);
}
var reservedWords2, keywords, reservedWordsStrictSet, reservedWordsStrictBindSet;
var init_lib = _chunkYQNCOY6Vjs.__esm.call(void 0, {
"node_modules/.pnpm/@babel+helper-validator-identifier@8.0.6/node_modules/@babel/helper-validator-identifier/lib/index.js"() {
"use strict";
init_identifier();
reservedWords2 = {
keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
strictBind: ["eval", "arguments"]
};
keywords = new Set(reservedWords2.keyword);
reservedWordsStrictSet = new Set(reservedWords2.strict);
reservedWordsStrictBindSet = new Set(reservedWords2.strictBind);
}
});
// node_modules/.pnpm/@babel+code-frame@8.0.6/node_modules/@babel/code-frame/lib/index.js
var lib_exports = {};
_chunkYQNCOY6Vjs.__export.call(void 0, lib_exports, {
codeFrameColumns: () => codeFrameColumns,
highlight: () => highlight
});
var _util = require('util');
function isColorSupported() {
return _util.styleText.call(void 0, "red", "-") !== "-";
}
function createFormatter(format) {
return (input) => _util.styleText.call(void 0, format, String(_nullishCoalesce(input, () => ( ""))), {
validateStream: false
});
}
function* tokenize(text) {
for (const token of js_tokens_default(text, {
jsx: true
})) {
switch (token.type) {
case "TemplateHead":
yield {
type: "string",
value: token.value.slice(0, -2)
};
yield {
type: "punctuator",
value: "${"
};
break;
case "TemplateMiddle":
yield {
type: "punctuator",
value: "}"
};
yield {
type: "string",
value: token.value.slice(1, -2)
};
yield {
type: "punctuator",
value: "${"
};
break;
case "TemplateTail":
yield {
type: "punctuator",
value: "}"
};
yield {
type: "string",
value: token.value.slice(1)
};
break;
default:
yield {
type: getTokenType(token),
value: token.value
};
}
}
}
function highlight(text) {
if (text === "") return "";
let highlighted = "";
for (const {
type,
value: value2
} of tokenize(text)) {
if (type in defs) {
highlighted += value2.split(NEWLINE2).map((str) => defs[type](str)).join("\n");
} else {
highlighted += value2;
}
}
return highlighted;
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
return _codeFrameColumns(rawLines, loc, opts, shouldHighlight ? {
defs,
highlight
} : void 0);
}
var defs, sometimesKeywords, NEWLINE2, BRACKET, getTokenType;
var init_lib2 = _chunkYQNCOY6Vjs.__esm.call(void 0, {
"node_modules/.pnpm/@babel+code-frame@8.0.6/node_modules/@babel/code-frame/lib/index.js"() {
"use strict";
init_common_shared();
init_js_tokens();
init_lib();
defs = {
keyword: createFormatter("cyan"),
capitalized: createFormatter("yellow"),
jsxIdentifier: createFormatter("yellow"),
punctuator: createFormatter("yellow"),
number: createFormatter("magenta"),
string: createFormatter("green"),
regex: createFormatter("magenta"),
comment: createFormatter("gray"),
invalid: createFormatter(["white", "bgRed", "bold"]),
gutter: createFormatter("gray"),
marker: createFormatter(["red", "bold"]),
message: createFormatter(["red", "bold"]),
reset: createFormatter("reset")
};
sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]);
NEWLINE2 = /\r\n|[\n\r\u2028\u2029]/;
BRACKET = /^[()[\]{}]$/;
getTokenType = function(token) {
if (token.type === "IdentifierName") {
const tokenValue = token.value;
if (isKeyword(tokenValue) || isStrictReservedWord(tokenValue, true) || sometimesKeywords.has(tokenValue)) {
return "keyword";
}
const firstChar = tokenValue.charCodeAt(0);
if (firstChar < 128) {
if (firstChar >= 65 && firstChar <= 90) {
return "capitalized";
}
} else {
const firstChar2 = String.fromCodePoint(tokenValue.codePointAt(0));
if (firstChar2 !== firstChar2.toLowerCase()) {
return "capitalized";
}
}
}
if (token.type === "Punctuator" && BRACKET.test(token.value)) {
return "uncolored";
}
if (token.type === "Invalid" && token.value === "@") {
return "punctuator";
}
switch (token.type) {
case "NumericLiteral":
return "number";
case "StringLiteral":
case "JSXString":
case "NoSubstitutionTemplate":
return "string";
case "RegularExpressionLiteral":
return "regex";
case "Punctuator":
case "JSXPunctuator":
return "punctuator";
case "MultiLineComment":
case "SingleLineComment":
return "comment";
case "Invalid":
case "JSXInvalid":
return "invalid";
case "JSXIdentifier":
return "jsxIdentifier";
default:
return "uncolored";
}
};
}
});
// node_modules/.pnpm/rollup-plugin-dts@6.5.1_rollup@4.64.6_typescript@6.0.3/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.cjs
var require_rollup_plugin_dts = _chunkYQNCOY6Vjs.__commonJS.call(void 0, {
"node_modules/.pnpm/rollup-plugin-dts@6.5.1_rollup@4.64.6_typescript@6.0.3/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.cjs"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var path3 = _chunkYQNCOY6Vjs.__require.call(void 0, "path");
var node_module = _chunkYQNCOY6Vjs.__require.call(void 0, "module");
var remapping = require_remapping_umd();
var MagicString = require_magic_string_cjs();
var fs2 = _chunkYQNCOY6Vjs.__require.call(void 0, "fs/promises");
var sourcemapCodec = require_sourcemap_codec_umd();
var convert$1 = require_convert_source_map();
var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
function _interopNamespaceDefault(e) {
var n = /* @__PURE__ */ Object.create(null);
if (e) {
Object.keys(e).forEach(function(k) {
if (k !== "default") {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function() {
return e[k];
}
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var path__namespace = /* @__PURE__ */ _interopNamespaceDefault(path3);
var require$1 = node_module.createRequire(typeof document === "undefined" ? _chunkYQNCOY6Vjs.__require.call(void 0, "url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("rollup-plugin-dts.cjs", document.baseURI).href);
function loadTypeScript() {
let ts3;
try {
ts3 = require$1("typescript");
} catch (e2) {
}
if (ts3 && typeof ts3.createProgram === "function") {
return ts3;
}
try {
return require$1("@typescript/typescript6");
} catch (e3) {
if (ts3) {
throw new Error(
`rollup-plugin-dts requires the TypeScript compiler API. The installed typescript@${ts3.version} does not provide it, and the \`@typescript/typescript6\` fallback is not installed.
TypeScript 7 does not ship a compiler API, so please additionally install the compatibility package:
npm install -D @typescript/typescript6`
);
}
throw new Error(
"rollup-plugin-dts requires the TypeScript compiler API, but the `typescript` package could not be loaded.\nPlease install typescript 4.5 - 6.x, or typescript 7 together with the `@typescript/typescript6` compatibility package:\n npm install -D typescript"
);
}
}
var ts2 = loadTypeScript();
function resolveDefaultOptions(options) {
return {
...options,
compilerOptions: _nullishCoalesce(options.compilerOptions, () => ( {})),
respectExternal: _nullishCoalesce(options.respectExternal, () => ( false)),
includeExternal: _nullishCoalesce(options.includeExternal, () => ( [])),
sourcemap: _nullishCoalesce(options.sourcemap, () => ( false))
};
}
var DTS_EXTENSIONS = /\.d\.(c|m)?tsx?$/;
var JSON_EXTENSIONS = /\.json$/;
var SUPPORTED_EXTENSIONS = /((\.d)?\.(c|m)?(t|j)sx?|\.json)$/;
function trimExtension(path4) {
return path4.replace(SUPPORTED_EXTENSIONS, "");
}
function getDeclarationId(path4) {
return path4.replace(SUPPORTED_EXTENSIONS, ".d.ts");
}
function parse(fileName, code) {
return ts2.createSourceFile(fileName, code, ts2.ScriptTarget.Latest, true);
}
var formatHost = {
getCurrentDirectory: () => ts2.sys.getCurrentDirectory(),
getNewLine: () => ts2.sys.newLine,
getCanonicalFileName: ts2.sys.useCaseSensitiveFileNames ? (f) => f : (f) => f.toLowerCase()
};
var DEFAULT_OPTIONS = {
// Ensure ".d.ts" modules are generated
declaration: true,
// Skip ".js" generation
noEmit: false,
emitDeclarationOnly: true,
// Skip code generation when error occurs
noEmitOnError: true,
// Avoid extra work
checkJs: false,
declarationMap: false,
skipLibCheck: true,
// Ensure TS2742 errors are visible
preserveSymlinks: true,
// Ensure we can parse the latest code
target: ts2.ScriptTarget.ESNext,
// Allows importing `*.json`
resolveJsonModule: true
};
var configByPath = /* @__PURE__ */ new Map();
var logCache = (...args) => process.env.DTS_LOG_CACHE ? console.log("[cache]", ...args) : null;
function cacheConfig([fromPath, toPath], config) {
logCache(fromPath);
configByPath.set(fromPath, config);
while (fromPath !== toPath && // make sure we're not stuck in an infinite loop
fromPath !== path__namespace.dirname(fromPath)) {
fromPath = path__namespace.dirname(fromPath);
logCache("up", fromPath);
if (configByPath.has(fromPath))
return logCache("has", fromPath);
configByPath.set(fromPath, config);
}
}
function getCompilerOptions(input, overrideOptions, overrideConfigPath, enableDeclarationMap) {
const compilerOptions = {
...DEFAULT_OPTIONS,
...overrideOptions,
// When plugin's sourcemap option is explicitly true, force declarationMap
// regardless of user's compilerOptions setting.
// When sourcemap is false/undefined, respect user's compilerOptions.declarationMap.
...enableDeclarationMap === true && { declarationMap: true }
};
let dirName = path__namespace.dirname(input);
let dtsFiles = [];
const cacheKey = overrideConfigPath || dirName;
if (!configByPath.has(cacheKey)) {
logCache("miss", cacheKey);
const configPath = overrideConfigPath ? path__namespace.resolve(process.cwd(), overrideConfigPath) : ts2.findConfigFile(dirName, ts2.sys.fileExists);
if (!configPath) {
return { dtsFiles, dirName, compilerOptions };
}
const inputDirName = dirName;
dirName = path__namespace.dirname(configPath);
const { config, error } = ts2.readConfigFile(configPath, ts2.sys.readFile);
if (error) {
console.error(ts2.formatDiagnostic(error, formatHost));
return { dtsFiles, dirName, compilerOptions };
}
logCache("tsconfig", config);
const configContents = ts2.parseJsonConfigFileContent(config, ts2.sys, dirName);
if (overrideConfigPath) {
cacheConfig([overrideConfigPath, overrideConfigPath], configContents);
} else {
cacheConfig([inputDirName, dirName], configContents);
}
} else {
logCache("HIT", cacheKey);
}
const { fileNames, options, errors } = configByPath.get(cacheKey);
dtsFiles = fileNames.filter((name) => DTS_EXTENSIONS.test(name));
if (errors.length) {
console.error(ts2.formatDiagnostics(errors, formatHost));
return { dtsFiles, dirName, compilerOptions };
}
return {
dtsFiles,
dirName,
compilerOptions: {
...options,
...compilerOptions
}
};
}
function createProgram$1(fileName, overrideOptions, tsconfig, enableDeclarationMap) {
const { dtsFiles, compilerOptions } = getCompilerOptions(fileName, overrideOptions, tsconfig, enableDeclarationMap);
return ts2.createProgram([fileName].concat(Array.from(dtsFiles)), compilerOptions, ts2.createCompilerHost(compilerOptions, true));
}
function createPrograms(input, overrideOptions, tsconfig, enableDeclarationMap) {
const programs = [];
const dtsFiles = /* @__PURE__ */ new Set();
let inputs = [];
let dirName = "";
let compilerOptions = {};
for (let main of input) {
if (DTS_EXTENSIONS.test(main)) {
continue;
}
main = path__namespace.resolve(main);
const options = getCompilerOptions(main, overrideOptions, tsconfig, enableDeclarationMap);
options.dtsFiles.forEach(dtsFiles.add, dtsFiles);
if (!inputs.length) {
inputs.push(main);
({ dirName, compilerOptions } = options);
continue;
}
if (options.dirName === dirName) {
inputs.push(main);
} else {
const host = ts2.createCompilerHost(compilerOptions, true);
const program = ts2.createProgram(inputs.concat(Array.from(dtsFiles)), compilerOptions, host);
programs.push(program);
inputs = [main];
({ dirName, compilerOptions } = options);
}
}
if (inputs.length) {
const host = ts2.createCompilerHost(compilerOptions, true);
const program = ts2.createProgram(inputs.concat(Array.from(dtsFiles)), compilerOptions, host);
programs.push(program);
}
return programs;
}
function getCodeFrame() {
let codeFrameColumns2 = void 0;
try {
({ codeFrameColumns: codeFrameColumns2 } = (init_lib2(), _chunkYQNCOY6Vjs.__toCommonJS.call(void 0, lib_exports)));
return codeFrameColumns2;
} catch (e4) {
try {
const esmRequire = node_module.createRequire(typeof document === "undefined" ? _chunkYQNCOY6Vjs.__require.call(void 0, "url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("rollup-plugin-dts.cjs", document.baseURI).href);
({ codeFrameColumns: codeFrameColumns2 } = esmRequire("@babel/code-frame"));
return codeFrameColumns2;
} catch (e5) {
}
}
return void 0;
}
function getLocation(node) {
const sourceFile = node.getSourceFile();
const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
return {
start: { line: start.line + 1, column: start.character + 1 },
end: { line: end.line + 1, column: end.character + 1 }
};
}
function frameNode(node) {
const codeFrame = getCodeFrame();
const sourceFile = node.getSourceFile();
const code = sourceFile.getFullText();
const location = getLocation(node);
if (codeFrame) {
return "\n" + codeFrame(code, location, {
highlightCode: true
});
} else {
return `
${location.start.line}:${location.start.column}: \`${node.getFullText().trim()}\``;
}
}
var UnsupportedSyntaxError = class extends Error {
constructor(node, message = "Syntax not yet supported") {
super(`${message}
${frameNode(node)}`);
}
};
var NamespaceFixer = class {
constructor(sourceFile) {
this.sourceFile = sourceFile;
}
findNamespaces() {
const namespaces = [];
const items = {};
for (const node of this.sourceFile.statements) {
const location = {
start: node.getStart(),
end: node.getEnd()
};
if (ts2.isEmptyStatement(node)) {
namespaces.unshift({
name: "",
exports: [],
location
});
continue;
}
if ((ts2.isImportDeclaration(node) || ts2.isExportDeclaration(node)) && node.moduleSpecifier && ts2.isStringLiteral(node.moduleSpecifier)) {
const { text } = node.moduleSpecifier;
if (text.startsWith(".") && (text.endsWith(".d.ts") || text.endsWith(".d.cts") || text.endsWith(".d.mts"))) {
const start = node.moduleSpecifier.getStart() + 1;
const end = node.moduleSpecifier.getEnd() - 1;
namespaces.unshift({
name: "",
exports: [],
location: {
start,
end
},
textBeforeCodeAfter: text.replace(/\.d\.ts$/, ".js").replace(/\.d\.cts$/, ".cjs").replace(/\.d\.mts$/, ".mjs")
});
}
}
if (ts2.isModuleDeclaration(node) && node.body) {
let body = node.body;
while (ts2.isModuleDeclaration(body) && body.body) {
body = body.body;
}
if (!ts2.isModuleBlock(body)) {
continue;
}
for (const stmt of body.statements) {
if (ts2.isExportDeclaration(stmt) && stmt.exportClause) {
if (ts2.isNamespaceExport(stmt.exportClause)) {
continue;
}
for (const decl2 of stmt.exportClause.elements) {
if (decl2.propertyName && decl2.propertyName.getText() == decl2.name.getText()) {
namespaces.unshift({
name: "",
exports: [],
location: {
start: decl2.propertyName.getEnd(),
end: decl2.name.getEnd()
}
});
}
}
}
}
}
if (ts2.isClassDeclaration(node)) {
items[node.name.getText()] = { type: "class", generics: node.typeParameters };
} else if (ts2.isFunctionDeclaration(node)) {
items[node.name.getText()] = { type: "function" };
} else if (ts2.isInterfaceDeclaration(node)) {
items[node.name.getText()] = { type: "interface", generics: node.typeParameters };
} else if (ts2.isTypeAliasDeclaration(node)) {
items[node.name.getText()] = { type: "type", generics: node.typeParameters };
} else if (ts2.isModuleDeclaration(node) && ts2.isIdentifier(node.name)) {
items[node.name.getText()] = { type: "namespace" };
} else if (ts2.isEnumDeclaration(node)) {
items[node.name.getText()] = { type: "enum" };
}
if (!ts2.isVariableStatement(node)) {
continue;
}
const { declarations } = node.declarationList;
if (declarations.length !== 1) {
continue;
}
const decl = declarations[0];
const name = decl.name.getText();
if (!decl.initializer || !ts2.isCallExpression(decl.initializer)) {
items[name] = { type: "var" };
continue;
}
const obj = decl.initializer.arguments[0];
if (!decl.initializer.expression.getFullText().includes("/*#__PURE__*/Object.freeze") || !ts2.isObjectLiteralExpression(obj)) {
continue;
}
const exports2 = [];
for (const prop of obj.properties) {
if (!ts2.isPropertyAssignment(prop) || !(ts2.isIdentifier(prop.name) || ts2.isStringLiteral(prop.name)) || prop.name.text !== "__proto__" && !ts2.isIdentifier(prop.initializer)) {
throw new UnsupportedSyntaxError(prop, "Expected a property assignment");
}
if (prop.name.text === "__proto__") {
continue;
}
exports2.push({
exportedName: prop.name.text,
localName: prop.initializer.getText()
});
}
namespaces.unshift({
name,
exports: exports2,
location
});
}
return { namespaces, itemTypes: items };
}
fix() {
let code = this.sourceFile.getFullText();
const { namespaces, itemTypes } = this.findNamespaces();
for (const ns of namespaces) {
const codeAfter = code.slice(ns.location.end);
code = code.slice(0, ns.location.start);
for (const { exportedName, localName } of ns.exports) {
if (exportedName === localName) {
const { type, generics } = itemTypes[localName] || {};
if (type === "interface" || type === "type") {
const typeParams = renderTypeParams(generics);
code += `type ${ns.name}_${exportedName}${typeParams.in} = ${localName}${typeParams.out};
`;
} else if (type === "enum" || type === "class") {
const typeParams = renderTypeParams(generics);
code += `type ${ns.name}_${exportedName}${typeParams.in} = ${localName}${typeParams.out};
`;
code += `declare const ${ns.name}_${exportedName}: typeof ${localName};
`;
} else if (type === "namespace") {
code += `import ${ns.name}_${exportedName} = ${localName};
`;
} else {
code += `declare const ${ns.name}_${exportedName}: typeof ${localName};
`;
}
}
}
if (ns.name) {
code += `declare namespace ${ns.name} {
`;
code += ` export {
`;
for (const { exportedName, localName } of ns.exports) {
if (exportedName === localName) {
code += ` ${ns.name}_${exportedName} as ${exportedName},
`;
} else {
code += ` ${localName} as ${exportedName},
`;
}
}
code += ` };
`;
code += `}`;
}
code += _nullishCoalesce(ns.textBeforeCodeAfter, () => ( ""));
code += codeAfter;
}
return code;
}
};
function renderTypeParams(typeParameters) {
if (!typeParameters || !typeParameters.length) {
return { in: "", out: "" };
}
return {
in: `<${typeParameters.map((param) => param.getText()).join(", ")}>`,
out: `<${typeParameters.map((param) => param.name.getText()).join(", ")}>`
};
}
var IDs = 1;
function createProgram(node) {
return withStartEnd({
type: "Program",
sourceType: "module",
body: []
}, { start: node.getFullStart(), end: node.getEnd() });
}
function createReference(id) {
const ident = {
type: "Identifier",
name: String(IDs++)
};
return {
ident,
expr: {
type: "AssignmentPattern",
left: ident,
right: id
}
};
}
function createIdentifier(node) {
return withStartEnd({
type: "Identifier",
name: node.text
}, node);
}
function createIIFE(range) {
const fn = withStartEnd({
type: "FunctionExpression",
id: null,
params: [],
body: { type: "BlockStatement", body: [] }
}, range);
const iife = withStartEnd({
type: "ExpressionStatement",
expression: {
type: "CallExpression",
callee: { type: "Identifier", name: String(IDs++) },
arguments: [fn],
optional: false
}
}, range);
return { fn, iife };
}
function createReturn() {
const expr = {
type: "ArrayExpression",
elements: []
};
return {
expr,
stmt: {
type: "ReturnStatement",
argument: expr
}
};
}
function createDeclaration(id, range) {
return withStartEnd({
type: "FunctionDeclaration",
id: withStartEnd({
type: "Identifier",
name: ts2.idText(id)
}, id),
params: [],
body: { type: "BlockStatement", body: [] }
}, range);
}
function convertExpression(node) {
if (ts2.isLiteralExpression(node)) {
return { type: "Literal", value: node.text };
}
if (ts2.isPropertyAccessExpression(node)) {
if (ts2.isPrivateIdentifier(node.name)) {
throw new UnsupportedSyntaxError(node.name);
}
return withStartEnd({
type: "MemberExpression",
computed: false,
optional: false,
object: convertExpression(node.expression),
property: convertExpression(node.name)
}, {
start: node.expression.getStart(),
end: node.name.getEnd()
});
}
if (ts2.isObjectLiteralExpression(node)) {
return withStartEnd({
type: "ObjectExpression",
properties: node.properties.map((prop) => {
if (ts2.isPropertyAssignment(prop)) {
return withStartEnd({
type: "Property",
key: ts2.isIdentifier(prop.name) ? createIdentifier(prop.name) : convertExpression(prop.name),
value: convertExpression(prop.initializer),
kind: "init",
method: false,
shorthand: false,
computed: ts2.isComputedPropertyName(prop.name)
}, prop);
} else if (ts2.isShorthandPropertyAssignment(prop)) {
return withStartEnd({
type: "Property",
key: createIdentifier(prop.name),
value: createIdentifier(prop.name),
kind: "init",
method: false,
shorthand: true,
computed: false
}, prop);
} else {
throw new UnsupportedSyntaxError(prop, "Unsupported property type in object literal");
}
})
}, node);
}
if (ts2.isArrayLiteralExpression(node)) {
return withStartEnd({
type: "ArrayExpression",
elements: node.elements.map((elem) => {
if (ts2.isExpression(elem)) {
return convertExpression(elem);
} else {
throw new UnsupportedSyntaxError(elem, "Unsupported element type in array literal");
}
})
}, node);
}
if (ts2.isIdentifier(node)) {
return createIdentifier(node);
} else if (node.kind == ts2.SyntaxKind.NullKeyword) {
return { type: "Literal", value: null };
} else {
throw new UnsupportedSyntaxError(node);
}
}
function withStartEnd(esNode, nodeOrRange) {
const range = "start" in nodeOrRange ? nodeOrRange : { start: nodeOrRange.getStart(), end: nodeOrRange.getEnd() };
return Object.assign(esNode, range);
}
function matchesModifier(node, flags) {
const nodeFlags = ts2.getCombinedModifierFlags(node);
return (nodeFlags & flags) === flags;
}
var LanguageService = (_class = class {
__init() {this.fileName = "index.d.ts"}
constructor(code) {;_class.prototype.__init.call(this);
const serviceHost = {
getCompilationSettings: () => ({
noEmit: true,
noResolve: true,
skipLibCheck: true,
declaration: false,
checkJs: false,
declarationMap: false,
target: ts2.ScriptTarget.ESNext
}),
getScriptFileNames: () => [this.fileName],
getScriptVersion: () => "1",
getScriptSnapshot: (fileName) => fileName === this.fileName ? ts2.ScriptSnapshot.fromString(code) : void 0,
getCurrentDirectory: () => "",
getDefaultLibFileName: () => "",
fileExists: (fileName) => fileName === this.fileName,
readFile: (fileName) => fileName === this.fileName ? code : void 0
};
this.service = ts2.createLanguageService(serviceHost, ts2.createDocumentRegistry(void 0, ""), ts2.LanguageServiceMode.PartialSemantic);
}
findReferenceCount(node) {
const referencedSymbols = this.service.findReferences(this.fileName, node.getStart());
if (!_optionalChain([referencedSymbols, 'optionalAccess', _2 => _2.length])) {
return 0;
}
return referencedSymbols.reduce((total, symbol) => total + symbol.references.length, 0);
}
}, _class);
var TypeOnlyFixer = (_class2 = class {
__init2() {this.types = /* @__PURE__ */ new Set()}
__init3() {this.values = /* @__PURE__ */ new Set()}
__init4() {this.typeHints = /* @__PURE__ */ new Map()}
__init5() {this.reExportTypeHints = /* @__PURE__ */ new Map()}
__init6() {this.importNodes = []}
__init7() {this.exportNodes = []}
constructor(fileName, rawCode) {;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);_class2.prototype.__init6.call(this);_class2.prototype.__init7.call(this);
this.rawCode = rawCode;
this.source = parse(fileName, rawCode);
this.code = new MagicString(rawCode);
}
fix() {
this.analyze(this.source.statements);
if (this.typeHints.size || this.reExportTypeHints.size) {
this.service = new LanguageService(this.rawCode);
this.importNodes.forEach((node) => this.fixTypeOnlyImport(node));
}
if (this.types.size) {
this.exportNodes.forEach((node) => this.fixTypeOnlyExport(node));
}
return this.types.size ? {
magicCode: this.code
} : {
code: this.rawCode,
map: null
};
}
fixTypeOnlyImport(node) {
let hasRemoved = false;
const typeImports = [];
const valueImports = [];
const specifier = node.moduleSpecifier.getText();
const nameNode = node.importClause.name;
const namedBindings = node.importClause.namedBindings;
if (nameNode) {
const name = nameNode.text;
if (this.isTypeOnly(name)) {
if (this.isUselessImport(nameNode)) {
hasRemoved = true;
} else {
typeImports.push(`import type ${name} from ${specifier};`);
}
} else {
valueImports.push(`import ${name} from ${specifier};`);
}
}
if (namedBindings && ts2.isNamespaceImport(namedBindings)) {
const name = namedBindings.name.text;
if (this.isTypeOnly(name)) {
if (this.isUselessImport(namedBindings.name)) {
hasRemoved = true;
} else {
typeImports.push(`import type * as ${name} from ${specifier};`);
}
} else {
valueImports.push(`import * as ${name} from ${specifier};`);
}
}
if (namedBindings && ts2.isNamedImports(namedBindings)) {
const typeNames = [];
const valueNames = [];
for (const element of namedBindings.elements) {
if (this.isTypeOnly(element.name.text)) {
if (this.isUselessImport(element.name)) {
hasRemoved = true;
} else {
typeNames.push(element.getText());
}
} else {
valueNames.push(element.getText());
}
}
if (typeNames.length) {
typeImports.push(`import type { ${typeNames.join(", ")} } from ${specifier};`);
}
if (valueNames.length) {
valueImports.push(`import { ${valueNames.join(", ")} } from ${specifier};`);
}
}
if (typeImports.length || hasRemoved) {
this.code.overwrite(node.getStart(), node.getEnd(), [...valueImports, ...typeImports].join(`
${getNodeIndent(node)}`));
}
}
fixTypeOnlyExport(node) {
const typeExports = [];
const valueExports = [];
const specifier = _optionalChain([node, 'access', _3 => _3.moduleSpecifier, 'optionalAccess', _4 => _4.getText, 'call', _5 => _5()]);
if (ts2.isNamespaceExport(node.exportClause)) {
const name = node.exportClause.name.text;
if (this.isReExportTypeOnly(name)) {
typeExports.push(`export type * as ${name} from ${specifier};`);
} else {
valueExports.push(`export * as ${name} from ${specifier};`);
}
}
if (ts2.isNamedExports(node.exportClause)) {
const typeNames = [];
const valueNames = [];
for (const element of node.exportClause.elements) {
const name = _optionalChain([element, 'access', _6 => _6.propertyName, 'optionalAccess', _7 => _7.text]) || element.name.text;
const isType = node.moduleSpecifier ? this.isReExportTypeOnly(element.name.text) : this.isTypeOnly(name);
if (isType) {
typeNames.push(getExportSpecifierBinding(element));
} else {
valueNames.push(element.getText());
}
}
if (typeNames.length) {
typeExports.push(`export type { ${typeNames.join(", ")} }${specifier ? ` from ${specifier}` : ""};`);
}
if (valueNames.length) {
valueExports.push(`export { ${valueNames.join(", ")} }${specifier ? ` from ${specifier}` : ""};`);
}
}
if (typeExports.length) {
this.code.overwrite(node.getStart(), node.getEnd(), [...valueExports, ...typeExports].join(`
${getNodeIndent(node)}`));
}
}
analyze(nodes) {
for (const node of nodes) {
if (ts2.isImportDeclaration(node) && node.importClause) {
this.importNodes.push(node);
continue;
}
if (ts2.isExportDeclaration(node) && node.exportClause) {
this.exportNodes.push(node);
continue;
}
if (ts2.isInterfaceDeclaration(node)) {
this.types.add(node.name.text);
continue;
}
if (ts2.isTypeAliasDeclaration(node)) {
const alias = node.name.text;
this.types.add(alias);
continue;
}
if (ts2.isEnumDeclaration(node) || ts2.isFunctionDeclaration(node) || ts2.isClassDeclaration(node) || ts2.isVariableStatement(node)) {
if (ts2.isVariableStatement(node)) {
for (const declaration of node.declarationList.declarations) {
if (ts2.isIdentifier(declaration.name)) {
this.values.add(declaration.name.text);
}
}
} else {
if (node.name) {
this.values.add(node.name.text);
}
}
continue;
}
if (ts2.isModuleBlock(node)) {
this.analyze(node.statements);
continue;
}
if (ts2.isModuleDeclaration(node)) {
if (node.name && ts2.isIdentifier(node.name)) {
this.values.add(node.name.text);
}
this.analyze(node.getChildren());
continue;
}
}
}
// The type-hint statements may lead to redundant import statements.
// After type-hint statements been removed,
// it is better to also remove these redundant import statements as well.
// Of course, this is not necessary since it won't cause issues,
// but it can make the output bundles cleaner :)
isUselessImport(node) {
const referenceCount = this.service.findReferenceCount(node);
const typeHintCount = this.typeHints.get(node.text);
return typeHintCount && typeHintCount + 1 >= referenceCount;
}
isTypeOnly(name) {
return this.typeHints.has(name) || this.types.has(name) && !this.values.has(name);
}
isReExportTypeOnly(name) {
return this.reExportTypeHints.has(name);
}
}, _class2);
function getNodeIndent(node) {
const match = node.getFullText().match(/^(?:\n*)([ ]*)/);
return " ".repeat(_optionalChain([match, 'optionalAccess', _8 => _8[1], 'optionalAccess', _9 => _9.length]) || 0);
}
function getExportSpecifierBinding(element) {
if (element.propertyName) {
return `${element.propertyName.getText()} as ${element.name.getText()}`;
}
return element.name.getText();
}
var RESOLVED_MODULE_PREFIX = "dts-resolved:";
var RESOLVED_MODULE_COMMENT = new RegExp(`\\/\\*${RESOLVED_MODULE_PREFIX}(.+?)\\*\\/`);
function encodeResolvedModule(absolutePath) {
return `/*${RESOLVED_MODULE_PREFIX}${absolutePath}*/`;
}
function decodeResolvedModule(text) {
return _nullishCoalesce(_optionalChain([text, 'access', _10 => _10.match, 'call', _11 => _11(RESOLVED_MODULE_COMMENT), 'optionalAccess', _12 => _12[1]]), () => ( null));
}
function stripResolvedModuleComment(text) {
return text.replace(RESOLVED_MODULE_COMMENT, "");
}
function normalizePath3(p) {
return p.split("\\").join("/");
}
function getAugmentedNames(body) {
const names = [];
for (const statement of body.statements) {
if ((ts2.isInterfaceDeclaration(statement) || ts2.isClassDeclaration(statement) || ts2.isFunctionDeclaration(statement) || ts2.isEnumDeclaration(statement) || ts2.isTypeAliasDeclaration(statement)) && statement.name) {
names.push(statement.name.text);
} else if (ts2.isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
if (ts2.isIdentifier(declaration.name)) {
names.push(declaration.name.text);
}
}
}
}
return names;
}
var ModuleDeclarationFixer = class {
constructor(chunk, code, sourcemap, moduleToChunk, chunks, warn) {
this.code = code;
this.sourcemap = sourcemap;
this.source = parse(chunk.fileName, code.original);
this.chunkFileName = chunk.fileName;
this.moduleToChunk = moduleToChunk;
this.chunks = chunks;
this.warn = warn;
}
fix() {
let modified = false;
for (const node of this.source.statements) {
if (!ts2.isModuleDeclaration(node) || !node.body || !ts2.isModuleBlock(node.body)) {
continue;
}
const sourceText = this.source.getFullText();
const textBetween = sourceText.slice(node.name.getEnd(), node.body.getStart());
const absolutePath = decodeResolvedModule(textBetween);
if (!absolutePath) {
continue;
}
const target = this.findTargetChunk(absolutePath);
let specifier = node.name.getText();
if (target === null) {
this.warn(`declare module ${specifier} (${absolutePath}) could not be resolved to any output chunk, keeping the original specifier`);
} else if (!this.augmentationApplies(getAugmentedNames(node.body), target.moduleId, target.chunkFileName)) {
this.warn(`declare module ${specifier} (${absolutePath}) augments names that the target chunk does not export unchanged, keeping the original specifier`);
} else {
const quote = node.name.kind === ts2.SyntaxKind.StringLiteral && "singleQuote" in node.name && node.name.singleQuote ? "'" : '"';
specifier = `${quote}${this.formatChunkReference(target.chunkFileName, target.jsExt)}${quote}`;
}
const cleanedBetween = stripResolvedModuleComment(textBetween);
this.code.overwrite(node.name.getStart(), node.body.getStart(), specifier + cleanedBetween);
modified = true;
}
return {
code: this.code.toString(),
map: modified && this.sourcemap ? this.code.generateMap() : null
};
}
/**
* Find the output chunk containing the module at an absolute path.
* Returns null when the module is not part of any output chunk.
*/
findTargetChunk(absolutePath) {
const jsExtMatch = absolutePath.match(/\.[cm]?js$/);
const basePath = jsExtMatch ? absolutePath.slice(0, -jsExtMatch[0].length) : absolutePath;
const extensions = ["", ".d.ts", ".d.mts", ".d.cts", ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
const possiblePaths = [];
for (const base of [basePath, `${basePath}/index`]) {
for (const ext of extensions) {
possiblePaths.push(base + ext);
}
}
for (const possiblePath of possiblePaths) {
const moduleId = normalizePath3(possiblePath);
const chunkFileName = this.moduleToChunk.get(moduleId);
if (chunkFileName) {
return { chunkFileName, moduleId, jsExt: _optionalChain([jsExtMatch, 'optionalAccess', _13 => _13[0]]) };
}
}
return null;
}
/**
* Check that every augmented name is exported from the target chunk under its
* original name. Augmentation matches by exported name, so a name the chunk
* dropped, re-exported under an alias, or deconflicted (`Foo` → `Foo$1` when two
* modules in the chunk export a `Foo`) would merge into the wrong declaration.
*/
augmentationApplies(names, moduleId, chunkFileName) {
const chunkInfo = this.chunks[chunkFileName];
if (!chunkInfo) {
return true;
}
const targetModule = _optionalChain([Object, 'access', _14 => _14.entries, 'call', _15 => _15(chunkInfo.modules), 'access', _16 => _16.find, 'call', _17 => _17(([id]) => normalizePath3(id) === moduleId), 'optionalAccess', _18 => _18[1]]);
return names.every((name) => {
if (!_optionalChain([targetModule, 'optionalAccess', _19 => _19.renderedExports, 'access', _20 => _20.includes, 'call', _21 => _21(name)]) || !chunkInfo.exports.includes(name)) {
return false;
}
const deconflicted = new RegExp(`^${name.replace(/\$/g, "\\$")}\\$\\d+$`);
return !chunkInfo.exports.some((exportName) => deconflicted.test(exportName));
});
}
/**
* Format a chunk filename as a relative path from the current chunk.
*/
formatChunkReference(chunkFileName, jsExt) {
const chunkDir = path__namespace.dirname(this.chunkFileName);
let relativePath = normalizePath3(path__namespace.relative(chunkDir, chunkFileName));
relativePath = relativePath.replace(/\.d\.[cm]?tsx?$/, "");
if (jsExt) {
relativePath += jsExt;
}
if (!relativePath.startsWith(".")) {
relativePath = "./" + relativePath;
}
return relativePath;
}
};
function preProcessNamespaceBody(body, code, sourceFile) {
if (ts2.isModuleDeclaration(body)) {
if (body.body && (ts2.isModuleBlock(body.body) || ts2.isModuleDeclaration(body.body))) {
preProcessNamespaceBody(body.body, code);
}
return;
}
for (const stmt of body.statements) {
fixModifiers(code, stmt);
if (ts2.isModuleDeclaration(stmt) && stmt.body && (ts2.isModuleBlock(stmt.body) || ts2.isModuleDeclaration(stmt.body))) {
preProcessNamespaceBody(stmt.body, code);
}
}
}
function preProcess({ sourceFile, isEntry, isJSON }) {
const code = new MagicString(sourceFile.getFullText());
const treatAsGlobalModule = !isEntry && isGlobalModule(sourceFile);
const declaredNames = /* @__PURE__ */ new Set();
const exportedNames = /* @__PURE__ */ new Set();
let defaultExport = "";
const inlineImports = /* @__PURE__ */ new Map();
const nameRanges = /* @__PURE__ */ new Map();
for (const node of sourceFile.statements) {
if (ts2.isEmptyStatement(node)) {
code.remove(node.getStart(), node.getEnd());
continue;
}
if (ts2.isImportDeclaration(node)) {
if (!node.importClause) {
continue;
}
if (node.importClause.name) {
declaredNames.add(node.importClause.name.text);
}
if (node.importClause.namedBindings) {
if (ts2.isNamespaceImport(node.importClause.namedBindings)) {
declaredNames.add(node.importClause.namedBindings.name.text);
} else {
node.importClause.namedBindings.elements.forEach((element) => declaredNames.add(element.name.text));
}
}
} else if (ts2.isEnumDeclaration(node) || ts2.isFunctionDeclaration(node) || ts2.isInterfaceDeclaration(node) || ts2.isClassDeclaration(node) || ts2.isTypeAliasDeclaration(node) || ts2.isModuleDeclaration(node)) {
if (node.name) {
const name = node.name.getText();
declaredNames.add(name);
if (node.flags & ts2.NodeFlags.GlobalAugmentation) ;
else if (matchesModifier(node, ts2.ModifierFlags.ExportDefault)) {
defaultExport = name;
} else if (treatAsGlobalModule && ts2.isIdentifier(node.name) || matchesModifier(node, ts2.ModifierFlags.Export)) {
exportedNames.add(name);
}
if (!(node.flags & ts2.NodeFlags.GlobalAugmentation)) {
pushNamedNode(name, [getStart(node), getEnd(node)]);
}
}
if (ts2.isModuleDeclaration(node)) {
if (node.body && (ts2.isModuleBlock(node.body) || ts2.isModuleDeclaration(node.body))) {
preProcessNamespaceBody(node.body, code);
}
duplicateExports(code, node);
}
fixModifiers(code, node);
} else if (ts2.isVariableStatement(node)) {
const { declarations } = node.declarationList;
const isExport = matchesModifier(node, ts2.ModifierFlags.Export);
for (const decl of node.declarationList.declarations) {
if (ts2.isIdentifier(decl.name)) {
const name = decl.name.getText();
declaredNames.add(name);
if (treatAsGlobalModule || isExport) {
exportedNames.add(name);
}
}
}
fixModifiers(code, node);
if (declarations.length === 1) {
const decl = declarations[0];
if (ts2.isIdentifier(decl.name)) {
pushNamedNode(decl.name.getText(), [getStart(node), getEnd(node)]);
}
} else {
const decls = declarations.slice();
const first = decls.shift();
pushNamedNode(first.name.getText(), [getStart(node), first.getEnd()]);
for (const decl of decls) {
if (ts2.isIdentifier(decl.name)) {
pushNamedNode(decl.name.getText(), [decl.getFullStart(), decl.getEnd()]);
}
}
}
const { flags } = node.declarationList;
const type = flags & ts2.NodeFlags.Let ? "let" : flags & ts2.NodeFlags.Const ? "const" : "var";
const prefix = `declare ${type} `;
const list = node.declarationList.getChildren().find((c) => c.kind === ts2.SyntaxKind.SyntaxList).getChildren();
let commaPos = 0;
for (const node2 of list) {
if (node2.kind === ts2.SyntaxKind.CommaToken) {
commaPos = node2.getStart();
code.remove(commaPos, node2.getEnd());
} else if (commaPos) {
code.appendLeft(commaPos, ";\n");
const start = node2.getFullStart();
const slice = code.slice(start, node2.getStart());
const whitespace = slice.length - slice.trimStart().length;
if (whitespace) {
code.overwrite(start, start + whitespace, prefix);
} else {
code.appendLeft(start, prefix);
}
}
}
}
}
for (const node of sourceFile.statements) {
checkInlineImport(node);
if (ts2.isExportAssignment(node) && !node.isExportEquals) {
if (ts2.isObjectLiteralExpression(node.expression) || ts2.isArrayLiteralExpression(node.expression)) {
if (!defaultExport) {
defaultExport = uniqName("export_default");
}
code.overwrite(node.getStart(), node.expression.getStart(), `declare var ${defaultExport} = `);
continue;
}
}
if (!matchesModifier(node, ts2.ModifierFlags.ExportDefault)) {
continue;
}
if (ts2.isFunctionDeclaration(node) || ts2.isClassDeclaration(node)) {
if (node.name) {
continue;
}
if (!defaultExport) {
defaultExport = uniqName("export_default");
}
const children = node.getChildren();
const idx = children.findIndex((node2) => node2.kind === ts2.SyntaxKind.ClassKeyword || node2.kind === ts2.SyntaxKind.FunctionKeyword);
const token = children[idx];
const nextToken = children[idx + 1];
const isPunctuation = nextToken.kind >= ts2.SyntaxKind.FirstPunctuation && nextToken.kind <= ts2.SyntaxKind.LastPunctuation;
if (isPunctuation) {
const addSpace = code.slice(token.getEnd(), nextToken.getStart()) != " ";
code.appendLeft(nextToken.getStart(), `${addSpace ? " " : ""}${defaultExport}`);
} else {
code.appendRight(token.getEnd(), ` ${defaultExport}`);
}
}
}
for (const ranges of nameRanges.values()) {
const last = ranges.pop();
const start = last[0];
for (const node of ranges) {
code.move(node[0], node[1], start);
}
}
if (defaultExport) {
code.append(`
export default ${defaultExport};
`);
}
if (exportedNames.size) {
code.append(`
export { ${[...exportedNames].join(", ")} };
`);
}
if (isJSON && exportedNames.size) {
defaultExport = uniqName("export_default");
code.append([
`
declare const ${defaultExport}: {`,
[...exportedNames].map((name) => ` ${name}: typeof ${name};`).join("\n"),
`};`,
`export default ${defaultExport};
`
].join("\n"));
}
for (const [fileId, importName] of inlineImports.entries()) {
code.prepend(`import * as ${importName} from "${fileId}";
`);
}
const lineStarts = sourceFile.getLineStarts();
const typeReferences = /* @__PURE__ */ new Set();
for (const ref of sourceFile.typeReferenceDirectives) {
typeReferences.add(ref.fileName);
const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos);
const start = lineStarts[line];
let end = sourceFile.getLineEndOfPosition(ref.pos);
if (code.slice(end, end + 1) === "\n") {
end += 1;
}
code.remove(start, end);
}
const fileReferences = /* @__PURE__ */ new Set();
for (const ref of sourceFile.referencedFiles) {
fileReferences.add(ref.fileName);
const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos);
const start = lineStarts[line];
let end = sourceFile.getLineEndOfPosition(ref.pos);
if (code.slice(end, end + 1) === "\n") {
end += 1;
}
code.remove(start, end);
}
const sourceDir = path__namespace.dirname(sourceFile.fileName);
for (const node of sourceFile.statements) {
if (ts2.isModuleDeclaration(node) && node.body && ts2.isModuleBlock(node.body) && ts2.isStringLiteral(node.name) && /^\.\.?\//.test(node.name.text)) {
const resolvedPath = path__namespace.resolve(sourceDir, node.name.text);
code.appendRight(node.name.getEnd(), encodeResolvedModule(resolvedPath));
}
}
const fullText = sourceFile.getFullText();
const eofTrivia = ts2.getLeadingCommentRanges(fullText, sourceFile.endOfFileToken.getFullStart());
const lastStatement = sourceFile.statements[sourceFile.statements.length - 1];
const trailingTrivia = lastStatement ? ts2.getTrailingCommentRanges(fullText, lastStatement.getEnd()) : void 0;
for (const comment of [..._nullishCoalesce(eofTrivia, () => ( [])), ..._nullishCoalesce(trailingTrivia, () => ( []))]) {
if (comment.kind !== ts2.SyntaxKind.SingleLineCommentTrivia)
continue;
const text = fullText.slice(comment.pos, comment.end);
if (!/^\/\/[#@]\s*sourceMappingURL=/.test(text))
continue;
let start = comment.pos;
if (start > 0 && fullText[start - 1] === "\n") {
start -= 1;
}
code.remove(start, comment.end);
break;
}
return {
code,
typeReferences,
fileReferences
};
function checkInlineImport(node) {
ts2.forEachChild(node, checkInlineImport);
if (ts2.isImportTypeNode(node)) {
if (!ts2.isLiteralTypeNode(node.argument) || !ts2.isStringLiteral(node.argument.literal)) {
throw new UnsupportedSyntaxError(node, "inline imports should have a literal argument");
}
const fileId = node.argument.literal.text;
const children = node.getChildren();
const start = children.find((t) => t.kind === ts2.SyntaxKind.ImportKeyword).getStart();
let end = node.getEnd();
const token = children.find((t) => t.kind === ts2.SyntaxKind.DotToken || t.kind === ts2.SyntaxKind.LessThanToken);
if (token) {
end = token.getStart();
}
const importName = createNamespaceImport(fileId);
code.overwrite(start, end, importName);
}
}
function createNamespaceImport(fileId) {
let importName = inlineImports.get(fileId);
if (!importName) {
importName = uniqName(getSafeName(fileId));
inlineImports.set(fileId, importName);
}
return importName;
}
function uniqName(hint) {
let name = hint;
while (declaredNames.has(name)) {
name = `_${name}`;
}
declaredNames.add(name);
return name;
}
function pushNamedNode(name, range) {
let nodes = nameRanges.get(name);
if (!nodes) {
nodes = [range];
nameRanges.set(name, nodes);
} else {
const last = nodes[nodes.length - 1];
if (last[1] === range[0]) {
last[1] = range[1];
} else {
nodes.push(range);
}
}
}
}
function isGlobalModule(sourceFile) {
let isModule = false;
for (const node of sourceFile.statements) {
if (ts2.isExportDeclaration(node) || ts2.isExportAssignment(node)) {
return false;
}
if (isModule || ts2.isImportDeclaration(node) || matchesModifier(node, ts2.ModifierFlags.Export)) {
isModule = true;
}
}
return isModule;
}
function fixModifiers(code, node) {
if (!ts2.canHaveModifiers(node)) {
return;
}
const isTopLevel = node.parent.kind === ts2.SyntaxKind.SourceFile;
if (isTopLevel) {
let hasDeclare = false;
const needsDeclare = ts2.isEnumDeclaration(node) || ts2.isClassDeclaration(node) || ts2.isFunctionDeclaration(node) || ts2.isModuleDeclaration(node) || ts2.isVariableStatement(node);
for (const mod of _nullishCoalesce(node.modifiers, () => ( []))) {
switch (mod.kind) {
case ts2.SyntaxKind.ExportKeyword:
// fall through
case ts2.SyntaxKind.DefaultKeyword:
code.remove(mod.getStart(), mod.getEnd() + 1);
break;
case ts2.SyntaxKind.DeclareKeyword:
hasDeclare = true;
}
}
if (needsDeclare && !hasDeclare) {
code.appendRight(node.getStart(), "declare ");
}
}
}
function duplicateExports(code, module2) {
if (!module2.body) {
return;
}
if (ts2.isModuleDeclaration(module2.body)) {
duplicateExports(code, module2.body);
return;
}
if (!ts2.isModuleBlock(module2.body)) {
return;
}
for (const node of module2.body.statements) {
if (ts2.isExportDeclaration(node) && node.exportClause) {
if (ts2.isNamespaceExport(node.exportClause)) {
continue;
}
for (const decl of node.exportClause.elements) {
if (!decl.propertyName) {
code.appendLeft(decl.name.getEnd(), ` as ${decl.name.getText()}`);
}
}
}
}
}
function getSafeName(fileId) {
return fileId.replace(/[^a-zA-Z0-9_$]/g, () => "_");
}
function getStart(node) {
const start = node.getFullStart();
return start + (newlineAt(node, start) ? 1 : 0);
}
function getEnd(node) {
const end = node.getEnd();
return end + (newlineAt(node, end) ? 1 : 0);
}
function newlineAt(node, idx) {
return node.getSourceFile().getFullText()[idx] === "\n";
}
var IGNORE_TYPENODES = /* @__PURE__ */ new Set([
ts2.SyntaxKind.LiteralType,
ts2.SyntaxKind.VoidKeyword,
ts2.SyntaxKind.UnknownKeyword,
ts2.SyntaxKind.AnyKeyword,
ts2.SyntaxKind.BooleanKeyword,
ts2.SyntaxKind.NumberKeyword,
ts2.SyntaxKind.StringKeyword,
ts2.SyntaxKind.ObjectKeyword,
ts2.SyntaxKind.NullKeyword,
ts2.SyntaxKind.UndefinedKeyword,
ts2.SyntaxKind.SymbolKeyword,
ts2.SyntaxKind.NeverKeyword,
ts2.SyntaxKind.ThisKeyword,
ts2.SyntaxKind.ThisType,
ts2.SyntaxKind.BigIntKeyword
]);
var DeclarationScope = (_class3 = class {
constructor({ id, range }) {;_class3.prototype.__init8.call(this);
if (id) {
this.declaration = createDeclaration(id, range);
} else {
const { iife, fn } = createIIFE(range);
this.iife = iife;
this.declaration = fn;
}
const ret = createReturn();
this.declaration.body.body.push(ret.stmt);
this.returnExpr = ret.expr;
}
/**
* As we walk the AST, we need to keep track of type variable bindings that
* shadow the outer identifiers. To achieve this, we keep a stack of scopes,
* represented as Sets of variable names.
*/
__init8() {this.scopes = []}
pushScope() {
this.scopes.push(/* @__PURE__ */ new Set());
}
popScope(n = 1) {
for (let i = 0; i < n; i++) {
this.scopes.pop();
}
}
pushTypeVariable(id) {
const name = id.getText();
_optionalChain([this, 'access', _22 => _22.scopes, 'access', _23 => _23[this.scopes.length - 1], 'optionalAccess', _24 => _24.add, 'call', _25 => _25(name)]);
}
pushReference(id) {
let name;
if (id.type === "Identifier") {
name = id.name;
} else if (id.type === "MemberExpression") {
if (id.object.type === "Identifier") {
name = id.object.name;
}
}
if (name) {
for (const scope of this.scopes) {
if (scope.has(name)) {
return;
}
}
}
if (name === "this")
return;
const { ident, expr } = createReference(id);
this.declaration.params.push(expr);
this.returnExpr.elements.push(ident);
}
pushIdentifierReference(id) {
this.pushReference(createIdentifier(id));
}
convertEntityName(node) {
if (ts2.isIdentifier(node)) {
return createIdentifier(node);
}
return withStartEnd({
type: "MemberExpression",
computed: false,
optional: false,
object: this.convertEntityName(node.left),
property: createIdentifier(node.right)
}, node);
}
convertPropertyAccess(node) {
if (!ts2.isIdentifier(node.expression) && !ts2.isPropertyAccessExpression(node.expression)) {
throw new UnsupportedSyntaxError(node.expression);
}
if (ts2.isPrivateIdentifier(node.name)) {
throw new UnsupportedSyntaxError(node.name);
}
const object = ts2.isIdentifier(node.expression) ? createIdentifier(node.expression) : this.convertPropertyAccess(node.expression);
return withStartEnd({
type: "MemberExpression",
computed: false,
optional: false,
object,
property: createIdentifier(node.name)
}, node);
}
convertComputedPropertyName(node) {
if (!node.name || !ts2.isComputedPropertyName(node.name)) {
return;
}
const { expression } = node.name;
if (ts2.isLiteralExpression(expression) || ts2.isPrefixUnaryExpression(expression)) {
return;
}
if (ts2.isIdentifier(expression)) {
return this.pushReference(createIdentifier(expression));
}
if (ts2.isPropertyAccessExpression(expression)) {
return this.pushReference(this.convertPropertyAccess(expression));
}
throw new UnsupportedSyntaxError(expression);
}
convertParametersAndType(node) {
this.convertComputedPropertyName(node);
const typeVariables = this.convertTypeParameters(node.typeParameters);
for (const param of node.parameters) {
this.convertTypeNode(param.type);
}
this.convertTypeNode(node.type);
this.popScope(typeVariables);
}
convertHeritageClauses(node) {
for (const heritage of node.heritageClauses || []) {
for (const type of heritage.types) {
this.pushReference(convertExpression(type.expression));
this.convertTypeArguments(type);
}
}
}
convertTypeArguments(node) {
if (!node.typeArguments) {
return;
}
for (const arg of node.typeArguments) {
this.convertTypeNode(arg);
}
}
convertMembers(members) {
for (const node of members) {
if (ts2.isPropertyDeclaration(node) || ts2.isPropertySignature(node) || ts2.isIndexSignatureDeclaration(node)) {
if (ts2.isPropertyDeclaration(node) && node.initializer && ts2.isPropertyAccessExpression(node.initializer)) {
this.pushReference(this.convertPropertyAccess(node.initializer));
}
this.convertComputedPropertyName(node);
this.convertTypeNode(node.type);
continue;
}
if (ts2.isMethodDeclaration(node) || ts2.isMethodSignature(node) || ts2.isConstructorDeclaration(node) || ts2.isConstructSignatureDeclaration(node) || ts2.isCallSignatureDeclaration(node) || ts2.isGetAccessorDeclaration(node) || ts2.isSetAccessorDeclaration(node)) {
this.convertParametersAndType(node);
} else {
throw new UnsupportedSyntaxError(node);
}
}
}
convertTypeParameters(params) {
if (!params) {
return 0;
}
for (const node of params) {
this.convertTypeNode(node.constraint);
this.convertTypeNode(node.default);
this.pushScope();
this.pushTypeVariable(node.name);
}
return params.length;
}
convertTypeNode(node) {
if (!node) {
return;
}
if (IGNORE_TYPENODES.has(node.kind)) {
return;
}
if (ts2.isTypeReferenceNode(node)) {
this.pushReference(this.convertEntityName(node.typeName));
this.convertTypeArguments(node);
return;
}
if (ts2.isTypeLiteralNode(node)) {
this.convertMembers(node.members);
return;
}
if (ts2.isArrayTypeNode(node)) {
this.convertTypeNode(node.elementType);
return;
}
if (ts2.isTupleTypeNode(node)) {
for (const type of node.elements) {
this.convertTypeNode(type);
}
return;
}
if (ts2.isNamedTupleMember(node) || ts2.isParenthesizedTypeNode(node) || ts2.isTypeOperatorNode(node) || ts2.isTypePredicateNode(node)) {
this.convertTypeNode(node.type);
return;
}
if (ts2.isUnionTypeNode(node) || ts2.isIntersectionTypeNode(node)) {
for (const type of node.types) {
this.convertTypeNode(type);
}
return;
}
if (ts2.isMappedTypeNode(node)) {
const { typeParameter, type, nameType } = node;
this.convertTypeNode(typeParameter.constraint);
this.pushScope();
this.pushTypeVariable(typeParameter.name);
this.convertTypeNode(type);
if (nameType) {
this.convertTypeNode(nameType);
}
this.popScope();
return;
}
if (ts2.isConditionalTypeNode(node)) {
this.convertTypeNode(node.checkType);
this.pushScope();
this.convertTypeNode(node.extendsType);
this.convertTypeNode(node.trueType);
this.convertTypeNode(node.falseType);
this.popScope();
return;
}
if (ts2.isIndexedAccessTypeNode(node)) {
this.convertTypeNode(node.objectType);
this.convertTypeNode(node.indexType);
return;
}
if (ts2.isFunctionOrConstructorTypeNode(node)) {
this.convertParametersAndType(node);
return;
}
if (ts2.isTypeQueryNode(node)) {
const reference = this.convertEntityName(node.exprName);
this.pushReference(reference);
this.convertTypeArguments(node);
return;
}
if (ts2.isRestTypeNode(node)) {
this.convertTypeNode(node.type);
return;
}
if (ts2.isOptionalTypeNode(node)) {
this.convertTypeNode(node.type);
return;
}
if (ts2.isTemplateLiteralTypeNode(node)) {
for (const span of node.templateSpans) {
this.convertTypeNode(span.type);
}
return;
}
if (ts2.isInferTypeNode(node)) {
const { typeParameter } = node;
this.convertTypeNode(typeParameter.constraint);
this.pushTypeVariable(typeParameter.name);
return;
} else {
throw new UnsupportedSyntaxError(node);
}
}
convertNamespace(node, relaxedModuleBlock = false) {
this.pushScope();
if (relaxedModuleBlock && node.body && ts2.isModuleDeclaration(node.body)) {
this.convertNamespace(node.body, true);
return;
}
if (!node.body || !ts2.isModuleBlock(node.body)) {
throw new UnsupportedSyntaxError(node, `namespace must have a "ModuleBlock" body.`);
}
const { statements } = node.body;
for (const stmt of statements) {
if (ts2.isEnumDeclaration(stmt) || ts2.isFunctionDeclaration(stmt) || ts2.isClassDeclaration(stmt) || ts2.isInterfaceDeclaration(stmt) || ts2.isTypeAliasDeclaration(stmt) || ts2.isModuleDeclaration(stmt)) {
if (stmt.name && ts2.isIdentifier(stmt.name)) {
this.pushTypeVariable(stmt.name);
} else {
throw new UnsupportedSyntaxError(stmt, "non-Identifier name not supported");
}
continue;
}
if (ts2.isVariableStatement(stmt)) {
for (const decl of stmt.declarationList.declarations) {
if (ts2.isIdentifier(decl.name)) {
this.pushTypeVariable(decl.name);
} else {
throw new UnsupportedSyntaxError(decl, "non-Identifier name not supported");
}
}
continue;
}
if (ts2.isImportDeclaration(stmt)) {
if (stmt.importClause) {
if (stmt.importClause.name) {
this.pushTypeVariable(stmt.importClause.name);
}
if (stmt.importClause.namedBindings) {
if (ts2.isNamespaceImport(stmt.importClause.namedBindings)) {
this.pushTypeVariable(stmt.importClause.namedBindings.name);
} else {
for (const el of stmt.importClause.namedBindings.elements) {
this.pushTypeVariable(el.name);
}
}
}
}
continue;
}
if (ts2.isImportEqualsDeclaration(stmt)) {
this.pushTypeVariable(stmt.name);
continue;
}
if (ts2.isExportDeclaration(stmt)) ;
else {
throw new UnsupportedSyntaxError(stmt, "namespace child (hoisting) not supported yet");
}
}
for (const stmt of statements) {
if (ts2.isVariableStatement(stmt)) {
for (const decl of stmt.declarationList.declarations) {
if (decl.type) {
this.convertTypeNode(decl.type);
}
}
continue;
}
if (ts2.isFunctionDeclaration(stmt)) {
this.convertParametersAndType(stmt);
continue;
}
if (ts2.isInterfaceDeclaration(stmt) || ts2.isClassDeclaration(stmt)) {
const typeVariables = this.convertTypeParameters(stmt.typeParameters);
this.convertHeritageClauses(stmt);
this.convertMembers(stmt.members);
this.popScope(typeVariables);
continue;
}
if (ts2.isTypeAliasDeclaration(stmt)) {
const typeVariables = this.convertTypeParameters(stmt.typeParameters);
this.convertTypeNode(stmt.type);
this.popScope(typeVariables);
continue;
}
if (ts2.isModuleDeclaration(stmt)) {
this.convertNamespace(stmt, relaxedModuleBlock);
continue;
}
if (ts2.isEnumDeclaration(stmt)) {
continue;
}
if (ts2.isImportDeclaration(stmt)) {
continue;
}
if (ts2.isImportEqualsDeclaration(stmt)) {
if (ts2.isEntityName(stmt.moduleReference)) {
this.pushReference(this.convertEntityName(stmt.moduleReference));
}
continue;
}
if (ts2.isExportDeclaration(stmt)) {
if (stmt.exportClause) {
if (ts2.isNamespaceExport(stmt.exportClause)) {
throw new UnsupportedSyntaxError(stmt.exportClause);
}
for (const decl of stmt.exportClause.elements) {
const id = decl.propertyName || decl.name;
this.pushIdentifierReference(id);
}
}
} else {
throw new UnsupportedSyntaxError(stmt, "namespace child (walking) not supported yet");
}
}
this.popScope();
}
}, _class3);
function convert({ sourceFile }) {
const transformer = new Transformer(sourceFile);
return transformer.transform();
}
var Transformer = (_class4 = class {
__init9() {this.declarations = /* @__PURE__ */ new Map()}
constructor(sourceFile) {;_class4.prototype.__init9.call(this);
this.sourceFile = sourceFile;
this.ast = createProgram(sourceFile);
for (const stmt of sourceFile.statements) {
this.convertStatement(stmt);
}
}
transform() {
return {
ast: this.ast
};
}
pushStatement(node) {
this.ast.body.push(node);
}
createDeclaration(node, id) {
const range = { start: node.getFullStart(), end: node.getEnd() };
if (!id) {
const scope2 = new DeclarationScope({ range });
this.pushStatement(scope2.iife);
return scope2;
}
const name = id.getText();
const scope = new DeclarationScope({ id, range });
const existingScope = this.declarations.get(name);
if (existingScope) {
existingScope.pushIdentifierReference(id);
existingScope.declaration.end = range.end;
const selfIdx = this.ast.body.findIndex((node2) => node2 == existingScope.declaration);
for (let i = selfIdx + 1; i < this.ast.body.length; i++) {
const decl = this.ast.body[i];
decl.start = decl.end = range.end;
}
} else {
this.pushStatement(scope.declaration);
this.declarations.set(name, scope);
}
return existingScope || scope;
}
convertStatement(node) {
if (ts2.isEnumDeclaration(node)) {
return this.convertEnumDeclaration(node);
}
if (ts2.isFunctionDeclaration(node)) {
return this.convertFunctionDeclaration(node);
}
if (ts2.isInterfaceDeclaration(node) || ts2.isClassDeclaration(node)) {
return this.convertClassOrInterfaceDeclaration(node);
}
if (ts2.isTypeAliasDeclaration(node)) {
return this.convertTypeAliasDeclaration(node);
}
if (ts2.isVariableStatement(node)) {
return this.convertVariableStatement(node);
}
if (ts2.isExportDeclaration(node) || ts2.isExportAssignment(node)) {
return this.convertExportDeclaration(node);
}
if (ts2.isModuleDeclaration(node)) {
return this.convertNamespaceDeclaration(node);
}
if (node.kind === ts2.SyntaxKind.NamespaceExportDeclaration) {
return this.removeStatement(node);
}
if (ts2.isImportDeclaration(node) || ts2.isImportEqualsDeclaration(node)) {
return this.convertImportDeclaration(node);
} else {
throw new UnsupportedSyntaxError(node);
}
}
removeStatement(node) {
this.pushStatement(withStartEnd({
type: "ExpressionStatement",
expression: { type: "Literal", value: "pls remove me" }
}, node));
}
convertNamespaceDeclaration(node) {
const isGlobalAugmentation = node.flags & ts2.NodeFlags.GlobalAugmentation;
if (isGlobalAugmentation || !ts2.isIdentifier(node.name)) {
const scope2 = this.createDeclaration(node);
scope2.convertNamespace(node, true);
return;
}
const scope = this.createDeclaration(node, node.name);
scope.pushIdentifierReference(node.name);
scope.convertNamespace(node, true);
}
convertEnumDeclaration(node) {
const scope = this.createDeclaration(node, node.name);
scope.pushIdentifierReference(node.name);
}
convertFunctionDeclaration(node) {
if (!node.name) {
throw new UnsupportedSyntaxError(node, "FunctionDeclaration should have a name");
}
const scope = this.createDeclaration(node, node.name);
scope.pushIdentifierReference(node.name);
scope.convertParametersAndType(node);
}
convertClassOrInterfaceDeclaration(node) {
if (!node.name) {
throw new UnsupportedSyntaxError(node, "ClassDeclaration / InterfaceDeclaration should have a name");
}
const scope = this.createDeclaration(node, node.name);
const typeVariables = scope.convertTypeParameters(node.typeParameters);
scope.convertHeritageClauses(node);
scope.convertMembers(node.members);
scope.popScope(typeVariables);
}
convertTypeAliasDeclaration(node) {
const scope = this.createDeclaration(node, node.name);
const typeVariables = scope.convertTypeParameters(node.typeParameters);
scope.convertTypeNode(node.type);
scope.popScope(typeVariables);
}
convertVariableStatement(node) {
const { declarations } = node.declarationList;
if (declarations.length !== 1) {
throw new UnsupportedSyntaxError(node, "VariableStatement with more than one declaration not yet supported");
}
for (const decl of declarations) {
if (!ts2.isIdentifier(decl.name)) {
throw new UnsupportedSyntaxError(node, "VariableDeclaration must have a name");
}
const scope = this.createDeclaration(node, decl.name);
scope.convertTypeNode(decl.type);
if (decl.initializer) {
this.trackExpressionReferences(decl.initializer, scope);
}
}
}
// Helper to track identifier references in expressions
trackExpressionReferences(expr, scope) {
if (ts2.isIdentifier(expr)) {
scope.pushIdentifierReference(expr);
} else if (ts2.isObjectLiteralExpression(expr)) {
for (const prop of expr.properties) {
if (ts2.isShorthandPropertyAssignment(prop)) {
scope.pushIdentifierReference(prop.name);
} else if (ts2.isPropertyAssignment(prop)) {
this.trackExpressionReferences(prop.initializer, scope);
}
}
} else if (ts2.isArrayLiteralExpression(expr)) {
for (const elem of expr.elements) {
if (ts2.isExpression(elem)) {
this.trackExpressionReferences(elem, scope);
}
}
} else if (ts2.isPropertyAccessExpression(expr)) {
this.trackExpressionReferences(expr.expression, scope);
}
}
convertExportDeclaration(node) {
if (ts2.isExportAssignment(node)) {
this.pushStatement(withStartEnd({
type: "ExportDefaultDeclaration",
declaration: convertExpression(node.expression)
}, node));
return;
}
const source = node.moduleSpecifier ? convertExpression(node.moduleSpecifier) : void 0;
if (!node.exportClause) {
this.pushStatement(withStartEnd({
type: "ExportAllDeclaration",
source,
exported: null,
attributes: []
}, node));
} else if (ts2.isNamespaceExport(node.exportClause)) {
this.pushStatement(withStartEnd({
type: "ExportAllDeclaration",
source,
exported: createIdentifier(node.exportClause.name),
attributes: []
}, node));
} else {
const specifiers = [];
for (const elem of node.exportClause.elements) {
specifiers.push(this.convertExportSpecifier(elem));
}
this.pushStatement(withStartEnd({
type: "ExportNamedDeclaration",
declaration: null,
specifiers,
source,
attributes: []
}, node));
}
}
convertImportDeclaration(node) {
if (ts2.isImportEqualsDeclaration(node)) {
if (ts2.isEntityName(node.moduleReference)) {
const scope = this.createDeclaration(node, node.name);
scope.pushReference(scope.convertEntityName(node.moduleReference));
return;
}
if (!ts2.isExternalModuleReference(node.moduleReference)) {
throw new UnsupportedSyntaxError(node, "ImportEquals should have a literal source.");
}
this.pushStatement(withStartEnd({
type: "ImportDeclaration",
specifiers: [
{
type: "ImportDefaultSpecifier",
local: createIdentifier(node.name)
}
],
source: convertExpression(node.moduleReference.expression),
attributes: []
}, node));
return;
}
const source = convertExpression(node.moduleSpecifier);
const specifiers = node.importClause && node.importClause.namedBindings ? this.convertNamedImportBindings(node.importClause.namedBindings) : [];
if (node.importClause && node.importClause.name) {
specifiers.push({
type: "ImportDefaultSpecifier",
local: createIdentifier(node.importClause.name)
});
}
this.pushStatement(withStartEnd({
type: "ImportDeclaration",
specifiers,
source,
attributes: []
}, node));
}
convertNamedImportBindings(node) {
if (ts2.isNamedImports(node)) {
return node.elements.map((el) => {
const local = createIdentifier(el.name);
const imported = el.propertyName ? createIdentifier(el.propertyName) : local;
return {
type: "ImportSpecifier",
local,
imported
};
});
}
return [
{
type: "ImportNamespaceSpecifier",
local: createIdentifier(node.name)
}
];
}
convertExportSpecifier(node) {
const exported = createIdentifier(node.name);
return {
type: "ExportSpecifier",
exported,
local: node.propertyName ? createIdentifier(node.propertyName) : exported
};
}
}, _class4);
function hydrateSourcemap(sparseMappings, inputMap, outputCode) {
const sparseDecoded = sourcemapCodec.decode(sparseMappings);
const inputDecoded = sourcemapCodec.decode(inputMap.mappings);
const outputLines = outputCode.split("\n");
const hydratedMappings = [];
for (let outLine = 0; outLine < sparseDecoded.length; outLine += 1) {
const sparseSegments = sparseDecoded[outLine];
if (!sparseSegments || sparseSegments.length === 0) {
hydratedMappings.push([]);
continue;
}
const anchor = sparseSegments.find((segment) => segment.length >= 4);
if (!anchor) {
hydratedMappings.push(sparseSegments);
continue;
}
const [, srcIdx, srcLine] = anchor;
if (srcIdx !== 0 || srcLine === void 0 || srcLine < 0 || srcLine >= inputDecoded.length) {
hydratedMappings.push(sparseSegments);
continue;
}
const inputSegments = inputDecoded[srcLine];
if (!inputSegments || inputSegments.length === 0) {
hydratedMappings.push(sparseSegments);
continue;
}
const anchorOutCol = anchor[0];
const anchorSrcCol = anchor.length >= 4 ? anchor[3] : 0;
const delta = anchorOutCol - (_nullishCoalesce(anchorSrcCol, () => ( 0)));
const outputLine = outputLines[outLine] || "";
const hydratedSegments = [];
for (const seg of inputSegments) {
const adjustedCol = seg[0] + delta;
if (adjustedCol < 0 || adjustedCol > outputLine.length)
continue;
if (seg.length === 5) {
hydratedSegments.push([adjustedCol, seg[1], seg[2], seg[3], seg[4]]);
} else if (seg.length === 4) {
hydratedSegments.push([adjustedCol, seg[1], seg[2], seg[3]]);
} else {
hydratedSegments.push([adjustedCol]);
}
}
hydratedSegments.sort((a, b) => a[0] - b[0]);
hydratedMappings.push(hydratedSegments);
}
return sourcemapCodec.encode(hydratedMappings);
}
async function loadInputSourcemap(info) {
const { fileName, originalCode, inputMapText } = info;
if (inputMapText) {
try {
return JSON.parse(inputMapText);
} catch (e6) {
return null;
}
}
const inlineConverter = convert$1.fromSource(originalCode);
if (inlineConverter) {
return inlineConverter.toObject();
}
const readMap = async (mapFile) => {
const urlWithoutQuery = mapFile.split(/[?#]/)[0];
const mapFilePath = path__namespace.resolve(path__namespace.dirname(fileName), urlWithoutQuery);
return fs2.readFile(mapFilePath, "utf8");
};
try {
const fileConverter = await convert$1.fromMapFileSource(originalCode, readMap);
if (fileConverter) {
return fileConverter.toObject();
}
} catch (e7) {
}
try {
const mapContent = await fs2.readFile(fileName + ".map", "utf8");
return JSON.parse(mapContent);
} catch (e8) {
return null;
}
}
function rewritePortableSharedChunkImportsInBundle(bundle, warn) {
const chunks = Object.values(bundle).filter(isOutputChunk);
const sharedChunks = chunks.filter((chunk) => !chunk.isEntry);
if (sharedChunks.length === 0)
return;
const entryChunks = chunks.filter((chunk) => chunk.isEntry);
const chunkGraph = new Map(chunks.map((chunk) => [
chunk.fileName,
{
exports: chunk.exports,
isEntry: chunk.isEntry
}
]));
const analyses = new Map(chunks.map((chunk) => [chunk.fileName, analyzeChunk(chunk, chunkGraph)]));
for (const chunk of entryChunks) {
const analysis = analyses.get(chunk.fileName);
const magicCode = new MagicString(chunk.code);
let hasChanges = false;
const unresolvedSymbols = /* @__PURE__ */ new Set();
for (const statement of analysis.importStatements) {
const sharedChunk = sharedChunks.find((candidate) => getChunkImportSpecifier(chunk.fileName, candidate.fileName) === statement.moduleSpecifier);
if (!sharedChunk) {
continue;
}
const keptSpecifiers = [];
const rewrittenSpecifiers = /* @__PURE__ */ new Map();
for (const specifier of statement.specifiers) {
if (hasPublicHostRoute(analysis, statement.moduleSpecifier, specifier.importedName)) {
keptSpecifiers.push(specifier);
continue;
}
const hostCandidate = pickHostCandidate(entryChunks, analyses, chunk.fileName, sharedChunk.fileName, specifier);
if (!hostCandidate) {
keptSpecifiers.push(specifier);
unresolvedSymbols.add(specifier.localName);
continue;
}
const hostSpecifier = getChunkImportSpecifier(chunk.fileName, hostCandidate.chunk.fileName);
const hostImportSpecifiers = rewrittenSpecifiers.get(hostSpecifier) || [];
hostImportSpecifiers.push({
importedName: hostCandidate.exportedName,
isTypeOnly: specifier.isTypeOnly || hostCandidate.isTypeOnly,
localName: specifier.localName
});
rewrittenSpecifiers.set(hostSpecifier, hostImportSpecifiers);
}
if (!rewrittenSpecifiers.size) {
continue;
}
const replacementStatements = [];
if (keptSpecifiers.length) {
replacementStatements.push(buildImportStatement(statement, keptSpecifiers, statement.moduleSpecifier, statement.quote));
}
const hostSpecifiers = Array.from(rewrittenSpecifiers.keys()).sort(compareStrings);
for (const hostSpecifier of hostSpecifiers) {
replacementStatements.push(buildImportStatement(statement, rewrittenSpecifiers.get(hostSpecifier), hostSpecifier, statement.quote));
}
magicCode.overwrite(statement.statement.getStart(), statement.statement.getEnd(), replacementStatements.join("\n"));
hasChanges = true;
}
if (hasChanges) {
applyChunkEdits(chunk, magicCode);
}
if (unresolvedSymbols.size) {
warn(formatUnresolvedSharedTypeWarning(chunk.fileName, unresolvedSymbols));
}
}
}
function analyzeChunk(chunk, chunkGraph) {
const source = parse(chunk.fileName, chunk.code);
const importStatements = [];
const importedBindings = /* @__PURE__ */ new Map();
const hostRoutesByModule = /* @__PURE__ */ new Map();
const starExports = [];
for (const statement of source.statements) {
if (ts2.isImportDeclaration(statement) && !_optionalChain([statement, 'access', _26 => _26.importClause, 'optionalAccess', _27 => _27.name]) && ts2.isStringLiteral(statement.moduleSpecifier) && _optionalChain([statement, 'access', _28 => _28.importClause, 'optionalAccess', _29 => _29.namedBindings]) && ts2.isNamedImports(statement.importClause.namedBindings)) {
const moduleSpecifier = statement.moduleSpecifier.text;
const quote = statement.moduleSpecifier.getText(source).startsWith('"') ? '"' : "'";
const specifiers = statement.importClause.namedBindings.elements.map((element) => {
const specifier = {
importedName: _optionalChain([element, 'access', _30 => _30.propertyName, 'optionalAccess', _31 => _31.text]) || element.name.text,
isTypeOnly: element.isTypeOnly || _optionalChain([statement, 'access', _32 => _32.importClause, 'optionalAccess', _33 => _33.isTypeOnly]) || false,
localName: element.name.text
};
importedBindings.set(specifier.localName, {
importedName: specifier.importedName,
isTypeOnly: specifier.isTypeOnly,
moduleSpecifier
});
return specifier;
});
importStatements.push({
isTypeOnly: statement.importClause.isTypeOnly,
moduleSpecifier,
quote,
specifiers,
statement
});
continue;
}
if (!ts2.isExportDeclaration(statement) || !statement.moduleSpecifier || !ts2.isStringLiteral(statement.moduleSpecifier)) {
continue;
}
if (!statement.exportClause) {
starExports.push(statement.moduleSpecifier.text);
continue;
}
if (!ts2.isNamedExports(statement.exportClause)) {
continue;
}
for (const element of statement.exportClause.elements) {
addHostExportRoute(hostRoutesByModule, statement.moduleSpecifier.text, _optionalChain([element, 'access', _34 => _34.propertyName, 'optionalAccess', _35 => _35.text]) || element.name.text, {
exportedName: element.name.text,
isTypeOnly: statement.isTypeOnly || element.isTypeOnly
});
}
}
for (const statement of source.statements) {
if (!ts2.isExportDeclaration(statement) || statement.moduleSpecifier || !statement.exportClause || !ts2.isNamedExports(statement.exportClause)) {
continue;
}
for (const element of statement.exportClause.elements) {
const localName = _optionalChain([element, 'access', _36 => _36.propertyName, 'optionalAccess', _37 => _37.text]) || element.name.text;
const binding = importedBindings.get(localName);
if (!binding) {
continue;
}
addHostExportRoute(hostRoutesByModule, binding.moduleSpecifier, binding.importedName, {
exportedName: element.name.text,
isTypeOnly: binding.isTypeOnly || statement.isTypeOnly || element.isTypeOnly
});
}
}
for (const moduleSpecifier of starExports) {
const sharedChunk = Array.from(chunkGraph.entries()).find(([candidateFileName, candidate]) => !candidate.isEntry && getChunkImportSpecifier(chunk.fileName, candidateFileName) === moduleSpecifier);
if (!sharedChunk) {
continue;
}
for (const exportedName of sharedChunk[1].exports) {
if (exportedName === "default") {
continue;
}
addHostExportRoute(hostRoutesByModule, moduleSpecifier, exportedName, {
exportedName,
isTypeOnly: false
});
}
}
return {
hostRoutesByModule,
importStatements
};
}
var isOutputChunk = (chunk) => chunk.type === "chunk";
function pickHostCandidate(entryChunks, analyses, currentChunkFileName, sharedChunkFileName, specifier) {
const candidates = [];
for (const hostChunk of entryChunks) {
if (hostChunk.fileName === currentChunkFileName) {
continue;
}
const hostAnalysis = analyses.get(hostChunk.fileName);
const sharedSpecifier = getChunkImportSpecifier(hostChunk.fileName, sharedChunkFileName);
const routes = getHostExportRoutes(hostAnalysis, sharedSpecifier, specifier.importedName);
for (const route of routes) {
candidates.push({
...route,
chunk: hostChunk
});
}
}
candidates.sort((left, right) => {
const leftMatchesLocal = left.exportedName === specifier.localName ? 0 : 1;
const rightMatchesLocal = right.exportedName === specifier.localName ? 0 : 1;
if (leftMatchesLocal !== rightMatchesLocal) {
return leftMatchesLocal - rightMatchesLocal;
}
const fileNameOrder = compareStrings(left.chunk.fileName, right.chunk.fileName);
if (fileNameOrder !== 0) {
return fileNameOrder;
}
return compareStrings(left.exportedName, right.exportedName);
});
return candidates[0];
}
var getHostExportRoutes = (analysis, moduleSpecifier, importedName) => _optionalChain([analysis, 'access', _38 => _38.hostRoutesByModule, 'access', _39 => _39.get, 'call', _40 => _40(moduleSpecifier), 'optionalAccess', _41 => _41.get, 'call', _42 => _42(importedName)]) || [];
var hasPublicHostRoute = (analysis, moduleSpecifier, importedName) => getHostExportRoutes(analysis, moduleSpecifier, importedName).length > 0;
var compareStrings = (left, right) => {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
return 0;
};
function addHostExportRoute(hostRoutesByModule, moduleSpecifier, importedName, route) {
const routesByImportedName = hostRoutesByModule.get(moduleSpecifier) || /* @__PURE__ */ new Map();
const routes = routesByImportedName.get(importedName) || [];
if (!routes.some((existing) => existing.exportedName === route.exportedName && existing.isTypeOnly === route.isTypeOnly)) {
routes.push(route);
}
routesByImportedName.set(importedName, routes);
hostRoutesByModule.set(moduleSpecifier, routesByImportedName);
}
function buildImportStatement(statement, specifiers, moduleSpecifier, quote) {
const useTypeOnlyImport = statement.isTypeOnly || specifiers.every((specifier) => specifier.isTypeOnly);
const importKeyword = useTypeOnlyImport ? "import type" : "import";
const namedImports = specifiers.map((specifier) => {
const prefix = !useTypeOnlyImport && specifier.isTypeOnly ? "type " : "";
if (specifier.importedName === specifier.localName) {
return `${prefix}${specifier.importedName}`;
}
return `${prefix}${specifier.importedName} as ${specifier.localName}`;
}).join(", ");
return `${importKeyword} { ${namedImports} } from ${quote}${moduleSpecifier}${quote};`;
}
function applyChunkEdits(chunk, code) {
const nextCode = code.toString();
if (nextCode === chunk.code) {
return;
}
if (chunk.map) {
const chunkFileName = normalizeChunkPath(chunk.fileName);
const rewriteMap = code.generateMap({
file: chunkFileName,
hires: true,
includeContent: true,
source: chunkFileName
});
const remapped = remapping(rewriteMap, (file) => {
if (normalizeChunkPath(file) === chunkFileName) {
return chunk.map;
}
return null;
});
chunk.map = {
...chunk.map,
mappings: typeof remapped.mappings === "string" ? remapped.mappings : "",
names: remapped.names || [],
sources: remapped.sources
};
delete chunk.map.sourcesContent;
}
chunk.code = nextCode;
}
var formatUnresolvedSharedTypeWarning = (chunkFileName, symbols) => {
const symbolList = Array.from(symbols).sort().join(", ");
return [
`Entry "${chunkFileName}" still references private shared type exports with no public re-export: ${symbolList}.`,
"rollup-plugin-dts will not invent new public exports for these types.",
"Re-export them from a public entry to avoid downstream TS2742 errors."
].join(" ");
};
var getChunkImportSpecifier = (fromChunkFileName, toChunkFileName) => {
const fromDir = path__namespace.posix.dirname(normalizeChunkPath(fromChunkFileName));
const toRuntimeFileName = getChunkRuntimeFileName(normalizeChunkPath(toChunkFileName));
let relativePath = path__namespace.posix.relative(fromDir, toRuntimeFileName);
if (!relativePath.startsWith(".")) {
relativePath = `./${relativePath}`;
}
return relativePath;
};
var getChunkRuntimeFileName = (fileName) => {
if (fileName.endsWith(".d.mts")) {
return `${fileName.slice(0, -6)}.mjs`;
}
if (fileName.endsWith(".d.cts")) {
return `${fileName.slice(0, -6)}.cjs`;
}
if (fileName.endsWith(".d.ts")) {
return `${fileName.slice(0, -5)}.js`;
}
return `${fileName}.js`;
};
var normalizeChunkPath = (fileName) => fileName.replaceAll("\\", "/");
var transform = (enableSourcemap) => {
const allTypeReferences = /* @__PURE__ */ new Map();
const allFileReferences = /* @__PURE__ */ new Map();
const pendingSourcemaps = /* @__PURE__ */ new Map();
return {
name: "dts-transform",
buildStart() {
allTypeReferences.clear();
allFileReferences.clear();
pendingSourcemaps.clear();
},
options({ onLog, ...options }) {
return {
...options,
onLog(level, log, defaultHandler) {
if (level === "warn" && log.code === "CIRCULAR_DEPENDENCY") {
return;
}
if (onLog) {
onLog(level, log, defaultHandler);
} else {
defaultHandler(level, log);
}
},
treeshake: {
moduleSideEffects: "no-external",
propertyReadSideEffects: true,
unknownGlobalSideEffects: false
}
};
},
outputOptions(options) {
return {
...options,
chunkFileNames: options.chunkFileNames || "[name]-[hash].d.ts",
entryFileNames: options.entryFileNames || "[name].d.ts",
format: "es",
exports: "named",
compact: false,
freeze: true,
interop: "esModule",
generatedCode: Object.assign({ symbols: false }, options.generatedCode),
strict: false
};
},
transform(code, fileName, inputMapTextOrOptions) {
const name = trimExtension(fileName);
const moduleIds = this.getModuleIds();
const moduleId = Array.from(moduleIds).find((id) => trimExtension(id) === name);
const isEntry = Boolean(moduleId && _optionalChain([this, 'access', _43 => _43.getModuleInfo, 'call', _44 => _44(moduleId), 'optionalAccess', _45 => _45.isEntry]));
const isJSON = Boolean(moduleId && JSON_EXTENSIONS.test(moduleId));
const inputMapText = typeof inputMapTextOrOptions === "string" ? inputMapTextOrOptions : void 0;
const rawCode = code;
let sourceFile = parse(fileName, code);
const preprocessed = preProcess({ sourceFile, isEntry, isJSON });
allTypeReferences.set(sourceFile.fileName, preprocessed.typeReferences);
allFileReferences.set(sourceFile.fileName, preprocessed.fileReferences);
code = preprocessed.code.toString();
sourceFile = parse(fileName, code);
const converted = convert({ sourceFile });
if (process.env.DTS_DUMP_AST) {
console.log(fileName);
console.log(code);
console.log(JSON.stringify(converted.ast.body, void 0, 2));
}
if (!enableSourcemap) {
return { code, ast: converted.ast, map: null };
}
const map = preprocessed.code.generateMap({ hires: true, source: fileName });
if (DTS_EXTENSIONS.test(fileName)) {
pendingSourcemaps.set(fileName, {
fileName,
originalCode: rawCode,
inputMapText
});
}
return { code, ast: converted.ast, map };
},
renderChunk(inputCode, chunk, options, meta) {
const source = parse(chunk.fileName, inputCode);
const fixer = new NamespaceFixer(source);
const typeReferences = /* @__PURE__ */ new Set();
const fileReferences = /* @__PURE__ */ new Set();
for (const fileName of Object.keys(chunk.modules)) {
for (const ref of allTypeReferences.get(fileName.split("\\").join("/")) || []) {
typeReferences.add(ref);
}
for (const ref of allFileReferences.get(fileName.split("\\").join("/")) || []) {
if (ref.startsWith(".")) {
const absolutePathToOriginal = path__namespace.join(path__namespace.dirname(fileName), ref);
const chunkFolder = options.file && path__namespace.dirname(options.file) || chunk.facadeModuleId && path__namespace.dirname(chunk.facadeModuleId) || ".";
let targetRelPath = path__namespace.relative(chunkFolder, absolutePathToOriginal).split("\\").join("/");
if (targetRelPath[0] !== ".") {
targetRelPath = "./" + targetRelPath;
}
fileReferences.add(targetRelPath);
} else {
fileReferences.add(ref);
}
}
}
let code = writeBlock(Array.from(fileReferences, (ref) => `/// <reference path="${ref}" />`));
code += writeBlock(Array.from(typeReferences, (ref) => `/// <reference types="${ref}" />`));
code += fixer.fix();
if (!code) {
code += "\nexport { };";
}
const typeOnlyFixer = new TypeOnlyFixer(chunk.fileName, code);
const typesFixed = typeOnlyFixer.fix();
const moduleToChunk = /* @__PURE__ */ new Map();
for (const [chunkFileName, chunkInfo] of Object.entries(meta.chunks)) {
for (const moduleId of Object.keys(chunkInfo.modules)) {
moduleToChunk.set(moduleId.split("\\").join("/"), chunkFileName);
}
}
const moduleDeclarationFixer = new ModuleDeclarationFixer(chunk, "magicCode" in typesFixed && typesFixed.magicCode ? typesFixed.magicCode : new MagicString(code), !!options.sourcemap, moduleToChunk, meta.chunks, (message) => this.warn(message));
return moduleDeclarationFixer.fix();
},
async generateBundle(options, bundle) {
rewritePortableSharedChunkImportsInBundle(bundle, (message) => this.warn(message));
if (!options.sourcemap)
return;
const inputSourcemaps = /* @__PURE__ */ new Map();
const entries = Array.from(pendingSourcemaps.entries());
const loadedMaps = await Promise.all(entries.map(async ([fileName, info]) => ({
fileName,
inputMap: await loadInputSourcemap(info)
})));
const isUrl = (p) => /^[a-z][a-z0-9+.-]*:\/\//i.test(p);
for (const { fileName, inputMap } of loadedMaps) {
if (inputMap && inputMap.sources) {
const inputMapDir = path__namespace.dirname(fileName);
let sourceRoot;
if (inputMap.sourceRoot) {
sourceRoot = isUrl(inputMap.sourceRoot) ? inputMap.sourceRoot : path__namespace.resolve(inputMapDir, inputMap.sourceRoot);
} else {
sourceRoot = inputMapDir;
}
const sourceRootIsUrl = isUrl(sourceRoot);
inputSourcemaps.set(fileName, {
version: _nullishCoalesce(inputMap.version, () => ( 3)),
sources: inputMap.sources.map((source) => {
if (source === null)
return null;
if (isUrl(source))
return source;
if (sourceRootIsUrl) {
const base = sourceRoot.endsWith("/") ? sourceRoot : sourceRoot + "/";
return new URL(source, base).toString();
}
return path__namespace.isAbsolute(source) ? source : path__namespace.resolve(sourceRoot, source);
}),
// Note: sourcesContent intentionally not copied.
// TypeScript's declaration maps never include sourcesContent, and tsserver's
// getDocumentPositionMapper() rejects maps that have it (returns identity mapper).
// https://github.com/microsoft/TypeScript/blob/b19a9da2a3b8f2a720d314d01258dd2bdc110fef/src/services/sourcemaps.ts#L226
mappings: inputMap.mappings,
names: inputMap.names
});
}
}
const outputDir = options.dir || (options.file ? path__namespace.dirname(options.file) : process.cwd());
for (const chunk of Object.values(bundle)) {
if (chunk.type !== "chunk" || !chunk.map)
continue;
const chunkDir = path__namespace.join(outputDir, path__namespace.dirname(chunk.fileName));
const toRelativeSourcePath = (source) => {
if (isUrl(source))
return source;
const relative = path__namespace.isAbsolute(source) ? path__namespace.relative(chunkDir, source) : source;
return relative.replaceAll("\\", "/");
};
const toRelativeSourcePathOrNull = (source) => source === null ? null : toRelativeSourcePath(source);
const sourcesToRemap = /* @__PURE__ */ new Map();
for (const source of chunk.map.sources) {
if (!source)
continue;
if (isUrl(source))
continue;
const absoluteSource = path__namespace.resolve(chunkDir, source);
let inputMap = inputSourcemaps.get(absoluteSource);
if (!inputMap && /\.[cm]?[tj]sx?$/.test(absoluteSource) && !absoluteSource.endsWith(".d.ts")) {
const dtsPath = absoluteSource.replace(/\.[cm]?[tj]sx?$/, ".d.ts");
inputMap = inputSourcemaps.get(dtsPath);
}
if (inputMap) {
sourcesToRemap.set(absoluteSource, inputMap);
}
}
if (sourcesToRemap.size === 0) {
delete chunk.map.sourcesContent;
if (chunk.map.sources.length === 0 && chunk.facadeModuleId) {
const inputMap = inputSourcemaps.get(chunk.facadeModuleId);
if (inputMap && inputMap.sources.length > 0) {
const newSources2 = inputMap.sources.map(toRelativeSourcePathOrNull);
chunk.map.sources = newSources2;
}
}
updateSourcemapAsset(bundle, chunk.fileName, {
sources: chunk.map.sources.map(toRelativeSourcePathOrNull),
mappings: chunk.map.mappings,
names: chunk.map.names || []
});
continue;
}
const isSingleSource = chunk.map.sources.length === 1 && sourcesToRemap.size === 1;
const singleInputMap = isSingleSource ? Array.from(sourcesToRemap.values())[0] : null;
const canSimplyReplace = singleInputMap && singleInputMap.sources.length === 1;
let newSources;
let newMappings;
let newNames;
if (canSimplyReplace && singleInputMap) {
newSources = singleInputMap.sources.map(toRelativeSourcePathOrNull);
newMappings = hydrateSourcemap(chunk.map.mappings, singleInputMap, chunk.code);
newNames = singleInputMap.names || [];
} else {
const visitedFiles = /* @__PURE__ */ new Set();
const remapped = remapping(chunk.map, (file) => {
const absolutePath = path__namespace.resolve(chunkDir, file);
if (visitedFiles.has(absolutePath)) {
return null;
}
visitedFiles.add(absolutePath);
const inputMap = sourcesToRemap.get(absolutePath);
if (inputMap) {
return inputMap;
}
return null;
});
newSources = remapped.sources.map(toRelativeSourcePathOrNull);
newMappings = typeof remapped.mappings === "string" ? remapped.mappings : "";
newNames = remapped.names || [];
}
chunk.map.sources = newSources;
delete chunk.map.sourcesContent;
chunk.map.mappings = newMappings;
chunk.map.names = newNames;
updateSourcemapAsset(bundle, chunk.fileName, {
sources: newSources,
mappings: newMappings,
names: newNames
});
}
}
};
};
function writeBlock(codes) {
if (codes.length) {
return codes.join("\n") + "\n";
}
return "";
}
function updateSourcemapAsset(bundle, chunkFileName, data) {
const mapFileName = `${chunkFileName}.map`;
const mapAsset = bundle[mapFileName];
if (mapAsset && mapAsset.type === "asset") {
mapAsset.source = JSON.stringify({
version: 3,
// file should be just the basename since the .map is in the same directory
file: path__namespace.basename(chunkFileName),
...data
});
}
}
var TS_EXTENSIONS = /\.([cm]ts|[tj]sx?)$/;
function getModule({ entries, programs, resolvedOptions }, fileName, code) {
const { compilerOptions, tsconfig } = resolvedOptions;
if (!programs.length && DTS_EXTENSIONS.test(fileName)) {
return { code };
}
const isEntry = entries.includes(fileName);
const existingProgram = programs.find((p) => {
if (isEntry) {
return p.getRootFileNames().includes(fileName);
} else {
const sourceFile = p.getSourceFile(fileName);
if (sourceFile && p.isSourceFileFromExternalLibrary(sourceFile)) {
return false;
}
return !!sourceFile;
}
});
if (existingProgram) {
const source = existingProgram.getSourceFile(fileName);
return {
code: _optionalChain([source, 'optionalAccess', _46 => _46.getFullText, 'call', _47 => _47()]),
source,
program: existingProgram
};
} else if (ts2.sys.fileExists(fileName)) {
if (programs.length > 0 && DTS_EXTENSIONS.test(fileName)) {
const shouldBundleExternal = resolvedOptions.includeExternal.length > 0 || resolvedOptions.respectExternal;
if (shouldBundleExternal) {
return { code };
}
}
const newProgram = createProgram$1(fileName, compilerOptions, tsconfig, resolvedOptions.sourcemap);
programs.push(newProgram);
const source = newProgram.getSourceFile(fileName);
return {
code: _optionalChain([source, 'optionalAccess', _48 => _48.getFullText, 'call', _49 => _49()]),
source,
program: newProgram
};
} else {
return null;
}
}
var plugin = (options = {}) => {
const ctx = { entries: [], programs: [], resolvedOptions: resolveDefaultOptions(options) };
const transformPlugin = transform(ctx.resolvedOptions.sourcemap);
return {
name: "dts",
// pass outputOptions, renderChunk, and generateBundle hooks to the inner transform plugin
outputOptions: transformPlugin.outputOptions,
renderChunk: transformPlugin.renderChunk,
generateBundle: transformPlugin.generateBundle,
options(options2) {
let { input = [] } = options2;
if (!Array.isArray(input)) {
input = typeof input === "string" ? [input] : Object.values(input);
} else if (input.length > 1) {
options2.input = {};
for (const filename of input) {
let name = trimExtension(filename);
if (path__namespace.isAbsolute(filename)) {
name = path__namespace.basename(name);
} else {
name = path__namespace.normalize(name);
}
options2.input[name] = filename;
}
}
ctx.programs = createPrograms(Object.values(input), ctx.resolvedOptions.compilerOptions, ctx.resolvedOptions.tsconfig, ctx.resolvedOptions.sourcemap);
return transformPlugin.options.call(this, options2);
},
transform(code, id) {
if (!TS_EXTENSIONS.test(id) && !JSON_EXTENSIONS.test(id)) {
return null;
}
const watchFiles = (module2) => {
if (module2.program) {
const sourceDirectory = path__namespace.dirname(id);
const sourceFilesInProgram = module2.program.getSourceFiles().map((sourceFile) => sourceFile.fileName).filter((fileName) => fileName.startsWith(sourceDirectory));
sourceFilesInProgram.forEach(this.addWatchFile);
}
};
const handleDtsFile = () => {
const module2 = getModule(ctx, id, code);
if (module2) {
watchFiles(module2);
return transformPlugin.transform.call(this, module2.code, id);
}
return null;
};
const treatTsAsDts = () => {
const declarationId = getDeclarationId(id);
const module2 = getModule(ctx, declarationId, code);
if (module2) {
watchFiles(module2);
return transformPlugin.transform.call(this, module2.code, declarationId);
}
return null;
};
const generateDts = () => {
const module2 = getModule(ctx, id, code);
if (!module2 || !module2.source || !module2.program)
return null;
watchFiles(module2);
const declarationId = getDeclarationId(id);
let declarationText;
let declarationMapText;
const { emitSkipped, diagnostics } = module2.program.emit(
module2.source,
(emitFileName, text) => {
if (emitFileName.endsWith(".map")) {
declarationMapText = text;
} else {
declarationText = text;
}
},
void 0,
// cancellationToken
true,
// emitOnlyDtsFiles
void 0,
// customTransformers
// @ts-ignore This is a private API for workers, should be safe to use as TypeScript Playground has used it for a long time.
true
);
if (emitSkipped) {
const errors = diagnostics.filter((diag) => diag.category === ts2.DiagnosticCategory.Error);
if (errors.length) {
console.error(ts2.formatDiagnostics(errors, formatHost));
this.error("Failed to compile. Check the logs above.");
}
}
if (!declarationText)
return null;
const cleanDeclarationText = declarationText.replace(/\n?\/\/# sourceMappingURL=[^\n]+/, "");
return transformPlugin.transform.call(this, cleanDeclarationText, declarationId, declarationMapText);
};
if (DTS_EXTENSIONS.test(id))
return handleDtsFile();
if (JSON_EXTENSIONS.test(id))
return generateDts();
return _nullishCoalesce(treatTsAsDts(), () => ( generateDts()));
},
resolveId(source, importer) {
if (!importer) {
ctx.entries.push(path__namespace.resolve(source));
return;
}
importer = importer.split("\\").join("/");
let resolvedCompilerOptions = ctx.resolvedOptions.compilerOptions;
if (ctx.resolvedOptions.tsconfig) {
const resolvedSource = source.startsWith(".") ? path__namespace.resolve(path__namespace.dirname(importer), source) : source;
resolvedCompilerOptions = getCompilerOptions(resolvedSource, ctx.resolvedOptions.compilerOptions, ctx.resolvedOptions.tsconfig, ctx.resolvedOptions.sourcemap).compilerOptions;
}
const { resolvedModule } = ts2.resolveModuleName(source, importer, {
// Default moduleResolution to node10 if not explicitly set. TS6 changed
// the default from node10 to bundler, and bundler resolution picks .js
// files over directories with .d.ts index files, breaking .d.ts bundling.
moduleResolution: ts2.ModuleResolutionKind.Node10,
...resolvedCompilerOptions
}, ts2.sys);
if (!resolvedModule) {
return;
}
if (resolvedModule.isExternalLibraryImport && resolvedModule.packageId && ctx.resolvedOptions.includeExternal.includes(resolvedModule.packageId.name)) {
return { id: path__namespace.resolve(resolvedModule.resolvedFileName) };
} else if (!ctx.resolvedOptions.respectExternal && resolvedModule.isExternalLibraryImport) {
return { id: source, external: true };
} else {
return { id: path__namespace.resolve(resolvedModule.resolvedFileName) };
}
}
};
};
exports.default = plugin;
exports.dts = plugin;
}
});
// src/rollup.ts
var _worker_threads = require('worker_threads');
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
var _typescript = require('typescript'); var _typescript2 = _interopRequireDefault(_typescript);
// node_modules/.pnpm/@rollup+pluginutils@5.4.0_rollup@4.64.6/node_modules/@rollup/pluginutils/dist/es/index.js
var import_picomatch = _chunkYQNCOY6Vjs.__toESM.call(void 0, require_picomatch2(), 1);
function isArray(arg) {
return Array.isArray(arg);
}
function ensureArray(thing) {
if (isArray(thing))
return thing;
if (thing == null)
return [];
return [thing];
}
var normalizePathRegExp = new RegExp(`\\${_path.win32.sep}`, "g");
var normalizePath = function normalizePath2(filename) {
return filename.replace(normalizePathRegExp, _path.posix.sep);
};
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false || _path.isAbsolute.call(void 0, id) || id.startsWith("**")) {
return normalizePath(id);
}
const basePath = normalizePath(_path.resolve.call(void 0, resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&");
return _path.posix.join(basePath, normalizePath(id));
}
var createFilter = function createFilter2(include, exclude, options) {
const resolutionBase = options && options.resolve;
const getMatcher = (id) => id instanceof RegExp ? id : {
test: (what) => {
const pattern = getMatcherString(id, resolutionBase);
const fn = (0, import_picomatch.default)(pattern, { dot: true });
const result = fn(what);
return result;
}
};
const includeMatchers = ensureArray(include).map(getMatcher);
const excludeMatchers = ensureArray(exclude).map(getMatcher);
if (!includeMatchers.length && !excludeMatchers.length)
return (id) => typeof id === "string" && !id.includes("\0");
return function result(id) {
if (typeof id !== "string")
return false;
if (id.includes("\0"))
return false;
const pathId = normalizePath(id);
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher instanceof RegExp) {
matcher.lastIndex = 0;
}
if (matcher.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher instanceof RegExp) {
matcher.lastIndex = 0;
}
if (matcher.test(pathId))
return true;
}
return !includeMatchers.length;
};
};
var reservedWords = "break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public";
var builtins = "arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl";
var forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(" "));
forbiddenIdentifiers.add("");
var makeLegalIdentifier = function makeLegalIdentifier2(str) {
let identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, "_");
if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
identifier = `_${identifier}`;
}
return identifier || "_";
};
function stringify(obj) {
return (JSON.stringify(obj) || "undefined").replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
}
function serializeArray(arr, indent, baseIndent) {
let output = "[";
const separator = indent ? `
${baseIndent}${indent}` : "";
for (let i = 0; i < arr.length; i++) {
const key = arr[i];
output += `${i > 0 ? "," : ""}${separator}${serialize(key, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `
${baseIndent}` : ""}]`;
}
function serializeObject(obj, indent, baseIndent) {
let output = "{";
const separator = indent ? `
${baseIndent}${indent}` : "";
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) {
const [key, value2] = entries[i];
const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
output += `${i > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value2, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `
${baseIndent}` : ""}}`;
}
function serialize(obj, indent, baseIndent) {
if (typeof obj === "object" && obj !== null) {
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
return serializeObject(obj, indent, baseIndent);
}
if (typeof obj === "number") {
if (obj === Infinity)
return "Infinity";
if (obj === -Infinity)
return "-Infinity";
if (obj === 0)
return 1 / obj === Infinity ? "0" : "-0";
if (obj !== obj)
return "NaN";
}
if (typeof obj === "symbol") {
const key = Symbol.keyFor(obj);
if (key !== void 0)
return `Symbol.for(${stringify(key)})`;
}
if (typeof obj === "bigint")
return `${obj}n`;
return stringify(obj);
}
var hasStringIsWellFormed = "isWellFormed" in String.prototype;
function isWellFormedString(input) {
if (hasStringIsWellFormed)
return input.isWellFormed();
return !new RegExp("\\p{Surrogate}", "u").test(input);
}
var identifierNameRE = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
var dataToEsm = function dataToEsm2(data, options = {}) {
var _a, _b;
const t = options.compact ? "" : "indent" in options ? options.indent : " ";
const _ = options.compact ? "" : " ";
const n = options.compact ? "" : "\n";
const declarationType = options.preferConst ? "const" : "var";
if (options.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) {
const code = serialize(data, options.compact ? null : t, "");
const magic = _ || (/^[{[\-\/]/.test(code) ? "" : " ");
return `export default${magic}${code};`;
}
let maxUnderbarPrefixLength = 0;
for (const key of Object.keys(data)) {
const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
if (underbarPrefixLength > maxUnderbarPrefixLength) {
maxUnderbarPrefixLength = underbarPrefixLength;
}
}
const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
let namedExportCode = "";
const defaultExportRows = [];
const arbitraryNameExportRows = [];
for (const [key, value2] of Object.entries(data)) {
if (key === makeLegalIdentifier(key)) {
if (options.objectShorthand)
defaultExportRows.push(key);
else
defaultExportRows.push(`${key}:${_}${key}`);
namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value2, options.compact ? null : t, "")};${n}`;
} else {
defaultExportRows.push(`${stringify(key)}:${_}${serialize(value2, options.compact ? null : t, "")}`);
if (key !== "default") {
const isIdentifierName2 = identifierNameRE.test(key);
if (isIdentifierName2 || options.includeArbitraryNames && isWellFormedString(key)) {
const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value2, options.compact ? null : t, "")};${n}`;
arbitraryNameExportRows.push(`${variableName} as ${isIdentifierName2 ? key : JSON.stringify(key)}`);
}
}
}
}
const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` : "";
const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
};
// node_modules/.pnpm/@rollup+plugin-json@6.1.0_rollup@4.64.6/node_modules/@rollup/plugin-json/dist/es/index.js
function json(options) {
if (options === void 0) options = {};
var filter = createFilter(options.include, options.exclude);
var indent = "indent" in options ? options.indent : " ";
return {
name: "json",
// eslint-disable-next-line no-shadow
transform: function transform(code, id) {
if (id.slice(-5) !== ".json" || !filter(id)) {
return null;
}
try {
var parsed = JSON.parse(code);
return {
code: dataToEsm(parsed, {
preferConst: options.preferConst,
compact: options.compact,
namedExports: options.namedExports,
includeArbitraryNames: options.includeArbitraryNames,
indent
}),
map: { mappings: "" }
};
} catch (err) {
var message = "Could not parse JSON file";
this.error({ message, id, cause: err });
return null;
}
}
};
}
// src/rollup.ts
var _resolvefrom = require('resolve-from'); var _resolvefrom2 = _interopRequireDefault(_resolvefrom);
// src/rollup/ts-resolve.ts
var import_resolve = _chunkYQNCOY6Vjs.__toESM.call(void 0, require_resolve());
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
var _module = require('module');
var _obug = require('obug');
var debug = _obug.createDebug.call(void 0, "tsup:ts-resolve");
var resolveModule = (id, opts) => new Promise((resolve2, reject) => {
(0, import_resolve.default)(id, opts, (err, res) => {
if (_optionalChain([err, 'optionalAccess', _50 => _50.code]) === "MODULE_NOT_FOUND") return resolve2(null);
if (err) return reject(err);
resolve2(res || null);
});
});
var tsResolvePlugin = ({
resolveOnly,
ignore
} = {}) => {
const resolveExtensions = [".d.ts", ".ts"];
return {
name: `ts-resolve`,
async resolveId(source, importer) {
debug("resolveId source: %s", source);
debug("resolveId importer: %s ", importer);
if (!importer) return null;
if (/\0/.test(source)) return null;
if (_module.builtinModules.includes(source)) return false;
if (ignore && ignore(source, importer)) {
debug("ignored %s", source);
return null;
}
if (resolveOnly) {
const shouldResolve = resolveOnly.some((v) => {
if (typeof v === "string") return v === source;
return v.test(source);
});
if (!shouldResolve) {
debug("skipped by matching resolveOnly: %s", source);
return null;
}
}
if (_path2.default.isAbsolute(source)) {
debug(`skipped absolute path: %s`, source);
return null;
}
const basedir = importer ? await _fs2.default.promises.realpath(_path2.default.dirname(importer)) : process.cwd();
if (source[0] === ".") {
return resolveModule(source, {
basedir,
extensions: resolveExtensions
});
}
let id = null;
if (!importer) {
id = await resolveModule(`./${source}`, {
basedir,
extensions: resolveExtensions
});
}
if (!id) {
id = await resolveModule(source, {
basedir,
extensions: resolveExtensions,
packageFilter(pkg) {
pkg.main = pkg.types || pkg.typings;
return pkg;
},
paths: ["node_modules", "node_modules/@types"]
});
}
if (id) {
debug("resolved %s to %s", source, id);
return id;
}
debug("mark %s as external", source);
return false;
}
};
};
// src/rollup.ts
var _rollup = require('fix-dts-default-cjs-exports/rollup');
var logger = _chunk6IOGQ2V3js.createLogger.call(void 0, );
var parseCompilerOptions = (compilerOptions) => {
if (!compilerOptions) return {};
const { options } = _typescript2.default.parseJsonConfigFileContent(
{ compilerOptions },
_typescript2.default.sys,
"./"
);
return options;
};
var dtsPlugin = require_rollup_plugin_dts();
var getRollupConfig = async (options) => {
_chunk6IOGQ2V3js.setSilent.call(void 0, options.silent);
const compilerOptions = parseCompilerOptions(_optionalChain([options, 'access', _51 => _51.dts, 'optionalAccess', _52 => _52.compilerOptions]));
const dtsOptions = options.dts || {};
dtsOptions.entry = dtsOptions.entry || options.entry;
if (Array.isArray(dtsOptions.entry) && dtsOptions.entry.length > 1) {
dtsOptions.entry = _chunkYQNCOY6Vjs.toObjectEntry.call(void 0, dtsOptions.entry);
}
let tsResolveOptions;
if (dtsOptions.resolve) {
tsResolveOptions = {};
if (Array.isArray(dtsOptions.resolve)) {
tsResolveOptions.resolveOnly = dtsOptions.resolve;
}
if (compilerOptions.paths) {
const res = Object.keys(compilerOptions.paths).map(
(p) => new RegExp(`^${p.replace("*", ".+")}$`)
);
tsResolveOptions.ignore = (source) => {
return res.some((re) => re.test(source));
};
}
}
const pkg = await _chunk6IOGQ2V3js.loadPkg.call(void 0, process.cwd());
const deps = await _chunk6IOGQ2V3js.getProductionDeps.call(void 0, process.cwd());
const tsupCleanPlugin = {
name: "tsup:clean",
async buildStart() {
if (options.clean) {
await _chunkYQNCOY6Vjs.removeFiles.call(void 0, ["**/*.d.{ts,mts,cts}"], options.outDir);
}
}
};
const ignoreFiles = {
name: "tsup:ignore-files",
load(id) {
if (!/\.(js|cjs|mjs|jsx|ts|tsx|mts|json)$/.test(id)) {
return "";
}
}
};
return {
inputConfig: {
input: dtsOptions.entry,
onwarn(warning, handler) {
if (warning.code === "UNRESOLVED_IMPORT" || warning.code === "CIRCULAR_DEPENDENCY" || warning.code === "EMPTY_BUNDLE") {
return;
}
return handler(warning);
},
plugins: [
tsupCleanPlugin,
tsResolveOptions && tsResolvePlugin(tsResolveOptions),
json(),
ignoreFiles,
dtsPlugin.default({
tsconfig: options.tsconfig,
compilerOptions: {
...compilerOptions,
// Ensure ".d.ts" modules are generated
declaration: true,
// Skip ".js" generation
noEmit: false,
emitDeclarationOnly: true,
// Skip code generation when error occurs
noEmitOnError: true,
// Avoid extra work
checkJs: false,
declarationMap: false,
skipLibCheck: true,
preserveSymlinks: false,
// Ensure we can parse the latest code
target: _typescript2.default.ScriptTarget.ESNext
}
})
].filter(Boolean),
external: [
// Exclude dependencies, e.g. `lodash`, `lodash/get`
...deps.map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`)),
...options.external || []
]
},
outputConfig: options.format.map((format) => {
const outputExtension = _optionalChain([options, 'access', _53 => _53.outExtension, 'optionalCall', _54 => _54({ format, options, pkgType: pkg.type }), 'access', _55 => _55.dts]) || _chunkYQNCOY6Vjs.defaultOutExtension.call(void 0, { format, pkgType: pkg.type }).dts;
return {
dir: options.outDir || "dist",
format: "esm",
exports: "named",
banner: dtsOptions.banner,
footer: dtsOptions.footer,
entryFileNames: `[name]${outputExtension}`,
chunkFileNames: `[name]-[hash]${outputExtension}`,
plugins: [
format === "cjs" && options.cjsInterop && _rollup.FixDtsDefaultCjsExportsPlugin.call(void 0, )
].filter(Boolean)
};
})
};
};
async function runRollup(options) {
const { rollup } = await Promise.resolve().then(() => _interopRequireWildcard(require("rollup")));
try {
const start = Date.now();
const getDuration = () => {
return `${Math.floor(Date.now() - start)}ms`;
};
logger.info("dts", "Build start");
const bundle = await rollup(options.inputConfig);
const results = await Promise.all(options.outputConfig.map(bundle.write));
const outputs = results.flatMap((result) => result.output);
logger.success("dts", `\u26A1\uFE0F Build success in ${getDuration()}`);
_chunk6IOGQ2V3js.reportSize.call(void 0,
logger,
"dts",
outputs.reduce((res, info) => {
const name = _path2.default.relative(
process.cwd(),
_path2.default.join(options.outputConfig[0].dir || ".", info.fileName)
);
return {
...res,
[name]: info.type === "chunk" ? info.code.length : info.source.length
};
}, {})
);
} catch (error) {
_chunkJZ25TPTYjs.handleError.call(void 0, error);
logger.error("dts", "Build error");
}
}
async function watchRollup(options) {
const { watch } = await Promise.resolve().then(() => _interopRequireWildcard(require("rollup")));
watch({
...options.inputConfig,
plugins: options.inputConfig.plugins,
output: options.outputConfig
}).on("event", (event) => {
if (event.code === "START") {
logger.info("dts", "Build start");
} else if (event.code === "BUNDLE_END") {
logger.success("dts", `\u26A1\uFE0F Build success in ${event.duration}ms`);
_optionalChain([_worker_threads.parentPort, 'optionalAccess', _56 => _56.postMessage, 'call', _57 => _57("success")]);
} else if (event.code === "ERROR") {
logger.error("dts", "Build failed");
_chunkJZ25TPTYjs.handleError.call(void 0, event.error);
}
});
}
var startRollup = async (options) => {
const config = await getRollupConfig(options);
if (options.watch) {
watchRollup(config);
} else {
try {
await runRollup(config);
_optionalChain([_worker_threads.parentPort, 'optionalAccess', _58 => _58.postMessage, 'call', _59 => _59("success")]);
} catch (e9) {
_optionalChain([_worker_threads.parentPort, 'optionalAccess', _60 => _60.postMessage, 'call', _61 => _61("error")]);
}
}
};
_optionalChain([_worker_threads.parentPort, 'optionalAccess', _62 => _62.on, 'call', _63 => _63("message", (data) => {
logger.setName(data.configName);
const hasTypescript = _resolvefrom2.default.silent(process.cwd(), "typescript");
if (!hasTypescript) {
logger.error("dts", `You need to install "typescript" in your project`);
_optionalChain([_worker_threads.parentPort, 'optionalAccess', _64 => _64.postMessage, 'call', _65 => _65("error")]);
return;
}
startRollup(data.options);
})]);