Merge branch 'main' into starlight-ghostcms

This commit is contained in:
Adam Matthiesen 2024-02-20 04:31:40 -08:00 committed by GitHub
commit e71b924b9f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
276 changed files with 315575 additions and 625 deletions

View File

@ -1,6 +1,8 @@
name: "Changesets: Build Changesets for Dependabot"
on: pull_request
#on: pull_request
on:
workflow_dispatch:
permissions:
contents: write

View File

@ -0,0 +1,943 @@
import limit from 'p-limit';
import { getSafeTimers, isObject, createDefer, format, objDisplay, objectAttr, toArray, shuffle } from '@vitest/utils';
import { processError } from '@vitest/utils/error';
export { processError } from '@vitest/utils/error';
import { j as createChainable, g as generateHash, c as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, p as partitionSuiteChildren, h as hasTests, e as hasFailed } from './chunk-tasks.js';
import { relative } from 'pathe';
const fnMap = /* @__PURE__ */ new WeakMap();
const fixtureMap = /* @__PURE__ */ new WeakMap();
const hooksMap = /* @__PURE__ */ new WeakMap();
function setFn(key, fn) {
fnMap.set(key, fn);
}
function getFn(key) {
return fnMap.get(key);
}
function setFixture(key, fixture) {
fixtureMap.set(key, fixture);
}
function getFixture(key) {
return fixtureMap.get(key);
}
function setHooks(key, hooks) {
hooksMap.set(key, hooks);
}
function getHooks(key) {
return hooksMap.get(key);
}
class PendingError extends Error {
constructor(message, task) {
super(message);
this.message = message;
this.taskId = task.id;
}
code = "VITEST_PENDING";
taskId;
}
const collectorContext = {
tasks: [],
currentSuite: null
};
function collectTask(task) {
var _a;
(_a = collectorContext.currentSuite) == null ? void 0 : _a.tasks.push(task);
}
async function runWithSuite(suite, fn) {
const prev = collectorContext.currentSuite;
collectorContext.currentSuite = suite;
await fn();
collectorContext.currentSuite = prev;
}
function withTimeout(fn, timeout, isHook = false) {
if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY)
return fn;
const { setTimeout, clearTimeout } = getSafeTimers();
return (...args) => {
return Promise.race([fn(...args), new Promise((resolve, reject) => {
var _a;
const timer = setTimeout(() => {
clearTimeout(timer);
reject(new Error(makeTimeoutMsg(isHook, timeout)));
}, timeout);
(_a = timer.unref) == null ? void 0 : _a.call(timer);
})]);
};
}
function createTestContext(test, runner) {
var _a;
const context = function() {
throw new Error("done() callback is deprecated, use promise instead");
};
context.task = test;
context.skip = () => {
test.pending = true;
throw new PendingError("test is skipped; abort execution", test);
};
context.onTestFailed = (fn) => {
test.onFailed || (test.onFailed = []);
test.onFailed.push(fn);
};
context.onTestFinished = (fn) => {
test.onFinished || (test.onFinished = []);
test.onFinished.push(fn);
};
return ((_a = runner.extendTaskContext) == null ? void 0 : _a.call(runner, context)) || context;
}
function makeTimeoutMsg(isHook, timeout) {
return `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.
If this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
}
function mergeContextFixtures(fixtures, context = {}) {
const fixtureOptionKeys = ["auto"];
const fixtureArray = Object.entries(fixtures).map(([prop, value]) => {
const fixtureItem = { value };
if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) {
Object.assign(fixtureItem, value[1]);
fixtureItem.value = value[0];
}
fixtureItem.prop = prop;
fixtureItem.isFn = typeof fixtureItem.value === "function";
return fixtureItem;
});
if (Array.isArray(context.fixtures))
context.fixtures = context.fixtures.concat(fixtureArray);
else
context.fixtures = fixtureArray;
fixtureArray.forEach((fixture) => {
if (fixture.isFn) {
const usedProps = getUsedProps(fixture.value);
if (usedProps.length)
fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop));
}
});
return context;
}
const fixtureValueMaps = /* @__PURE__ */ new Map();
const cleanupFnArrayMap = /* @__PURE__ */ new Map();
async function callFixtureCleanup(context) {
const cleanupFnArray = cleanupFnArrayMap.get(context) ?? [];
for (const cleanup of cleanupFnArray.reverse())
await cleanup();
cleanupFnArrayMap.delete(context);
}
function withFixtures(fn, testContext) {
return (hookContext) => {
const context = hookContext || testContext;
if (!context)
return fn({});
const fixtures = getFixture(context);
if (!(fixtures == null ? void 0 : fixtures.length))
return fn(context);
const usedProps = getUsedProps(fn);
const hasAutoFixture = fixtures.some(({ auto }) => auto);
if (!usedProps.length && !hasAutoFixture)
return fn(context);
if (!fixtureValueMaps.get(context))
fixtureValueMaps.set(context, /* @__PURE__ */ new Map());
const fixtureValueMap = fixtureValueMaps.get(context);
if (!cleanupFnArrayMap.has(context))
cleanupFnArrayMap.set(context, []);
const cleanupFnArray = cleanupFnArrayMap.get(context);
const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop));
const pendingFixtures = resolveDeps(usedFixtures);
if (!pendingFixtures.length)
return fn(context);
async function resolveFixtures() {
for (const fixture of pendingFixtures) {
if (fixtureValueMap.has(fixture))
continue;
const resolvedValue = fixture.isFn ? await resolveFixtureFunction(fixture.value, context, cleanupFnArray) : fixture.value;
context[fixture.prop] = resolvedValue;
fixtureValueMap.set(fixture, resolvedValue);
cleanupFnArray.unshift(() => {
fixtureValueMap.delete(fixture);
});
}
}
return resolveFixtures().then(() => fn(context));
};
}
async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) {
const useFnArgPromise = createDefer();
let isUseFnArgResolved = false;
const fixtureReturn = fixtureFn(context, async (useFnArg) => {
isUseFnArgResolved = true;
useFnArgPromise.resolve(useFnArg);
const useReturnPromise = createDefer();
cleanupFnArray.push(async () => {
useReturnPromise.resolve();
await fixtureReturn;
});
await useReturnPromise;
}).catch((e) => {
if (!isUseFnArgResolved) {
useFnArgPromise.reject(e);
return;
}
throw e;
});
return useFnArgPromise;
}
function resolveDeps(fixtures, depSet = /* @__PURE__ */ new Set(), pendingFixtures = []) {
fixtures.forEach((fixture) => {
if (pendingFixtures.includes(fixture))
return;
if (!fixture.isFn || !fixture.deps) {
pendingFixtures.push(fixture);
return;
}
if (depSet.has(fixture))
throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`);
depSet.add(fixture);
resolveDeps(fixture.deps, depSet, pendingFixtures);
pendingFixtures.push(fixture);
depSet.clear();
});
return pendingFixtures;
}
function getUsedProps(fn) {
const match = fn.toString().match(/[^(]*\(([^)]*)/);
if (!match)
return [];
const args = splitByComma(match[1]);
if (!args.length)
return [];
const first = args[0];
if (!(first.startsWith("{") && first.endsWith("}")))
throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`);
const _first = first.slice(1, -1).replace(/\s/g, "");
const props = splitByComma(_first).map((prop) => {
return prop.replace(/\:.*|\=.*/g, "");
});
const last = props.at(-1);
if (last && last.startsWith("..."))
throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`);
return props;
}
function splitByComma(s) {
const result = [];
const stack = [];
let start = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "{" || s[i] === "[") {
stack.push(s[i] === "{" ? "}" : "]");
} else if (s[i] === stack[stack.length - 1]) {
stack.pop();
} else if (!stack.length && s[i] === ",") {
const token = s.substring(start, i).trim();
if (token)
result.push(token);
start = i + 1;
}
}
const lastToken = s.substring(start).trim();
if (lastToken)
result.push(lastToken);
return result;
}
let _test;
function setCurrentTest(test) {
_test = test;
}
function getCurrentTest() {
return _test;
}
const suite = createSuite();
const test = createTest(
function(name, optionsOrFn, optionsOrTest) {
if (getCurrentTest())
throw new Error('Calling the test function inside another test function is not allowed. Please put it inside "describe" or "suite" so it can be properly collected.');
getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
}
);
const describe = suite;
const it = test;
let runner;
let defaultSuite;
function getDefaultSuite() {
return defaultSuite;
}
function getRunner() {
return runner;
}
function clearCollectorContext(currentRunner) {
if (!defaultSuite)
defaultSuite = currentRunner.config.sequence.shuffle ? suite.shuffle("") : currentRunner.config.sequence.concurrent ? suite.concurrent("") : suite("");
runner = currentRunner;
collectorContext.tasks.length = 0;
defaultSuite.clear();
collectorContext.currentSuite = defaultSuite;
}
function getCurrentSuite() {
return collectorContext.currentSuite || defaultSuite;
}
function createSuiteHooks() {
return {
beforeAll: [],
afterAll: [],
beforeEach: [],
afterEach: []
};
}
function parseArguments(optionsOrFn, optionsOrTest) {
let options = {};
let fn = () => {
};
if (typeof optionsOrTest === "object") {
if (typeof optionsOrFn === "object")
throw new TypeError("Cannot use two objects as arguments. Please provide options and a function callback in that order.");
options = optionsOrTest;
} else if (typeof optionsOrTest === "number") {
options = { timeout: optionsOrTest };
} else if (typeof optionsOrFn === "object") {
options = optionsOrFn;
}
if (typeof optionsOrFn === "function") {
if (typeof optionsOrTest === "function")
throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
fn = optionsOrFn;
} else if (typeof optionsOrTest === "function") {
fn = optionsOrTest;
}
return {
options,
handler: fn
};
}
function createSuiteCollector(name, factory = () => {
}, mode, shuffle, each, suiteOptions) {
const tasks = [];
const factoryQueue = [];
let suite2;
initSuite();
const task = function(name2 = "", options = {}) {
const task2 = {
id: "",
name: name2,
suite: void 0,
each: options.each,
fails: options.fails,
context: void 0,
type: "custom",
retry: options.retry ?? runner.config.retry,
repeats: options.repeats,
mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
meta: options.meta ?? /* @__PURE__ */ Object.create(null)
};
const handler = options.handler;
if (options.concurrent || !options.sequential && runner.config.sequence.concurrent)
task2.concurrent = true;
if (shuffle)
task2.shuffle = true;
const context = createTestContext(task2, runner);
Object.defineProperty(task2, "context", {
value: context,
enumerable: false
});
setFixture(context, options.fixtures);
if (handler) {
setFn(task2, withTimeout(
withFixtures(handler, context),
(options == null ? void 0 : options.timeout) ?? runner.config.testTimeout
));
}
tasks.push(task2);
return task2;
};
const test2 = createTest(function(name2, optionsOrFn, optionsOrTest) {
let { options, handler } = parseArguments(
optionsOrFn,
optionsOrTest
);
if (typeof suiteOptions === "object")
options = Object.assign({}, suiteOptions, options);
options.concurrent = this.concurrent || !this.sequential && (options == null ? void 0 : options.concurrent);
options.sequential = this.sequential || !this.concurrent && (options == null ? void 0 : options.sequential);
const test3 = task(
formatName(name2),
{ ...this, ...options, handler }
);
test3.type = "test";
});
const collector = {
type: "collector",
name,
mode,
options: suiteOptions,
test: test2,
tasks,
collect,
task,
clear,
on: addHook
};
function addHook(name2, ...fn) {
getHooks(suite2)[name2].push(...fn);
}
function initSuite() {
if (typeof suiteOptions === "number")
suiteOptions = { timeout: suiteOptions };
suite2 = {
id: "",
type: "suite",
name,
mode,
each,
shuffle,
tasks: [],
meta: /* @__PURE__ */ Object.create(null),
projectName: ""
};
setHooks(suite2, createSuiteHooks());
}
function clear() {
tasks.length = 0;
factoryQueue.length = 0;
initSuite();
}
async function collect(file) {
factoryQueue.length = 0;
if (factory)
await runWithSuite(collector, () => factory(test2));
const allChildren = [];
for (const i of [...factoryQueue, ...tasks])
allChildren.push(i.type === "collector" ? await i.collect(file) : i);
suite2.file = file;
suite2.tasks = allChildren;
allChildren.forEach((task2) => {
task2.suite = suite2;
if (file)
task2.file = file;
});
return suite2;
}
collectTask(collector);
return collector;
}
function createSuite() {
function suiteFn(name, factoryOrOptions, optionsOrFactory = {}) {
const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
const currentSuite = getCurrentSuite();
let { options, handler: factory } = parseArguments(
factoryOrOptions,
optionsOrFactory
);
if (currentSuite == null ? void 0 : currentSuite.options)
options = { ...currentSuite.options, ...options };
options.concurrent = this.concurrent || !this.sequential && (options == null ? void 0 : options.concurrent);
options.sequential = this.sequential || !this.concurrent && (options == null ? void 0 : options.sequential);
return createSuiteCollector(formatName(name), factory, mode, this.shuffle, this.each, options);
}
suiteFn.each = function(cases, ...args) {
const suite2 = this.withContext();
this.setContext("each", true);
if (Array.isArray(cases) && args.length)
cases = formatTemplateString(cases, args);
return (name, optionsOrFn, fnOrOptions) => {
const _name = formatName(name);
const arrayOnlyCases = cases.every(Array.isArray);
const { options, handler } = parseArguments(
optionsOrFn,
fnOrOptions
);
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i];
arrayOnlyCases ? suite2(formatTitle(_name, items, idx), options, () => handler(...items)) : suite2(formatTitle(_name, items, idx), options, () => handler(i));
});
this.setContext("each", void 0);
};
};
suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
suiteFn.runIf = (condition) => condition ? suite : suite.skip;
return createChainable(
["concurrent", "sequential", "shuffle", "skip", "only", "todo"],
suiteFn
);
}
function createTaskCollector(fn, context) {
const taskFn = fn;
taskFn.each = function(cases, ...args) {
const test2 = this.withContext();
this.setContext("each", true);
if (Array.isArray(cases) && args.length)
cases = formatTemplateString(cases, args);
return (name, optionsOrFn, fnOrOptions) => {
const _name = formatName(name);
const arrayOnlyCases = cases.every(Array.isArray);
const { options, handler } = parseArguments(
optionsOrFn,
fnOrOptions
);
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i];
arrayOnlyCases ? test2(formatTitle(_name, items, idx), options, () => handler(...items)) : test2(formatTitle(_name, items, idx), options, () => handler(i));
});
this.setContext("each", void 0);
};
};
taskFn.skipIf = function(condition) {
return condition ? this.skip : this;
};
taskFn.runIf = function(condition) {
return condition ? this : this.skip;
};
taskFn.extend = function(fixtures) {
const _context = mergeContextFixtures(fixtures, context);
return createTest(function fn2(name, optionsOrFn, optionsOrTest) {
getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
}, _context);
};
const _test = createChainable(
["concurrent", "sequential", "skip", "only", "todo", "fails"],
taskFn
);
if (context)
_test.mergeContext(context);
return _test;
}
function createTest(fn, context) {
return createTaskCollector(fn, context);
}
function formatName(name) {
return typeof name === "string" ? name : name instanceof Function ? name.name || "<anonymous>" : String(name);
}
function formatTitle(template, items, idx) {
if (template.includes("%#")) {
template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/__vitest_escaped_%__/g, "%%");
}
const count = template.split("%").length - 1;
let formatted = format(template, ...items.slice(0, count));
if (isObject(items[0])) {
formatted = formatted.replace(
/\$([$\w_.]+)/g,
// https://github.com/chaijs/chai/pull/1490
(_, key) => {
var _a, _b;
return objDisplay(objectAttr(items[0], key), { truncate: (_b = (_a = runner == null ? void 0 : runner.config) == null ? void 0 : _a.chaiConfig) == null ? void 0 : _b.truncateThreshold });
}
);
}
return formatted;
}
function formatTemplateString(cases, args) {
const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
const res = [];
for (let i = 0; i < Math.floor(args.length / header.length); i++) {
const oneCase = {};
for (let j = 0; j < header.length; j++)
oneCase[header[j]] = args[i * header.length + j];
res.push(oneCase);
}
return res;
}
async function runSetupFiles(config, runner) {
const files = toArray(config.setupFiles);
if (config.sequence.setupFiles === "parallel") {
await Promise.all(
files.map(async (fsPath) => {
await runner.importFile(fsPath, "setup");
})
);
} else {
for (const fsPath of files)
await runner.importFile(fsPath, "setup");
}
}
const now$1 = Date.now;
async function collectTests(paths, runner) {
const files = [];
const config = runner.config;
for (const filepath of paths) {
const path = relative(config.root, filepath);
const file = {
id: generateHash(`${path}${config.name || ""}`),
name: path,
type: "suite",
mode: "run",
filepath,
tasks: [],
meta: /* @__PURE__ */ Object.create(null),
projectName: config.name
};
clearCollectorContext(runner);
try {
const setupStart = now$1();
await runSetupFiles(config, runner);
const collectStart = now$1();
file.setupDuration = collectStart - setupStart;
await runner.importFile(filepath, "collect");
const defaultTasks = await getDefaultSuite().collect(file);
setHooks(file, getHooks(defaultTasks));
for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
if (c.type === "test") {
file.tasks.push(c);
} else if (c.type === "custom") {
file.tasks.push(c);
} else if (c.type === "suite") {
file.tasks.push(c);
} else if (c.type === "collector") {
const suite = await c.collect(file);
if (suite.name || suite.tasks.length)
file.tasks.push(suite);
}
}
file.collectDuration = now$1() - collectStart;
} catch (e) {
const error = processError(e);
file.result = {
state: "fail",
errors: [error]
};
}
calculateSuiteHash(file);
const hasOnlyTasks = someTasksAreOnly(file);
interpretTaskModes(file, config.testNamePattern, hasOnlyTasks, false, config.allowOnly);
files.push(file);
}
return files;
}
const now = Date.now;
function updateSuiteHookState(suite, name, state, runner) {
var _a;
if (!suite.result)
suite.result = { state: "run" };
if (!((_a = suite.result) == null ? void 0 : _a.hooks))
suite.result.hooks = {};
const suiteHooks = suite.result.hooks;
if (suiteHooks) {
suiteHooks[name] = state;
updateTask(suite, runner);
}
}
function getSuiteHooks(suite, name, sequence) {
const hooks = getHooks(suite)[name];
if (sequence === "stack" && (name === "afterAll" || name === "afterEach"))
return hooks.slice().reverse();
return hooks;
}
async function callSuiteHook(suite, currentTask, name, runner, args) {
const sequence = runner.config.sequence.hooks;
const callbacks = [];
if (name === "beforeEach" && suite.suite) {
callbacks.push(
...await callSuiteHook(suite.suite, currentTask, name, runner, args)
);
}
updateSuiteHookState(currentTask, name, "run", runner);
const hooks = getSuiteHooks(suite, name, sequence);
if (sequence === "parallel") {
callbacks.push(...await Promise.all(hooks.map((fn) => fn(...args))));
} else {
for (const hook of hooks)
callbacks.push(await hook(...args));
}
updateSuiteHookState(currentTask, name, "pass", runner);
if (name === "afterEach" && suite.suite) {
callbacks.push(
...await callSuiteHook(suite.suite, currentTask, name, runner, args)
);
}
return callbacks;
}
const packs = /* @__PURE__ */ new Map();
let updateTimer;
let previousUpdate;
function updateTask(task, runner) {
packs.set(task.id, [task.result, task.meta]);
const { clearTimeout, setTimeout } = getSafeTimers();
clearTimeout(updateTimer);
updateTimer = setTimeout(() => {
previousUpdate = sendTasksUpdate(runner);
}, 10);
}
async function sendTasksUpdate(runner) {
var _a;
const { clearTimeout } = getSafeTimers();
clearTimeout(updateTimer);
await previousUpdate;
if (packs.size) {
const taskPacks = Array.from(packs).map(([id, task]) => {
return [
id,
task[0],
task[1]
];
});
const p = (_a = runner.onTaskUpdate) == null ? void 0 : _a.call(runner, taskPacks);
packs.clear();
return p;
}
}
async function callCleanupHooks(cleanups) {
await Promise.all(cleanups.map(async (fn) => {
if (typeof fn !== "function")
return;
await fn();
}));
}
async function runTest(test, runner) {
var _a, _b, _c, _d, _e, _f, _g, _h;
await ((_a = runner.onBeforeRunTask) == null ? void 0 : _a.call(runner, test));
if (test.mode !== "run")
return;
if (((_b = test.result) == null ? void 0 : _b.state) === "fail") {
updateTask(test, runner);
return;
}
const start = now();
test.result = {
state: "run",
startTime: start,
retryCount: 0
};
updateTask(test, runner);
setCurrentTest(test);
const repeats = test.repeats ?? 0;
for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) {
const retry = test.retry ?? 0;
for (let retryCount = 0; retryCount <= retry; retryCount++) {
let beforeEachCleanups = [];
try {
await ((_c = runner.onBeforeTryTask) == null ? void 0 : _c.call(runner, test, { retry: retryCount, repeats: repeatCount }));
test.result.repeatCount = repeatCount;
beforeEachCleanups = await callSuiteHook(test.suite, test, "beforeEach", runner, [test.context, test.suite]);
if (runner.runTask) {
await runner.runTask(test);
} else {
const fn = getFn(test);
if (!fn)
throw new Error("Test function is not found. Did you add it using `setFn`?");
await fn();
}
if (test.promises) {
const result = await Promise.allSettled(test.promises);
const errors = result.map((r) => r.status === "rejected" ? r.reason : void 0).filter(Boolean);
if (errors.length)
throw errors;
}
await ((_d = runner.onAfterTryTask) == null ? void 0 : _d.call(runner, test, { retry: retryCount, repeats: repeatCount }));
if (test.result.state !== "fail") {
if (!test.repeats)
test.result.state = "pass";
else if (test.repeats && retry === retryCount)
test.result.state = "pass";
}
} catch (e) {
failTask(test.result, e, runner.config.diffOptions);
}
if (test.pending || ((_e = test.result) == null ? void 0 : _e.state) === "skip") {
test.mode = "skip";
test.result = { state: "skip" };
updateTask(test, runner);
setCurrentTest(void 0);
return;
}
try {
await callSuiteHook(test.suite, test, "afterEach", runner, [test.context, test.suite]);
await callCleanupHooks(beforeEachCleanups);
await callFixtureCleanup(test.context);
} catch (e) {
failTask(test.result, e, runner.config.diffOptions);
}
if (test.result.state === "pass")
break;
if (retryCount < retry) {
test.result.state = "run";
test.result.retryCount = (test.result.retryCount ?? 0) + 1;
}
updateTask(test, runner);
}
}
try {
await Promise.all(((_f = test.onFinished) == null ? void 0 : _f.map((fn) => fn(test.result))) || []);
} catch (e) {
failTask(test.result, e, runner.config.diffOptions);
}
if (test.result.state === "fail") {
try {
await Promise.all(((_g = test.onFailed) == null ? void 0 : _g.map((fn) => fn(test.result))) || []);
} catch (e) {
failTask(test.result, e, runner.config.diffOptions);
}
}
if (test.fails) {
if (test.result.state === "pass") {
const error = processError(new Error("Expect test to fail"));
test.result.state = "fail";
test.result.errors = [error];
} else {
test.result.state = "pass";
test.result.errors = void 0;
}
}
setCurrentTest(void 0);
test.result.duration = now() - start;
await ((_h = runner.onAfterRunTask) == null ? void 0 : _h.call(runner, test));
updateTask(test, runner);
}
function failTask(result, err, diffOptions) {
if (err instanceof PendingError) {
result.state = "skip";
return;
}
result.state = "fail";
const errors = Array.isArray(err) ? err : [err];
for (const e of errors) {
const error = processError(e, diffOptions);
result.errors ?? (result.errors = []);
result.errors.push(error);
}
}
function markTasksAsSkipped(suite, runner) {
suite.tasks.forEach((t) => {
t.mode = "skip";
t.result = { ...t.result, state: "skip" };
updateTask(t, runner);
if (t.type === "suite")
markTasksAsSkipped(t, runner);
});
}
async function runSuite(suite, runner) {
var _a, _b, _c, _d;
await ((_a = runner.onBeforeRunSuite) == null ? void 0 : _a.call(runner, suite));
if (((_b = suite.result) == null ? void 0 : _b.state) === "fail") {
markTasksAsSkipped(suite, runner);
updateTask(suite, runner);
return;
}
const start = now();
suite.result = {
state: "run",
startTime: start
};
updateTask(suite, runner);
let beforeAllCleanups = [];
if (suite.mode === "skip") {
suite.result.state = "skip";
} else if (suite.mode === "todo") {
suite.result.state = "todo";
} else {
try {
beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", runner, [suite]);
if (runner.runSuite) {
await runner.runSuite(suite);
} else {
for (let tasksGroup of partitionSuiteChildren(suite)) {
if (tasksGroup[0].concurrent === true) {
const mutex = limit(runner.config.maxConcurrency);
await Promise.all(tasksGroup.map((c) => mutex(() => runSuiteChild(c, runner))));
} else {
const { sequence } = runner.config;
if (sequence.shuffle || suite.shuffle) {
const suites = tasksGroup.filter((group) => group.type === "suite");
const tests = tasksGroup.filter((group) => group.type === "test");
const groups = shuffle([suites, tests], sequence.seed);
tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed));
}
for (const c of tasksGroup)
await runSuiteChild(c, runner);
}
}
}
} catch (e) {
failTask(suite.result, e, runner.config.diffOptions);
}
try {
await callSuiteHook(suite, suite, "afterAll", runner, [suite]);
await callCleanupHooks(beforeAllCleanups);
} catch (e) {
failTask(suite.result, e, runner.config.diffOptions);
}
if (suite.mode === "run") {
if (!runner.config.passWithNoTests && !hasTests(suite)) {
suite.result.state = "fail";
if (!((_c = suite.result.errors) == null ? void 0 : _c.length)) {
const error = processError(new Error(`No test found in suite ${suite.name}`));
suite.result.errors = [error];
}
} else if (hasFailed(suite)) {
suite.result.state = "fail";
} else {
suite.result.state = "pass";
}
}
updateTask(suite, runner);
suite.result.duration = now() - start;
await ((_d = runner.onAfterRunSuite) == null ? void 0 : _d.call(runner, suite));
}
}
async function runSuiteChild(c, runner) {
if (c.type === "test" || c.type === "custom")
return runTest(c, runner);
else if (c.type === "suite")
return runSuite(c, runner);
}
async function runFiles(files, runner) {
var _a, _b;
for (const file of files) {
if (!file.tasks.length && !runner.config.passWithNoTests) {
if (!((_b = (_a = file.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.length)) {
const error = processError(new Error(`No test suite found in file ${file.filepath}`));
file.result = {
state: "fail",
errors: [error]
};
}
}
await runSuite(file, runner);
}
}
async function startTests(paths, runner) {
var _a, _b, _c, _d;
await ((_a = runner.onBeforeCollect) == null ? void 0 : _a.call(runner, paths));
const files = await collectTests(paths, runner);
(_b = runner.onCollected) == null ? void 0 : _b.call(runner, files);
await ((_c = runner.onBeforeRunFiles) == null ? void 0 : _c.call(runner, files));
await runFiles(files, runner);
await ((_d = runner.onAfterRunFiles) == null ? void 0 : _d.call(runner, files));
await sendTasksUpdate(runner);
return files;
}
function getDefaultHookTimeout() {
return getRunner().config.hookTimeout;
}
function beforeAll(fn, timeout) {
return getCurrentSuite().on("beforeAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true));
}
function afterAll(fn, timeout) {
return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true));
}
function beforeEach(fn, timeout) {
return getCurrentSuite().on("beforeEach", withTimeout(withFixtures(fn), timeout ?? getDefaultHookTimeout(), true));
}
function afterEach(fn, timeout) {
return getCurrentSuite().on("afterEach", withTimeout(withFixtures(fn), timeout ?? getDefaultHookTimeout(), true));
}
const onTestFailed = createTestHook("onTestFailed", (test, handler) => {
test.onFailed || (test.onFailed = []);
test.onFailed.push(handler);
});
const onTestFinished = createTestHook("onTestFinished", (test, handler) => {
test.onFinished || (test.onFinished = []);
test.onFinished.push(handler);
});
function createTestHook(name, handler) {
return (fn) => {
const current = getCurrentTest();
if (!current)
throw new Error(`Hook ${name}() can only be called inside a test`);
return handler(current, fn);
};
}
export { afterAll, afterEach, beforeAll, beforeEach, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, setFn, setHooks, startTests, suite, test, updateTask };

View File

@ -0,0 +1,22 @@
{
"name": "@rollup/rollup-linux-x64-gnu",
"version": "4.12.0",
"os": [
"linux"
],
"cpu": [
"x64"
],
"files": [
"rollup.linux-x64-gnu.node"
],
"description": "Native bindings for Rollup",
"author": "Lukas Taegert-Atkinson",
"homepage": "https://rollupjs.org/",
"license": "MIT",
"repository": "rollup/rollup",
"libc": [
"glibc"
],
"main": "./rollup.linux-x64-gnu.node"
}

View File

@ -0,0 +1,33 @@
import { VitestRunner } from './types.js';
export { CancelReason, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource } from './types.js';
import { T as Task, F as File, d as SuiteAPI, e as TestAPI, f as SuiteCollector, g as CustomAPI, h as SuiteHooks, O as OnTestFailedHandler, i as OnTestFinishedHandler, a as Test, C as Custom, S as Suite } from './tasks-_kyNRBhz.js';
export { D as DoneCallback, E as ExtendedContext, t as Fixture, s as FixtureFn, r as FixtureOptions, u as Fixtures, v as HookCleanupCallback, H as HookListener, I as InferFixturesTypes, R as RunMode, y as RuntimeContext, B as SequenceHooks, G as SequenceSetupFiles, x as SuiteFactory, k as TaskBase, A as TaskContext, w as TaskCustomOptions, m as TaskMeta, l as TaskPopulated, n as TaskResult, o as TaskResultPack, j as TaskState, z as TestContext, p as TestFunction, q as TestOptions, U as Use } from './tasks-_kyNRBhz.js';
import { Awaitable } from '@vitest/utils';
export { processError } from '@vitest/utils/error';
import '@vitest/utils/diff';
declare function updateTask(task: Task, runner: VitestRunner): void;
declare function startTests(paths: string[], runner: VitestRunner): Promise<File[]>;
declare const suite: SuiteAPI;
declare const test: TestAPI;
declare const describe: SuiteAPI;
declare const it: TestAPI;
declare function getCurrentSuite<ExtraContext = {}>(): SuiteCollector<ExtraContext>;
declare function createTaskCollector(fn: (...args: any[]) => any, context?: Record<string, unknown>): CustomAPI;
declare function beforeAll(fn: SuiteHooks['beforeAll'][0], timeout?: number): void;
declare function afterAll(fn: SuiteHooks['afterAll'][0], timeout?: number): void;
declare function beforeEach<ExtraContext = {}>(fn: SuiteHooks<ExtraContext>['beforeEach'][0], timeout?: number): void;
declare function afterEach<ExtraContext = {}>(fn: SuiteHooks<ExtraContext>['afterEach'][0], timeout?: number): void;
declare const onTestFailed: (fn: OnTestFailedHandler) => void;
declare const onTestFinished: (fn: OnTestFinishedHandler) => void;
declare function setFn(key: Test | Custom, fn: (() => Awaitable<void>)): void;
declare function getFn<Task = Test | Custom>(key: Task): (() => Awaitable<void>);
declare function setHooks(key: Suite, hooks: SuiteHooks): void;
declare function getHooks(key: Suite): SuiteHooks;
declare function getCurrentTest<T extends Test | Custom | undefined>(): T;
export { Custom, CustomAPI, File, OnTestFailedHandler, OnTestFinishedHandler, Suite, SuiteAPI, SuiteCollector, SuiteHooks, Task, Test, TestAPI, VitestRunner, afterAll, afterEach, beforeAll, beforeEach, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, setFn, setHooks, startTests, suite, test, updateTask };

View File

@ -0,0 +1 @@
{"files":{"dist/index.js":{"checkedAt":1708389320583,"integrity":"sha512-0kfv/XwgTPS6RyTL5LIFATgQuRD5jYMCdTx7E8nZXsVKlDXgjxXiVp+GGLNrSv7vYnplmk9k50iJzI4avpZ8kQ==","mode":420,"size":3831},"README.md":{"checkedAt":1708389320583,"integrity":"sha512-YgFkqdxPqbLCzh8GS6hPgLDlcZeiqSNZJZdjRo6aUxmM1uuqzOEPC/KDWSVXjvnKbnab3ZQqQqLh7h6MAW2xcg==","mode":420,"size":63},"dist/index.d.ts":{"checkedAt":1708389320584,"integrity":"sha512-ipbREd2PW+AxybhnhFXhjmAZPHKt+uwEIUa4W5ZW82fGWmyxgIbtQ5/an5YTisOCtnoBX3YFi6+4LM67dSP81Q==","mode":420,"size":12089},"LICENSE":{"checkedAt":1708389320584,"integrity":"sha512-UVFpfPJvKX+pFZi9kICLGeKXa7aMp5oeTmTQJBxCYHGrecls8D80KYY+DoSbK71Xw3IjeSGb/B31WXPYaplODw==","mode":420,"size":1177},"package.json":{"checkedAt":1708389320584,"integrity":"sha512-g08RLzXH6/OD46xcTcFsCjtVvg8qj/77USRH+M/C534iJ02tc0ZJt52k166NxGxKNmhbG5t327DsX/7u3bshhQ==","mode":420,"size":909}}}

View File

@ -0,0 +1,30 @@
export { c as createForksRpcOptions, a as createThreadsRpcOptions, u as unwrapForksConfig } from './vendor/utils.GbToHGHI.js';
export { p as provideWorkerState } from './vendor/global.CkGT_TMy.js';
export { run as runVitestWorker } from './worker.js';
export { r as runVmTests } from './vendor/vm.UmCkcXp-.js';
export { r as runBaseTests } from './vendor/base.RpormaJz.js';
import '@vitest/utils';
import 'node:url';
import 'tinypool';
import 'vite-node/client';
import 'pathe';
import './vendor/index.GVFv9dZ0.js';
import 'node:console';
import './vendor/base.knFzp7G3.js';
import 'node:module';
import './vendor/rpc.joBhAkyK.js';
import './vendor/index.8bPxjt7g.js';
import 'node:vm';
import './chunks/runtime-console.Iloo9fIt.js';
import 'node:stream';
import 'node:path';
import './vendor/date.Ns1pGd_X.js';
import './vendor/execute.aFSzc0Da.js';
import 'vite-node/utils';
import '@vitest/utils/error';
import './path.js';
import 'node:fs';
import 'vite-node/constants';
import './vendor/index.ir9i0ywP.js';
import 'std-env';
import '@vitest/runner/utils';

View File

@ -0,0 +1,16 @@
export { createTaskCollector, getCurrentSuite, getFn, getHooks, setFn, setHooks } from '@vitest/runner';
export { createChainable } from '@vitest/runner/utils';
export { g as getBenchFn, a as getBenchOptions } from './suite-xGC-mxBC.js';
import './reporters-QGe8gs4b.js';
import 'vite';
import 'vite-node';
import '@vitest/snapshot';
import '@vitest/expect';
import '@vitest/utils';
import 'tinybench';
import 'vite-node/client';
import '@vitest/snapshot/manager';
import 'vite-node/server';
import 'node:worker_threads';
import 'node:fs';
import 'chai';

View File

@ -0,0 +1,43 @@
import { readUInt16LE } from "./utils.js";
const TYPE_ICON = 1;
const SIZE_HEADER = 2 + 2 + 2;
const SIZE_IMAGE_ENTRY = 1 + 1 + 1 + 1 + 2 + 2 + 4 + 4;
function getSizeFromOffset(input, offset) {
const value = input[offset];
return value === 0 ? 256 : value;
}
function getImageSize(input, imageIndex) {
const offset = SIZE_HEADER + imageIndex * SIZE_IMAGE_ENTRY;
return {
height: getSizeFromOffset(input, offset + 1),
width: getSizeFromOffset(input, offset)
};
}
const ICO = {
validate(input) {
const reserved = readUInt16LE(input, 0);
const imageCount = readUInt16LE(input, 4);
if (reserved !== 0 || imageCount === 0)
return false;
const imageType = readUInt16LE(input, 2);
return imageType === TYPE_ICON;
},
calculate(input) {
const nbImages = readUInt16LE(input, 4);
const imageSize = getImageSize(input, 0);
if (nbImages === 1)
return imageSize;
const imgs = [imageSize];
for (let imageIndex = 1; imageIndex < nbImages; imageIndex += 1) {
imgs.push(getImageSize(input, imageIndex));
}
return {
height: imageSize.height,
images: imgs,
width: imageSize.width
};
}
};
export {
ICO
};

View File

@ -0,0 +1,56 @@
import { extname } from "node:path";
function extendManualChunks(outputOptions, hooks) {
const manualChunks = outputOptions.manualChunks;
outputOptions.manualChunks = function(id, meta) {
if (hooks.before) {
let value = hooks.before(id, meta);
if (value) {
return value;
}
}
if (typeof manualChunks == "object") {
if (id in manualChunks) {
let value = manualChunks[id];
return value[0];
}
} else if (typeof manualChunks === "function") {
const outid = manualChunks.call(this, id, meta);
if (outid) {
return outid;
}
}
if (hooks.after) {
return hooks.after(id, meta) || null;
}
return null;
};
}
const ASTRO_PAGE_EXTENSION_POST_PATTERN = "@_@";
function getVirtualModulePageNameFromPath(virtualModulePrefix, path) {
const extension = extname(path);
return `${virtualModulePrefix}${path.replace(
extension,
extension.replace(".", ASTRO_PAGE_EXTENSION_POST_PATTERN)
)}`;
}
function getPathFromVirtualModulePageName(virtualModulePrefix, id) {
const pageName = id.slice(virtualModulePrefix.length);
return pageName.replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, ".");
}
function shouldInlineAsset(assetContent, assetPath, assetsInlineLimit) {
if (typeof assetsInlineLimit === "number") {
return Buffer.byteLength(assetContent) < assetsInlineLimit;
}
const result = assetsInlineLimit(assetPath, Buffer.from(assetContent));
if (result != null) {
return result;
}
return Buffer.byteLength(assetContent) < 4096;
}
export {
ASTRO_PAGE_EXTENSION_POST_PATTERN,
extendManualChunks,
getPathFromVirtualModulePageName,
getVirtualModulePageNameFromPath,
shouldInlineAsset
};

View File

@ -0,0 +1,64 @@
/*
@license
Rollup.js v4.12.0
Fri, 16 Feb 2024 13:31:42 GMT - commit 0146b84be33a8416b4df4b9382549a7ca19dd64a
https://github.com/rollup/rollup
Released under the MIT License.
*/
const getLogFilter = filters => {
if (filters.length === 0)
return () => true;
const normalizedFilters = filters.map(filter => filter.split('&').map(subFilter => {
const inverted = subFilter.startsWith('!');
if (inverted)
subFilter = subFilter.slice(1);
const [key, ...value] = subFilter.split(':');
return { inverted, key: key.split('.'), parts: value.join(':').split('*') };
}));
return (log) => {
nextIntersectedFilter: for (const intersectedFilters of normalizedFilters) {
for (const { inverted, key, parts } of intersectedFilters) {
const isFilterSatisfied = testFilter(log, key, parts);
if (inverted ? isFilterSatisfied : !isFilterSatisfied) {
continue nextIntersectedFilter;
}
}
return true;
}
return false;
};
};
const testFilter = (log, key, parts) => {
let rawValue = log;
for (let index = 0; index < key.length; index++) {
if (!rawValue) {
return false;
}
const part = key[index];
if (!(part in rawValue)) {
return false;
}
rawValue = rawValue[part];
}
let value = typeof rawValue === 'object' ? JSON.stringify(rawValue) : String(rawValue);
if (parts.length === 1) {
return value === parts[0];
}
if (!value.startsWith(parts[0])) {
return false;
}
const lastPartIndex = parts.length - 1;
for (let index = 1; index < lastPartIndex; index++) {
const part = parts[index];
const position = value.indexOf(part);
if (position === -1) {
return false;
}
value = value.slice(position + part.length);
}
return value.endsWith(parts[lastPartIndex]);
};
export { getLogFilter };

View File

@ -0,0 +1,62 @@
{
"name": "strip-literal",
"version": "2.0.0",
"packageManager": "pnpm@8.13.1",
"description": "Strip comments and string literals from JavaScript code",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/strip-literal#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu/strip-literal.git"
},
"bugs": {
"url": "https://github.com/antfu/strip-literal/issues"
},
"keywords": [],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"dev": "unbuild --stub",
"lint": "eslint .",
"prepublishOnly": "nr build",
"release": "bumpp --commit --push --tag && npm publish",
"start": "esmo src/index.ts",
"test": "vitest",
"bench": "vitest bench",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"js-tokens": "^8.0.2"
},
"devDependencies": {
"@antfu/eslint-config": "^2.6.1",
"@antfu/ni": "^0.21.12",
"@types/node": "^20.10.5",
"bumpp": "^9.2.1",
"eslint": "^8.56.0",
"esmo": "^4.0.0",
"pnpm": "^8.13.1",
"rimraf": "^5.0.5",
"three": "^0.160.0",
"typescript": "^5.3.3",
"unbuild": "^2.0.0",
"vite": "^5.0.10",
"vitest": "^1.1.0",
"vue": "^3.4.0"
}
}

View File

@ -0,0 +1,276 @@
import { ErrorWithDiff, Awaitable } from '@vitest/utils';
type ChainableFunction<T extends string, F extends (...args: any) => any, C = {}> = F & {
[x in T]: ChainableFunction<T, F, C>;
} & {
fn: (this: Record<T, any>, ...args: Parameters<F>) => ReturnType<F>;
} & C;
declare function createChainable<T extends string, Args extends any[], R = any>(keys: T[], fn: (this: Record<T, any>, ...args: Args) => R): ChainableFunction<T, (...args: Args) => R>;
interface FixtureItem extends FixtureOptions {
prop: string;
value: any;
/**
* Indicates whether the fixture is a function
*/
isFn: boolean;
/**
* The dependencies(fixtures) of current fixture function.
*/
deps?: FixtureItem[];
}
type RunMode = 'run' | 'skip' | 'only' | 'todo';
type TaskState = RunMode | 'pass' | 'fail';
interface TaskBase {
id: string;
name: string;
mode: RunMode;
meta: TaskMeta;
each?: boolean;
concurrent?: boolean;
shuffle?: boolean;
suite?: Suite;
file?: File;
result?: TaskResult;
retry?: number;
repeats?: number;
}
interface TaskPopulated extends TaskBase {
suite: Suite;
pending?: boolean;
result?: TaskResult;
fails?: boolean;
onFailed?: OnTestFailedHandler[];
onFinished?: OnTestFinishedHandler[];
/**
* Store promises (from async expects) to wait for them before finishing the test
*/
promises?: Promise<any>[];
}
interface TaskMeta {
}
interface TaskResult {
state: TaskState;
duration?: number;
startTime?: number;
heap?: number;
errors?: ErrorWithDiff[];
htmlError?: string;
hooks?: Partial<Record<keyof SuiteHooks, TaskState>>;
retryCount?: number;
repeatCount?: number;
}
type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta];
interface Suite extends TaskBase {
type: 'suite';
tasks: Task[];
filepath?: string;
projectName: string;
}
interface File extends Suite {
filepath: string;
collectDuration?: number;
setupDuration?: number;
}
interface Test<ExtraContext = {}> extends TaskPopulated {
type: 'test';
context: TaskContext<Test> & ExtraContext & TestContext;
}
interface Custom<ExtraContext = {}> extends TaskPopulated {
type: 'custom';
context: TaskContext<Custom> & ExtraContext & TestContext;
}
type Task = Test | Suite | Custom | File;
type DoneCallback = (error?: any) => void;
type TestFunction<ExtraContext = {}> = (context: ExtendedContext<Test> & ExtraContext) => Awaitable<any> | void;
type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
1: [T[0]];
2: [T[0], T[1]];
3: [T[0], T[1], T[2]];
4: [T[0], T[1], T[2], T[3]];
5: [T[0], T[1], T[2], T[3], T[4]];
6: [T[0], T[1], T[2], T[3], T[4], T[5]];
7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
}[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : 'fallback'];
interface EachFunctionReturn<T extends any[]> {
/**
* @deprecated Use options as the second argument instead
*/
(name: string | Function, fn: (...args: T) => Awaitable<void>, options: TestOptions): void;
(name: string | Function, fn: (...args: T) => Awaitable<void>, options?: number | TestOptions): void;
(name: string | Function, options: TestOptions, fn: (...args: T) => Awaitable<void>): void;
}
interface TestEachFunction {
<T extends any[] | [any]>(cases: ReadonlyArray<T>): EachFunctionReturn<T>;
<T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): EachFunctionReturn<ExtractEachCallbackArgs<T>>;
<T>(cases: ReadonlyArray<T>): EachFunctionReturn<T[]>;
(...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
}
interface TestCollectorCallable<C = {}> {
/**
* @deprecated Use options as the second argument instead
*/
<ExtraContext extends C>(name: string | Function, fn: TestFunction<ExtraContext>, options: TestOptions): void;
<ExtraContext extends C>(name: string | Function, fn?: TestFunction<ExtraContext>, options?: number | TestOptions): void;
<ExtraContext extends C>(name: string | Function, options?: TestOptions, fn?: TestFunction<ExtraContext>): void;
}
type ChainableTestAPI<ExtraContext = {}> = ChainableFunction<'concurrent' | 'sequential' | 'only' | 'skip' | 'todo' | 'fails', TestCollectorCallable<ExtraContext>, {
each: TestEachFunction;
}>;
interface TestOptions {
/**
* Test timeout.
*/
timeout?: number;
/**
* Times to retry the test if fails. Useful for making flaky tests more stable.
* When retries is up, the last test error will be thrown.
*
* @default 0
*/
retry?: number;
/**
* How many times the test will run.
* Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default.
*
* @default 0
*/
repeats?: number;
/**
* Whether tests run concurrently.
* Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`.
*/
concurrent?: boolean;
/**
* Whether tests run sequentially.
* Tests inherit `sequential` from `describe()` and nested `describe()` will inherit from parent's `sequential`.
*/
sequential?: boolean;
/**
* Whether the test should be skipped.
*/
skip?: boolean;
/**
* Should this test be the only one running in a suite.
*/
only?: boolean;
/**
* Whether the test should be skipped and marked as a todo.
*/
todo?: boolean;
/**
* Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail.
*/
fails?: boolean;
}
interface ExtendedAPI<ExtraContext> {
skipIf: (condition: any) => ChainableTestAPI<ExtraContext>;
runIf: (condition: any) => ChainableTestAPI<ExtraContext>;
}
type CustomAPI<ExtraContext = {}> = ChainableTestAPI<ExtraContext> & ExtendedAPI<ExtraContext> & {
extend: <T extends Record<string, any> = {}>(fixtures: Fixtures<T, ExtraContext>) => CustomAPI<{
[K in keyof T | keyof ExtraContext]: K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never;
}>;
};
type TestAPI<ExtraContext = {}> = ChainableTestAPI<ExtraContext> & ExtendedAPI<ExtraContext> & {
extend: <T extends Record<string, any> = {}>(fixtures: Fixtures<T, ExtraContext>) => TestAPI<{
[K in keyof T | keyof ExtraContext]: K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never;
}>;
};
interface FixtureOptions {
/**
* Whether to automatically set up current fixture, even though it's not being used in tests.
*/
auto?: boolean;
}
type Use<T> = (value: T) => Promise<void>;
type FixtureFn<T, K extends keyof T, ExtraContext> = (context: Omit<T, K> & ExtraContext, use: Use<T[K]>) => Promise<void>;
type Fixture<T, K extends keyof T, ExtraContext = {}> = ((...args: any) => any) extends T[K] ? (T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never) : T[K] | (T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never);
type Fixtures<T extends Record<string, any>, ExtraContext = {}> = {
[K in keyof T]: Fixture<T, K, ExtraContext & ExtendedContext<Test>> | [Fixture<T, K, ExtraContext & ExtendedContext<Test>>, FixtureOptions?];
};
type InferFixturesTypes<T> = T extends TestAPI<infer C> ? C : T;
interface SuiteCollectorCallable<ExtraContext = {}> {
/**
* @deprecated Use options as the second argument instead
*/
(name: string | Function, fn: SuiteFactory<ExtraContext>, options: TestOptions): SuiteCollector<ExtraContext>;
(name: string | Function, fn?: SuiteFactory<ExtraContext>, options?: number | TestOptions): SuiteCollector<ExtraContext>;
(name: string | Function, options: TestOptions, fn?: SuiteFactory<ExtraContext>): SuiteCollector<ExtraContext>;
}
type ChainableSuiteAPI<ExtraContext = {}> = ChainableFunction<'concurrent' | 'sequential' | 'only' | 'skip' | 'todo' | 'shuffle', SuiteCollectorCallable<ExtraContext>, {
each: TestEachFunction;
}>;
type SuiteAPI<ExtraContext = {}> = ChainableSuiteAPI<ExtraContext> & {
skipIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
runIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
};
type HookListener<T extends any[], Return = void> = (...args: T) => Awaitable<Return>;
type HookCleanupCallback = (() => Awaitable<unknown>) | void;
interface SuiteHooks<ExtraContext = {}> {
beforeAll: HookListener<[Readonly<Suite | File>], HookCleanupCallback>[];
afterAll: HookListener<[Readonly<Suite | File>]>[];
beforeEach: HookListener<[ExtendedContext<Test | Custom> & ExtraContext, Readonly<Suite>], HookCleanupCallback>[];
afterEach: HookListener<[ExtendedContext<Test | Custom> & ExtraContext, Readonly<Suite>]>[];
}
interface TaskCustomOptions extends TestOptions {
concurrent?: boolean;
sequential?: boolean;
skip?: boolean;
only?: boolean;
todo?: boolean;
fails?: boolean;
each?: boolean;
meta?: Record<string, unknown>;
fixtures?: FixtureItem[];
handler?: (context: TaskContext<Custom>) => Awaitable<void>;
}
interface SuiteCollector<ExtraContext = {}> {
readonly name: string;
readonly mode: RunMode;
options?: TestOptions;
type: 'collector';
test: TestAPI<ExtraContext>;
tasks: (Suite | Custom<ExtraContext> | Test<ExtraContext> | SuiteCollector<ExtraContext>)[];
task: (name: string, options?: TaskCustomOptions) => Custom<ExtraContext>;
collect: (file?: File) => Promise<Suite>;
clear: () => void;
on: <T extends keyof SuiteHooks<ExtraContext>>(name: T, ...fn: SuiteHooks<ExtraContext>[T]) => void;
}
type SuiteFactory<ExtraContext = {}> = (test: (name: string | Function, fn: TestFunction<ExtraContext>) => void) => Awaitable<void>;
interface RuntimeContext {
tasks: (SuiteCollector | Test)[];
currentSuite: SuiteCollector | null;
}
interface TestContext {
}
interface TaskContext<Task extends Custom | Test = Custom | Test> {
/**
* Metadata of the current test
*/
task: Readonly<Task>;
/**
* Extract hooks on test failed
*/
onTestFailed: (fn: OnTestFailedHandler) => void;
/**
* Extract hooks on test failed
*/
onTestFinished: (fn: OnTestFinishedHandler) => void;
/**
* Mark tests as skipped. All execution after this call will be skipped.
*/
skip: () => void;
}
type ExtendedContext<T extends Custom | Test> = TaskContext<T> & TestContext;
type OnTestFailedHandler = (result: TaskResult) => Awaitable<void>;
type OnTestFinishedHandler = (result: TaskResult) => Awaitable<void>;
type SequenceHooks = 'stack' | 'list' | 'parallel';
type SequenceSetupFiles = 'list' | 'parallel';
export { type TaskContext as A, type SequenceHooks as B, type Custom as C, type DoneCallback as D, type ExtendedContext as E, type File as F, type SequenceSetupFiles as G, type HookListener as H, type InferFixturesTypes as I, type OnTestFailedHandler as O, type RunMode as R, type Suite as S, type Task as T, type Use as U, type Test as a, type ChainableFunction as b, createChainable as c, type SuiteAPI as d, type TestAPI as e, type SuiteCollector as f, type CustomAPI as g, type SuiteHooks as h, type OnTestFinishedHandler as i, type TaskState as j, type TaskBase as k, type TaskPopulated as l, type TaskMeta as m, type TaskResult as n, type TaskResultPack as o, type TestFunction as p, type TestOptions as q, type FixtureOptions as r, type FixtureFn as s, type Fixture as t, type Fixtures as u, type HookCleanupCallback as v, type TaskCustomOptions as w, type SuiteFactory as x, type RuntimeContext as y, type TestContext as z };

View File

@ -0,0 +1,37 @@
/*
@license
Rollup.js v4.12.0
Fri, 16 Feb 2024 13:31:42 GMT - commit 0146b84be33a8416b4df4b9382549a7ca19dd64a
https://github.com/rollup/rollup
Released under the MIT License.
*/
'use strict';
let fsEvents;
let fsEventsImportError;
async function loadFsEvents() {
try {
({ default: fsEvents } = await import('fsevents'));
}
catch (error) {
fsEventsImportError = error;
}
}
// A call to this function will be injected into the chokidar code
function getFsEvents() {
if (fsEventsImportError)
throw fsEventsImportError;
return fsEvents;
}
const fseventsImporter = /*#__PURE__*/Object.defineProperty({
__proto__: null,
getFsEvents,
loadFsEvents
}, Symbol.toStringTag, { value: 'Module' });
exports.fseventsImporter = fseventsImporter;
exports.loadFsEvents = loadFsEvents;
//# sourceMappingURL=fsevents-importer.js.map

View File

@ -0,0 +1,2 @@
import type { IImage } from './interface.ts';
export declare const GIF: IImage;

View File

@ -0,0 +1,46 @@
import { VitestRunner, VitestRunnerImportSource, Suite, Task, CancelReason, Test, Custom, TaskContext, ExtendedContext } from '@vitest/runner';
import { R as ResolvedConfig } from './reporters-QGe8gs4b.js';
import * as tinybench from 'tinybench';
import 'vite';
import 'vite-node';
import '@vitest/snapshot';
import '@vitest/expect';
import '@vitest/runner/utils';
import '@vitest/utils';
import 'vite-node/client';
import '@vitest/snapshot/manager';
import 'vite-node/server';
import 'node:worker_threads';
import 'node:fs';
import 'chai';
declare class VitestTestRunner implements VitestRunner {
config: ResolvedConfig;
private snapshotClient;
private workerState;
private __vitest_executor;
private cancelRun;
constructor(config: ResolvedConfig);
importFile(filepath: string, source: VitestRunnerImportSource): unknown;
onBeforeRunFiles(): void;
onAfterRunSuite(suite: Suite): Promise<void>;
onAfterRunTask(test: Task): void;
onCancel(_reason: CancelReason): void;
onBeforeRunTask(test: Task): Promise<void>;
onBeforeRunSuite(suite: Suite): Promise<void>;
onBeforeTryTask(test: Task): void;
onAfterTryTask(test: Task): void;
extendTaskContext<T extends Test | Custom>(context: TaskContext<T>): ExtendedContext<T>;
}
declare class NodeBenchmarkRunner implements VitestRunner {
config: ResolvedConfig;
private __vitest_executor;
constructor(config: ResolvedConfig);
importTinybench(): Promise<typeof tinybench>;
importFile(filepath: string, source: VitestRunnerImportSource): unknown;
runSuite(suite: Suite): Promise<void>;
runTask(): Promise<void>;
}
export { NodeBenchmarkRunner, VitestTestRunner };

View File

@ -0,0 +1,253 @@
import * as _vitest_utils from '@vitest/utils';
import { stringify, Constructable } from '@vitest/utils';
export { setupColors } from '@vitest/utils';
import { diff } from '@vitest/utils/diff';
export { DiffOptions } from '@vitest/utils/diff';
type Formatter = (input: string | number | null | undefined) => string;
declare function getMatcherUtils(): {
EXPECTED_COLOR: _vitest_utils.ColorMethod;
RECEIVED_COLOR: _vitest_utils.ColorMethod;
INVERTED_COLOR: _vitest_utils.ColorMethod;
BOLD_WEIGHT: _vitest_utils.ColorMethod;
DIM_COLOR: _vitest_utils.ColorMethod;
matcherHint: (matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions) => string;
printReceived: (object: unknown) => string;
printExpected: (value: unknown) => string;
};
declare function addCustomEqualityTesters(newTesters: Array<Tester>): void;
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
type ChaiPlugin = Chai.ChaiPlugin;
type Tester = (this: TesterContext, a: any, b: any, customTesters: Array<Tester>) => boolean | undefined;
interface TesterContext {
equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
}
interface MatcherHintOptions {
comment?: string;
expectedColor?: Formatter;
isDirectExpectCall?: boolean;
isNot?: boolean;
promise?: string;
receivedColor?: Formatter;
secondArgument?: string;
secondArgumentColor?: Formatter;
}
interface MatcherState {
customTesters: Array<Tester>;
assertionCalls: number;
currentTestName?: string;
dontThrow?: () => void;
error?: Error;
equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
expand?: boolean;
expectedAssertionsNumber?: number | null;
expectedAssertionsNumberErrorGen?: (() => Error) | null;
isExpectingAssertions?: boolean;
isExpectingAssertionsError?: Error | null;
isNot: boolean;
promise: string;
suppressedErrors: Array<Error>;
testPath?: string;
utils: ReturnType<typeof getMatcherUtils> & {
diff: typeof diff;
stringify: typeof stringify;
iterableEquality: Tester;
subsetEquality: Tester;
};
soft?: boolean;
}
interface SyncExpectationResult {
pass: boolean;
message: () => string;
actual?: any;
expected?: any;
}
type AsyncExpectationResult = Promise<SyncExpectationResult>;
type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
interface RawMatcherFn<T extends MatcherState = MatcherState> {
(this: T, received: any, expected: any, options?: any): ExpectationResult;
}
type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>>;
interface ExpectStatic extends Chai.ExpectStatic, AsymmetricMatchersContaining {
<T>(actual: T, message?: string): Assertion<T>;
unreachable: (message?: string) => never;
soft: <T>(actual: T, message?: string) => Assertion<T>;
extend: (expects: MatchersObject) => void;
addEqualityTesters: (testers: Array<Tester>) => void;
assertions: (expected: number) => void;
hasAssertions: () => void;
anything: () => any;
any: (constructor: unknown) => any;
getState: () => MatcherState;
setState: (state: Partial<MatcherState>) => void;
not: AsymmetricMatchersContaining;
}
interface AsymmetricMatchersContaining {
stringContaining: (expected: string) => any;
objectContaining: <T = any>(expected: T) => any;
arrayContaining: <T = unknown>(expected: Array<T>) => any;
stringMatching: (expected: string | RegExp) => any;
closeTo: (expected: number, precision?: number) => any;
}
interface JestAssertion<T = any> extends jest.Matchers<void, T> {
toEqual: <E>(expected: E) => void;
toStrictEqual: <E>(expected: E) => void;
toBe: <E>(expected: E) => void;
toMatch: (expected: string | RegExp) => void;
toMatchObject: <E extends {} | any[]>(expected: E) => void;
toContain: <E>(item: E) => void;
toContainEqual: <E>(item: E) => void;
toBeTruthy: () => void;
toBeFalsy: () => void;
toBeGreaterThan: (num: number | bigint) => void;
toBeGreaterThanOrEqual: (num: number | bigint) => void;
toBeLessThan: (num: number | bigint) => void;
toBeLessThanOrEqual: (num: number | bigint) => void;
toBeNaN: () => void;
toBeUndefined: () => void;
toBeNull: () => void;
toBeDefined: () => void;
toBeInstanceOf: <E>(expected: E) => void;
toBeCalledTimes: (times: number) => void;
toHaveLength: (length: number) => void;
toHaveProperty: <E>(property: string | (string | number)[], value?: E) => void;
toBeCloseTo: (number: number, numDigits?: number) => void;
toHaveBeenCalledTimes: (times: number) => void;
toHaveBeenCalled: () => void;
toBeCalled: () => void;
toHaveBeenCalledWith: <E extends any[]>(...args: E) => void;
toBeCalledWith: <E extends any[]>(...args: E) => void;
toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
nthCalledWith: <E extends any[]>(nthCall: number, ...args: E) => void;
toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => void;
lastCalledWith: <E extends any[]>(...args: E) => void;
toThrow: (expected?: string | Constructable | RegExp | Error) => void;
toThrowError: (expected?: string | Constructable | RegExp | Error) => void;
toReturn: () => void;
toHaveReturned: () => void;
toReturnTimes: (times: number) => void;
toHaveReturnedTimes: (times: number) => void;
toReturnWith: <E>(value: E) => void;
toHaveReturnedWith: <E>(value: E) => void;
toHaveLastReturnedWith: <E>(value: E) => void;
lastReturnedWith: <E>(value: E) => void;
toHaveNthReturnedWith: <E>(nthCall: number, value: E) => void;
nthReturnedWith: <E>(nthCall: number, value: E) => void;
}
type VitestAssertion<A, T> = {
[K in keyof A]: A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T>;
} & ((type: string, message?: string) => Assertion);
type Promisify<O> = {
[K in keyof O]: O[K] extends (...args: infer A) => infer R ? O extends R ? Promisify<O[K]> : (...args: A) => Promise<R> : O[K];
};
interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T> {
toBeTypeOf: (expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => void;
toHaveBeenCalledOnce: () => void;
toSatisfy: <E>(matcher: (value: E) => boolean, message?: string) => void;
resolves: Promisify<Assertion<T>>;
rejects: Promisify<Assertion<T>>;
}
declare global {
namespace jest {
interface Matchers<R, T = {}> {
}
}
}
interface AsymmetricMatcherInterface {
asymmetricMatch: (other: unknown) => boolean;
toString: () => string;
getExpectedType?: () => string;
toAsymmetricMatcher?: () => string;
}
declare abstract class AsymmetricMatcher<T, State extends MatcherState = MatcherState> implements AsymmetricMatcherInterface {
protected sample: T;
protected inverse: boolean;
$$typeof: symbol;
constructor(sample: T, inverse?: boolean);
protected getMatcherContext(expect?: Chai.ExpectStatic): State;
abstract asymmetricMatch(other: unknown): boolean;
abstract toString(): string;
getExpectedType?(): string;
toAsymmetricMatcher?(): string;
}
declare class StringContaining extends AsymmetricMatcher<string> {
constructor(sample: string, inverse?: boolean);
asymmetricMatch(other: string): boolean;
toString(): string;
getExpectedType(): string;
}
declare class Anything extends AsymmetricMatcher<void> {
asymmetricMatch(other: unknown): boolean;
toString(): string;
toAsymmetricMatcher(): string;
}
declare class ObjectContaining extends AsymmetricMatcher<Record<string, unknown>> {
constructor(sample: Record<string, unknown>, inverse?: boolean);
getPrototype(obj: object): any;
hasProperty(obj: object | null, property: string): boolean;
asymmetricMatch(other: any): boolean;
toString(): string;
getExpectedType(): string;
}
declare class ArrayContaining<T = unknown> extends AsymmetricMatcher<Array<T>> {
constructor(sample: Array<T>, inverse?: boolean);
asymmetricMatch(other: Array<T>): boolean;
toString(): string;
getExpectedType(): string;
}
declare class Any extends AsymmetricMatcher<any> {
constructor(sample: unknown);
fnNameFor(func: Function): string;
asymmetricMatch(other: unknown): boolean;
toString(): string;
getExpectedType(): string;
toAsymmetricMatcher(): string;
}
declare class StringMatching extends AsymmetricMatcher<RegExp> {
constructor(sample: string | RegExp, inverse?: boolean);
asymmetricMatch(other: string): boolean;
toString(): string;
getExpectedType(): string;
}
declare const JestAsymmetricMatchers: ChaiPlugin;
declare function equals(a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean): boolean;
declare function isAsymmetric(obj: any): boolean;
declare function hasAsymmetric(obj: any, seen?: Set<unknown>): boolean;
declare function isA(typeName: string, value: unknown): boolean;
declare function fnNameFor(func: Function): string;
declare function hasProperty(obj: object | null, property: string): boolean;
declare function isImmutableUnorderedKeyed(maybeKeyed: any): boolean;
declare function isImmutableUnorderedSet(maybeSet: any): boolean;
declare function iterableEquality(a: any, b: any, customTesters?: Array<Tester>, aStack?: Array<any>, bStack?: Array<any>): boolean | undefined;
declare function subsetEquality(object: unknown, subset: unknown, customTesters?: Array<Tester>): boolean | undefined;
declare function typeEquality(a: any, b: any): boolean | undefined;
declare function arrayBufferEquality(a: unknown, b: unknown): boolean | undefined;
declare function sparseArrayEquality(a: unknown, b: unknown, customTesters?: Array<Tester>): boolean | undefined;
declare function generateToBeMessage(deepEqualityName: string, expected?: string, actual?: string): string;
declare function pluralize(word: string, count: number): string;
declare const MATCHERS_OBJECT: unique symbol;
declare const JEST_MATCHERS_OBJECT: unique symbol;
declare const GLOBAL_EXPECT: unique symbol;
declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol;
declare function getState<State extends MatcherState = MatcherState>(expect: ExpectStatic): State;
declare function setState<State extends MatcherState = MatcherState>(state: Partial<State>, expect: ExpectStatic): void;
declare const JestChaiExpect: ChaiPlugin;
declare const JestExtend: ChaiPlugin;
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, type Assertion, AsymmetricMatcher, type AsymmetricMatcherInterface, type AsymmetricMatchersContaining, type AsyncExpectationResult, type ChaiPlugin, type ExpectStatic, type ExpectationResult, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, type JestAssertion, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, type MatcherHintOptions, type MatcherState, type MatchersObject, ObjectContaining, type RawMatcherFn, StringContaining, StringMatching, type SyncExpectationResult, type Tester, type TesterContext, addCustomEqualityTesters, arrayBufferEquality, equals, fnNameFor, generateToBeMessage, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality };

View File

@ -0,0 +1,21 @@
import { V as ViteNodeServerOptions } from './index-WT31LSgS.js';
import './trace-mapping.d-xyIfZtPm.js';
interface CliOptions {
'root'?: string;
'script'?: boolean;
'config'?: string;
'mode'?: string;
'watch'?: boolean;
'options'?: ViteNodeServerOptionsCLI;
'version'?: boolean;
'help'?: boolean;
'--'?: string[];
}
type Optional<T> = T | undefined;
type ComputeViteNodeServerOptionsCLI<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends Optional<RegExp[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[] | true> ? string | string[] | true : T[K] extends Optional<Record<string, any>> ? ComputeViteNodeServerOptionsCLI<T[K]> : T[K];
};
type ViteNodeServerOptionsCLI = ComputeViteNodeServerOptionsCLI<ViteNodeServerOptions>;
export type { CliOptions, ViteNodeServerOptionsCLI };

View File

@ -0,0 +1,2 @@
import type { ISize } from './vendor/image-size/types/interface.ts';
export declare function probe(url: string): Promise<ISize>;

View File

@ -0,0 +1,47 @@
{
"name": "@vitest/expect",
"type": "module",
"version": "1.3.0",
"description": "Jest's expect matchers as a Chai plugin",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/expect#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
"directory": "packages/expect"
},
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"sideEffects": false,
"exports": {
".": {
"types": "./index.d.ts",
"default": "./dist/index.js"
},
"./*": "./*"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./index.d.ts",
"files": [
"*.d.ts",
"dist"
],
"dependencies": {
"chai": "^4.3.10",
"@vitest/spy": "1.3.0",
"@vitest/utils": "1.3.0"
},
"devDependencies": {
"@types/chai": "4.3.6",
"picocolors": "^1.0.0",
"rollup-plugin-copy": "^3.5.0",
"@vitest/runner": "1.3.0"
},
"scripts": {
"build": "rimraf dist && rollup -c",
"dev": "rollup -c --watch"
}
}

View File

@ -0,0 +1,133 @@
'use strict';
var os = require('node:os');
var stdEnv = require('std-env');
var vite = require('vite');
var _a$1;
typeof process < "u" && typeof process.stdout < "u" && !((_a$1 = process.versions) == null ? void 0 : _a$1.deno) && !globalThis.window;
var _a, _b;
const defaultInclude = ["**/*.{test,spec}.?(c|m)[jt]s?(x)"];
const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*"];
const defaultCoverageExcludes = [
"coverage/**",
"dist/**",
"**/[.]**",
"packages/*/test?(s)/**",
"**/*.d.ts",
"**/virtual:*",
"**/__x00__*",
"**/\0*",
"cypress/**",
"test?(s)/**",
"test?(-*).?(c|m)[jt]s?(x)",
"**/*{.,-}{test,spec}.?(c|m)[jt]s?(x)",
"**/__tests__/**",
"**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*",
"**/vitest.{workspace,projects}.[jt]s?(on)",
"**/.{eslint,mocha,prettier}rc.{?(c|m)js,yml}"
];
const coverageConfigDefaults = {
provider: "v8",
enabled: false,
all: true,
clean: true,
cleanOnRerun: true,
reportsDirectory: "./coverage",
exclude: defaultCoverageExcludes,
reportOnFailure: false,
reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte", ".marko"],
allowExternal: false,
processingConcurrency: Math.min(20, ((_b = (_a = os).availableParallelism) == null ? void 0 : _b.call(_a)) ?? os.cpus().length)
};
const fakeTimersDefaults = {
loopLimit: 1e4,
shouldClearNativeTimers: true,
toFake: [
"setTimeout",
"clearTimeout",
"setInterval",
"clearInterval",
"setImmediate",
"clearImmediate",
"Date"
]
};
const config = {
allowOnly: !stdEnv.isCI,
isolate: true,
watch: !stdEnv.isCI,
globals: false,
environment: "node",
pool: "threads",
clearMocks: false,
restoreMocks: false,
mockReset: false,
include: defaultInclude,
exclude: defaultExclude,
testTimeout: 5e3,
hookTimeout: 1e4,
teardownTimeout: 1e4,
watchExclude: ["**/node_modules/**", "**/dist/**"],
forceRerunTriggers: [
"**/package.json/**",
"**/{vitest,vite}.config.*/**"
],
update: false,
reporters: [],
silent: false,
hideSkippedTests: false,
api: false,
ui: false,
uiBase: "/__vitest__/",
open: !stdEnv.isCI,
css: {
include: []
},
coverage: coverageConfigDefaults,
fakeTimers: fakeTimersDefaults,
maxConcurrency: 5,
dangerouslyIgnoreUnhandledErrors: false,
typecheck: {
checker: "tsc",
include: ["**/*.{test,spec}-d.?(c|m)[jt]s?(x)"],
exclude: defaultExclude
},
slowTestThreshold: 300,
disableConsoleIntercept: false
};
const configDefaults = Object.freeze(config);
const extraInlineDeps = [
/^(?!.*(?:node_modules)).*\.mjs$/,
/^(?!.*(?:node_modules)).*\.cjs\.js$/,
// Vite client
/vite\w*\/dist\/client\/env.mjs/,
// Nuxt
"@nuxt/test-utils"
];
function defineConfig(config) {
return config;
}
function defineProject(config) {
return config;
}
function defineWorkspace(config) {
return config;
}
Object.defineProperty(exports, "mergeConfig", {
enumerable: true,
get: function () { return vite.mergeConfig; }
});
exports.configDefaults = configDefaults;
exports.coverageConfigDefaults = coverageConfigDefaults;
exports.defaultExclude = defaultExclude;
exports.defaultInclude = defaultInclude;
exports.defineConfig = defineConfig;
exports.defineProject = defineProject;
exports.defineWorkspace = defineWorkspace;
exports.extraInlineDeps = extraInlineDeps;

View File

@ -0,0 +1,2 @@
import type { IImage } from './interface.ts';
export declare const BMP: IImage;

View File

@ -0,0 +1,25 @@
import type { BuildOptions, Rollup, Plugin as VitePlugin } from 'vite';
type OutputOptionsHook = Extract<VitePlugin['outputOptions'], Function>;
type OutputOptions = Parameters<OutputOptionsHook>[0];
type ExtendManualChunksHooks = {
before?: Rollup.GetManualChunk;
after?: Rollup.GetManualChunk;
};
export declare function extendManualChunks(outputOptions: OutputOptions, hooks: ExtendManualChunksHooks): void;
export declare const ASTRO_PAGE_EXTENSION_POST_PATTERN = "@_@";
/**
* 1. We add a fixed prefix, which is used as virtual module naming convention;
* 2. We replace the dot that belongs extension with an arbitrary string.
*
* @param virtualModulePrefix
* @param path
*/
export declare function getVirtualModulePageNameFromPath(virtualModulePrefix: string, path: string): string;
/**
*
* @param virtualModulePrefix
* @param id
*/
export declare function getPathFromVirtualModulePageName(virtualModulePrefix: string, id: string): string;
export declare function shouldInlineAsset(assetContent: string, assetPath: string, assetsInlineLimit: NonNullable<BuildOptions['assetsInlineLimit']>): boolean;
export {};

View File

@ -0,0 +1,2 @@
import type { imageType } from './types/index.js';
export declare function detector(input: Uint8Array): imageType | undefined;

View File

@ -0,0 +1,179 @@
import { fade, slide } from "../../transitions/index.js";
import { markHTMLString } from "./escape.js";
import cssesc from "cssesc";
const transitionNameMap = /* @__PURE__ */ new WeakMap();
function incrementTransitionNumber(result) {
let num = 1;
if (transitionNameMap.has(result)) {
num = transitionNameMap.get(result) + 1;
}
transitionNameMap.set(result, num);
return num;
}
function createTransitionScope(result, hash) {
const num = incrementTransitionNumber(result);
return `astro-${hash}-${num}`;
}
const getAnimations = (name) => {
if (name === "fade")
return fade();
if (name === "slide")
return slide();
if (typeof name === "object")
return name;
};
const addPairs = (animations, stylesheet) => {
for (const [direction, images] of Object.entries(animations)) {
for (const [image, rules] of Object.entries(images)) {
stylesheet.addAnimationPair(direction, image, rules);
}
}
};
const reEncodeValidChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
const reEncodeInValidStart = "-0123456789_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
function reEncode(s) {
let result = "";
let codepoint;
for (let i = 0; i < s.length; i += (codepoint ?? 0) > 65535 ? 2 : 1) {
codepoint = s.codePointAt(i);
if (codepoint !== void 0) {
result += codepoint < 128 ? codepoint === 95 ? "__" : reEncodeValidChars[codepoint] ?? "_" + codepoint.toString(16).padStart(2, "0") : String.fromCodePoint(codepoint);
}
}
return reEncodeInValidStart[result.codePointAt(0) ?? 0] ? "_" + result : result;
}
function renderTransition(result, hash, animationName, transitionName) {
if (!animationName)
animationName = "fade";
const scope = createTransitionScope(result, hash);
const name = transitionName ? cssesc(reEncode(transitionName), { isIdentifier: true }) : scope;
const sheet = new ViewTransitionStyleSheet(scope, name);
const animations = getAnimations(animationName);
if (animations) {
addPairs(animations, sheet);
} else if (animationName === "none") {
sheet.addFallback("old", "animation: none; mix-blend-mode: normal;");
sheet.addModern("old", "animation: none; opacity: 0; mix-blend-mode: normal;");
sheet.addAnimationRaw("new", "animation: none; mix-blend-mode: normal;");
}
result._metadata.extraHead.push(markHTMLString(`<style>${sheet.toString()}</style>`));
return scope;
}
function createAnimationScope(transitionName, animations) {
const hash = Math.random().toString(36).slice(2, 8);
const scope = `astro-${hash}`;
const sheet = new ViewTransitionStyleSheet(scope, transitionName);
addPairs(animations, sheet);
return { scope, styles: sheet.toString().replaceAll('"', "") };
}
class ViewTransitionStyleSheet {
constructor(scope, name) {
this.scope = scope;
this.name = name;
}
modern = [];
fallback = [];
toString() {
const { scope, name } = this;
const [modern, fallback] = [this.modern, this.fallback].map((rules) => rules.join(""));
return [
`[data-astro-transition-scope="${scope}"] { view-transition-name: ${name}; }`,
this.layer(modern),
fallback
].join("");
}
layer(cssText) {
return cssText ? `@layer astro { ${cssText} }` : "";
}
addRule(target, cssText) {
this[target].push(cssText);
}
addAnimationRaw(image, animation) {
this.addModern(image, animation);
this.addFallback(image, animation);
}
addModern(image, animation) {
const { name } = this;
this.addRule("modern", `::view-transition-${image}(${name}) { ${animation} }`);
}
addFallback(image, animation) {
const { scope } = this;
this.addRule(
"fallback",
// Two selectors here, the second in case there is an animation on the root.
`[data-astro-transition-fallback="${image}"] [data-astro-transition-scope="${scope}"],
[data-astro-transition-fallback="${image}"][data-astro-transition-scope="${scope}"] { ${animation} }`
);
}
addAnimationPair(direction, image, rules) {
const { scope, name } = this;
const animation = stringifyAnimation(rules);
const prefix = direction === "backwards" ? `[data-astro-transition=back]` : direction === "forwards" ? "" : `[data-astro-transition=${direction}]`;
this.addRule("modern", `${prefix}::view-transition-${image}(${name}) { ${animation} }`);
this.addRule(
"fallback",
`${prefix}[data-astro-transition-fallback="${image}"] [data-astro-transition-scope="${scope}"],
${prefix}[data-astro-transition-fallback="${image}"][data-astro-transition-scope="${scope}"] { ${animation} }`
);
}
}
function addAnimationProperty(builder, prop, value) {
let arr = builder[prop];
if (Array.isArray(arr)) {
arr.push(value.toString());
} else {
builder[prop] = [value.toString()];
}
}
function animationBuilder() {
return {
toString() {
let out = "";
for (let k in this) {
let value = this[k];
if (Array.isArray(value)) {
out += `
${k}: ${value.join(", ")};`;
}
}
return out;
}
};
}
function stringifyAnimation(anim) {
if (Array.isArray(anim)) {
return stringifyAnimations(anim);
} else {
return stringifyAnimations([anim]);
}
}
function stringifyAnimations(anims) {
const builder = animationBuilder();
for (const anim of anims) {
if (anim.duration) {
addAnimationProperty(builder, "animation-duration", toTimeValue(anim.duration));
}
if (anim.easing) {
addAnimationProperty(builder, "animation-timing-function", anim.easing);
}
if (anim.direction) {
addAnimationProperty(builder, "animation-direction", anim.direction);
}
if (anim.delay) {
addAnimationProperty(builder, "animation-delay", anim.delay);
}
if (anim.fillMode) {
addAnimationProperty(builder, "animation-fill-mode", anim.fillMode);
}
addAnimationProperty(builder, "animation-name", anim.name);
}
return builder.toString();
}
function toTimeValue(num) {
return typeof num === "number" ? num + "ms" : num;
}
export {
createAnimationScope,
createTransitionScope,
renderTransition
};

View File

@ -0,0 +1,5 @@
// @ts-ignore
export { default as SEO } from "./SEO.astro";
// @ts-ignore
export * from "./SEO.astro";

View File

@ -0,0 +1,7 @@
/**
* This file is prebuilt from packages/astro/src/runtime/server/astro-island.ts
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
declare const _default: "(()=>{var v=Object.defineProperty;var A=(c,s,a)=>s in c?v(c,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):c[s]=a;var l=(c,s,a)=>(A(c,typeof s!=\"symbol\"?s+\"\":s,a),a);var m;{let c={0:t=>y(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t)},s=t=>{let[e,n]=t;return e in c?c[e](n):void 0},a=t=>t.map(s),y=t=>typeof t!=\"object\"||t===null?t:Object.fromEntries(Object.entries(t).map(([e,n])=>[e,s(n)]));customElements.get(\"astro-island\")||customElements.define(\"astro-island\",(m=class extends HTMLElement{constructor(){super(...arguments);l(this,\"Component\");l(this,\"hydrator\");l(this,\"hydrate\",async()=>{var f;if(!this.hydrator||!this.isConnected)return;let e=(f=this.parentElement)==null?void 0:f.closest(\"astro-island[ssr]\");if(e){e.addEventListener(\"astro:hydrate\",this.hydrate,{once:!0});return}let n=this.querySelectorAll(\"astro-slot\"),r={},h=this.querySelectorAll(\"template[data-astro-template]\");for(let o of h){let i=o.closest(this.tagName);i!=null&&i.isSameNode(this)&&(r[o.getAttribute(\"data-astro-template\")||\"default\"]=o.innerHTML,o.remove())}for(let o of n){let i=o.closest(this.tagName);i!=null&&i.isSameNode(this)&&(r[o.getAttribute(\"name\")||\"default\"]=o.innerHTML)}let p;try{p=this.hasAttribute(\"props\")?y(JSON.parse(this.getAttribute(\"props\"))):{}}catch(o){let i=this.getAttribute(\"component-url\")||\"<unknown>\",b=this.getAttribute(\"component-export\");throw b&&(i+=` (export ${b})`),console.error(`[hydrate] Error parsing props for component ${i}`,this.getAttribute(\"props\"),o),o}let d,u=this.hydrator(this);d=performance.now(),await u(this.Component,p,r,{client:this.getAttribute(\"client\")}),d&&this.setAttribute(\"client-render-time\",(performance.now()-d).toString()),this.removeAttribute(\"ssr\"),this.dispatchEvent(new CustomEvent(\"astro:hydrate\"))});l(this,\"unmount\",()=>{this.isConnected||this.dispatchEvent(new CustomEvent(\"astro:unmount\"))})}disconnectedCallback(){document.removeEventListener(\"astro:after-swap\",this.unmount),document.addEventListener(\"astro:after-swap\",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute(\"await-children\")||document.readyState===\"interactive\"||document.readyState===\"complete\")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener(\"DOMContentLoaded\",e),n.disconnect(),this.childrenConnectedCallback()},n=new MutationObserver(()=>{var r;((r=this.lastChild)==null?void 0:r.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue===\"astro:end\"&&(this.lastChild.remove(),e())});n.observe(this,{childList:!0}),document.addEventListener(\"DOMContentLoaded\",e)}}async childrenConnectedCallback(){let e=this.getAttribute(\"before-hydration-url\");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute(\"opts\")),n=this.getAttribute(\"client\");if(Astro[n]===void 0){window.addEventListener(`astro:${n}`,()=>this.start(),{once:!0});return}try{await Astro[n](async()=>{let r=this.getAttribute(\"renderer-url\"),[h,{default:p}]=await Promise.all([import(this.getAttribute(\"component-url\")),r?import(r):()=>()=>{}]),d=this.getAttribute(\"component-export\")||\"default\";if(!d.includes(\".\"))this.Component=h[d];else{this.Component=h;for(let u of d.split(\".\"))this.Component=this.Component[u]}return this.hydrator=p,this.hydrate},e,this)}catch(r){console.error(`[astro-island] Error hydrating ${this.getAttribute(\"component-url\")}`,r)}}attributeChangedCallback(){this.hydrate()}},l(m,\"observedAttributes\",[\"props\"]),m))}})();";
export default _default;

View File

@ -0,0 +1,33 @@
{
"name": "@medv/finder",
"version": "3.1.0",
"description": "CSS Selector Generator",
"type": "module",
"main": "finder.js",
"types": "finder.d.ts",
"files": [
"*.ts",
"*.js"
],
"scripts": {
"build": "tsc",
"test": "tsc && uvu",
"release": "release-it --access public"
},
"devDependencies": {
"css.escape": "^1.5.1",
"jsdom": "^21.1.0",
"release-it": "^15.7.0",
"typescript": "4.9.5",
"uvu": "^0.5.6"
},
"author": "Anton Medvedev <anton@medv.io>",
"license": "MIT",
"homepage": "https://github.com/antonmedv/finder",
"repository": "antonmedv/finder",
"keywords": [
"css",
"selector",
"generator"
]
}

View File

@ -0,0 +1,308 @@
import {
attachTooltipToHighlight,
createHighlight,
getElementsPositionInDocument,
positionHighlight
} from "../utils/highlight.js";
import { createWindowElement } from "../utils/window.js";
import { a11y } from "./a11y.js";
import { finder } from "@medv/finder";
import { perf } from "./perf.js";
const icon = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 1 20 16"><path fill="#fff" d="M.6 2A1.1 1.1 0 0 1 1.7.9h16.6a1.1 1.1 0 1 1 0 2.2H1.6A1.1 1.1 0 0 1 .8 2Zm1.1 7.1h6a1.1 1.1 0 0 0 0-2.2h-6a1.1 1.1 0 0 0 0 2.2ZM9.3 13H1.8a1.1 1.1 0 1 0 0 2.2h7.5a1.1 1.1 0 1 0 0-2.2Zm11.3 1.9a1.1 1.1 0 0 1-1.5 0l-1.7-1.7a4.1 4.1 0 1 1 1.6-1.6l1.6 1.7a1.1 1.1 0 0 1 0 1.6Zm-5.3-3.4a1.9 1.9 0 1 0 0-3.8 1.9 1.9 0 0 0 0 3.8Z"/></svg>';
const rules = [...a11y, ...perf];
const dynamicAuditRuleKeys = ["title", "message"];
function resolveAuditRule(rule, element) {
let resolved = { ...rule };
for (const key of dynamicAuditRuleKeys) {
const value = rule[key];
if (typeof value === "string")
continue;
resolved[key] = value(element);
}
return resolved;
}
var audit_default = {
id: "astro:audit",
name: "Audit",
icon,
async init(canvas, eventTarget) {
let audits = [];
await lint();
document.addEventListener("astro:after-swap", async () => lint());
document.addEventListener("astro:page-load", async () => refreshLintPositions);
function onPageClick(event) {
const target = event.target;
if (!target)
return;
if (!target.closest)
return;
if (target.closest("astro-dev-toolbar"))
return;
eventTarget.dispatchEvent(
new CustomEvent("toggle-app", {
detail: {
state: false
}
})
);
}
eventTarget.addEventListener("app-toggled", (event) => {
if (event.detail.state === true) {
document.addEventListener("click", onPageClick, true);
} else {
document.removeEventListener("click", onPageClick, true);
}
});
async function lint() {
audits.forEach(({ highlightElement }) => {
highlightElement.remove();
});
audits = [];
canvas.getElementById("no-audit")?.remove();
const selectorCache = /* @__PURE__ */ new Map();
for (const rule of rules) {
const elements = selectorCache.get(rule.selector) ?? document.querySelectorAll(rule.selector);
let matches = [];
if (typeof rule.match === "undefined") {
matches = Array.from(elements);
} else {
for (const element of elements) {
if (await rule.match(element)) {
matches.push(element);
}
}
}
for (const element of matches) {
if (audits.some((audit) => audit.auditedElement === element))
continue;
await createAuditProblem(rule, element);
}
}
if (audits.length > 0) {
eventTarget.dispatchEvent(
new CustomEvent("toggle-notification", {
detail: {
state: true
}
})
);
const auditListWindow = createWindowElement(
`
<style>
astro-dev-toolbar-window {
left: initial;
top: 8px;
right: 8px;
transform: none;
width: 320px;
max-height: 320px;
padding: 0;
overflow: hidden;
}
hr {
margin: 0;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 18px;
}
h1 {
font-size: 22px;
font-weight: 600;
color: #fff;
}
ul, li {
margin: 0;
padding: 0;
list-style: none;
}
h1, h2 {
margin: 0;
}
h3 {
margin: 0;
margin-bottom: 8px;
color: white;
white-space: nowrap;
}
.audit-title {
font-weight: bold;
color: white;
margin-right: 1ch;
}
#audit-list {
display: flex;
flex-direction: column;
overflow: auto;
}
</style>
<header>
<h1>Audits</h1>
<astro-dev-toolbar-badge size="large">${audits.length} problem${audits.length > 1 ? "s" : ""} found</astro-dev-toolbar-badge>
</header>
<hr />`
);
const auditListUl = document.createElement("ul");
auditListUl.id = "audit-list";
audits.forEach((audit, index) => {
const resolvedRule = resolveAuditRule(audit.rule, audit.auditedElement);
const card = document.createElement("astro-dev-toolbar-card");
card.shadowRoot.innerHTML = `
<style>
:host>button {
text-align: left;
box-shadow: none !important;
${index + 1 < audits.length ? "border-radius: 0 !important;" : "border-radius: 0 0 8px 8px !important;"}
}
:host>button:hover {
cursor: pointer;
}
</style>`;
card.clickAction = () => {
audit.highlightElement.scrollIntoView();
audit.highlightElement.focus();
};
const h3 = document.createElement("h3");
h3.innerText = finder(audit.auditedElement);
card.appendChild(h3);
const div = document.createElement("div");
const title = document.createElement("span");
title.classList.add("audit-title");
title.innerHTML = resolvedRule.title;
div.appendChild(title);
card.appendChild(div);
auditListUl.appendChild(card);
});
auditListWindow.appendChild(auditListUl);
canvas.append(auditListWindow);
} else {
eventTarget.dispatchEvent(
new CustomEvent("toggle-notification", {
detail: {
state: false
}
})
);
const window2 = createWindowElement(
`<style>
header {
display: flex;
}
h1 {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: #fff;
margin: 0;
font-size: 22px;
}
astro-dev-toolbar-icon {
width: 1em;
height: 1em;
padding: 8px;
display: block;
background: green;
border-radius: 9999px;
}
</style>
<header>
<h1><astro-dev-toolbar-icon icon="check-circle"></astro-dev-toolbar-icon>No accessibility or performance issues detected.</h1>
</header>
<p>
Nice work! This app scans the page and highlights common accessibility and performance issues for you, like a missing "alt" attribute on an image, or a image not using performant attributes.
</p>
`
);
canvas.append(window2);
}
["scroll", "resize"].forEach((event) => {
window.addEventListener(event, refreshLintPositions);
});
}
function refreshLintPositions() {
const noAuditBlock = canvas.getElementById("no-audit");
if (noAuditBlock) {
const devOverlayRect = document.querySelector("astro-dev-toolbar")?.shadowRoot.querySelector("#dev-toolbar-root")?.getBoundingClientRect();
noAuditBlock.style.top = `${(devOverlayRect?.top ?? 0) - (devOverlayRect?.height ?? 0) - 16}px`;
}
audits.forEach(({ highlightElement, auditedElement }) => {
const rect = auditedElement.getBoundingClientRect();
positionHighlight(highlightElement, rect);
});
}
async function createAuditProblem(rule, originalElement) {
const computedStyle = window.getComputedStyle(originalElement);
const targetedElement = originalElement.children[0] || originalElement;
if (targetedElement.offsetParent === null || computedStyle.display === "none") {
return;
}
if (originalElement.nodeName === "IMG" && !originalElement.complete) {
return;
}
const rect = originalElement.getBoundingClientRect();
const highlight = createHighlight(rect, "warning", { "data-audit-code": rule.code });
const tooltip = buildAuditTooltip(rule, originalElement);
const { isFixed } = getElementsPositionInDocument(originalElement);
if (isFixed) {
tooltip.style.position = highlight.style.position = "fixed";
}
attachTooltipToHighlight(highlight, tooltip, originalElement);
canvas.append(highlight);
audits.push({
highlightElement: highlight,
auditedElement: originalElement,
rule
});
}
function buildAuditTooltip(rule, element) {
const tooltip = document.createElement("astro-dev-toolbar-tooltip");
const { title, message } = resolveAuditRule(rule, element);
tooltip.sections = [
{
icon: "warning",
title: escapeHtml(title)
},
{
content: escapeHtml(message)
}
];
const elementFile = element.getAttribute("data-astro-source-file");
const elementPosition = element.getAttribute("data-astro-source-loc");
if (elementFile) {
const elementFileWithPosition = elementFile + (elementPosition ? ":" + elementPosition : "");
tooltip.sections.push({
content: elementFileWithPosition.slice(
window.__astro_dev_toolbar__.root.length - 1
// We want to keep the final slash, so minus one.
),
clickDescription: "Click to go to file",
async clickAction() {
await fetch("/__open-in-editor?file=" + encodeURIComponent(elementFileWithPosition));
}
});
}
return tooltip;
}
function escapeHtml(unsafe) {
return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}
}
};
export {
audit_default as default
};

View File

@ -0,0 +1,57 @@
import { RedirectComponentInstance, routeIsRedirect } from "../core/redirects/index.js";
import { preload } from "../vite-plugin-astro-server/index.js";
import { getPrerenderStatus } from "./metadata.js";
async function getSortedPreloadedMatches({
pipeline,
matches,
settings
}) {
return (await preloadAndSetPrerenderStatus({
pipeline,
matches,
settings
})).sort((a, b) => prioritizePrerenderedMatchesComparator(a.route, b.route));
}
async function preloadAndSetPrerenderStatus({
pipeline,
matches,
settings
}) {
const preloaded = new Array();
for (const route of matches) {
const filePath = new URL(`./${route.component}`, settings.config.root);
if (routeIsRedirect(route)) {
preloaded.push({
preloadedComponent: RedirectComponentInstance,
route,
filePath
});
continue;
}
const preloadedComponent = await preload({ pipeline, filePath });
const prerenderStatus = getPrerenderStatus({
filePath,
loader: pipeline.getModuleLoader()
});
if (prerenderStatus !== void 0) {
route.prerender = prerenderStatus;
}
preloaded.push({ preloadedComponent, route, filePath });
}
return preloaded;
}
function prioritizePrerenderedMatchesComparator(a, b) {
if (areRegexesEqual(a.pattern, b.pattern)) {
if (a.prerender !== b.prerender) {
return a.prerender ? -1 : 1;
}
return a.component < b.component ? -1 : 1;
}
return 0;
}
function areRegexesEqual(regexp1, regexp2) {
return regexp1.source === regexp2.source && regexp1.global === regexp2.global;
}
export {
getSortedPreloadedMatches
};

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="./favicon.svg" type="image/svg+xml">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vitest</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Readex+Pro:wght@300;400&display=swap" rel="stylesheet">
<script>
(function () {
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
const setting = localStorage.getItem('vueuse-color-scheme') || 'auto'
if (setting === 'dark' || (prefersDark && setting !== 'light'))
document.documentElement.classList.toggle('dark', true)
})()
</script>
<!-- !LOAD_METADATA! -->
<script type="module" crossorigin src="./assets/index-AUm0OrLY.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-iPSQW1bz.css">
</head>
<body>
<div id="app"></div>
</body>
</html>

View File

@ -0,0 +1,678 @@
import { Console } from 'node:console';
const denyList = /* @__PURE__ */ new Set([
"GLOBAL",
"root",
"global",
"Buffer",
"ArrayBuffer",
"Uint8Array"
]);
const nodeGlobals = new Map(
Object.getOwnPropertyNames(globalThis).filter((global) => !denyList.has(global)).map((nodeGlobalsKey) => {
const descriptor = Object.getOwnPropertyDescriptor(
globalThis,
nodeGlobalsKey
);
if (!descriptor) {
throw new Error(
`No property descriptor for ${nodeGlobalsKey}, this is a bug in Vitest.`
);
}
return [nodeGlobalsKey, descriptor];
})
);
var node = {
name: "node",
transformMode: "ssr",
// this is largely copied from jest's node environment
async setupVM() {
const vm = await import('node:vm');
let context = vm.createContext();
let global = vm.runInContext(
"this",
context
);
const contextGlobals = new Set(Object.getOwnPropertyNames(global));
for (const [nodeGlobalsKey, descriptor] of nodeGlobals) {
if (!contextGlobals.has(nodeGlobalsKey)) {
if (descriptor.configurable) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
get() {
const val = globalThis[nodeGlobalsKey];
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
value: val,
writable: descriptor.writable === true || nodeGlobalsKey === "performance"
});
return val;
},
set(val) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
value: val,
writable: true
});
}
});
} else if ("value" in descriptor) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: false,
enumerable: descriptor.enumerable,
value: descriptor.value,
writable: descriptor.writable
});
} else {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: false,
enumerable: descriptor.enumerable,
get: descriptor.get,
set: descriptor.set
});
}
}
}
global.global = global;
global.Buffer = Buffer;
global.ArrayBuffer = ArrayBuffer;
global.Uint8Array = Uint8Array;
return {
getVmContext() {
return context;
},
teardown() {
context = void 0;
global = void 0;
}
};
},
async setup(global) {
global.console.Console = Console;
return {
teardown(global2) {
delete global2.console.Console;
}
};
}
};
const LIVING_KEYS = [
"DOMException",
"URL",
"URLSearchParams",
"EventTarget",
"NamedNodeMap",
"Node",
"Attr",
"Element",
"DocumentFragment",
"DOMImplementation",
"Document",
"XMLDocument",
"CharacterData",
"Text",
"CDATASection",
"ProcessingInstruction",
"Comment",
"DocumentType",
"NodeList",
"RadioNodeList",
"HTMLCollection",
"HTMLOptionsCollection",
"DOMStringMap",
"DOMTokenList",
"StyleSheetList",
"HTMLElement",
"HTMLHeadElement",
"HTMLTitleElement",
"HTMLBaseElement",
"HTMLLinkElement",
"HTMLMetaElement",
"HTMLStyleElement",
"HTMLBodyElement",
"HTMLHeadingElement",
"HTMLParagraphElement",
"HTMLHRElement",
"HTMLPreElement",
"HTMLUListElement",
"HTMLOListElement",
"HTMLLIElement",
"HTMLMenuElement",
"HTMLDListElement",
"HTMLDivElement",
"HTMLAnchorElement",
"HTMLAreaElement",
"HTMLBRElement",
"HTMLButtonElement",
"HTMLCanvasElement",
"HTMLDataElement",
"HTMLDataListElement",
"HTMLDetailsElement",
"HTMLDialogElement",
"HTMLDirectoryElement",
"HTMLFieldSetElement",
"HTMLFontElement",
"HTMLFormElement",
"HTMLHtmlElement",
"HTMLImageElement",
"HTMLInputElement",
"HTMLLabelElement",
"HTMLLegendElement",
"HTMLMapElement",
"HTMLMarqueeElement",
"HTMLMediaElement",
"HTMLMeterElement",
"HTMLModElement",
"HTMLOptGroupElement",
"HTMLOptionElement",
"HTMLOutputElement",
"HTMLPictureElement",
"HTMLProgressElement",
"HTMLQuoteElement",
"HTMLScriptElement",
"HTMLSelectElement",
"HTMLSlotElement",
"HTMLSourceElement",
"HTMLSpanElement",
"HTMLTableCaptionElement",
"HTMLTableCellElement",
"HTMLTableColElement",
"HTMLTableElement",
"HTMLTimeElement",
"HTMLTableRowElement",
"HTMLTableSectionElement",
"HTMLTemplateElement",
"HTMLTextAreaElement",
"HTMLUnknownElement",
"HTMLFrameElement",
"HTMLFrameSetElement",
"HTMLIFrameElement",
"HTMLEmbedElement",
"HTMLObjectElement",
"HTMLParamElement",
"HTMLVideoElement",
"HTMLAudioElement",
"HTMLTrackElement",
"HTMLFormControlsCollection",
"SVGElement",
"SVGGraphicsElement",
"SVGSVGElement",
"SVGTitleElement",
"SVGAnimatedString",
"SVGNumber",
"SVGStringList",
"Event",
"CloseEvent",
"CustomEvent",
"MessageEvent",
"ErrorEvent",
"HashChangeEvent",
"PopStateEvent",
"StorageEvent",
"ProgressEvent",
"PageTransitionEvent",
"SubmitEvent",
"UIEvent",
"FocusEvent",
"InputEvent",
"MouseEvent",
"KeyboardEvent",
"TouchEvent",
"CompositionEvent",
"WheelEvent",
"BarProp",
"External",
"Location",
"History",
"Screen",
"Crypto",
"Performance",
"Navigator",
"PluginArray",
"MimeTypeArray",
"Plugin",
"MimeType",
"FileReader",
"Blob",
"File",
"FileList",
"ValidityState",
"DOMParser",
"XMLSerializer",
"FormData",
"XMLHttpRequestEventTarget",
"XMLHttpRequestUpload",
"XMLHttpRequest",
"WebSocket",
"NodeFilter",
"NodeIterator",
"TreeWalker",
"AbstractRange",
"Range",
"StaticRange",
"Selection",
"Storage",
"CustomElementRegistry",
"ShadowRoot",
"MutationObserver",
"MutationRecord",
"Headers",
"AbortController",
"AbortSignal",
"Uint8Array",
"Uint16Array",
"Uint32Array",
"Uint8ClampedArray",
"Int8Array",
"Int16Array",
"Int32Array",
"Float32Array",
"Float64Array",
"ArrayBuffer",
"DOMRectReadOnly",
"DOMRect",
// not specified in docs, but is available
"Image",
"Audio",
"Option",
"CSS"
];
const OTHER_KEYS = [
"addEventListener",
"alert",
// 'atob',
"blur",
// 'btoa',
"cancelAnimationFrame",
/* 'clearInterval', */
/* 'clearTimeout', */
"close",
"confirm",
/* 'console', */
"createPopup",
"dispatchEvent",
"document",
"focus",
"frames",
"getComputedStyle",
"history",
"innerHeight",
"innerWidth",
"length",
"location",
"matchMedia",
"moveBy",
"moveTo",
"name",
"navigator",
"open",
"outerHeight",
"outerWidth",
"pageXOffset",
"pageYOffset",
"parent",
"postMessage",
"print",
"prompt",
"removeEventListener",
"requestAnimationFrame",
"resizeBy",
"resizeTo",
"screen",
"screenLeft",
"screenTop",
"screenX",
"screenY",
"scroll",
"scrollBy",
"scrollLeft",
"scrollTo",
"scrollTop",
"scrollX",
"scrollY",
"self",
/* 'setInterval', */
/* 'setTimeout', */
"stop",
/* 'toString', */
"top",
"Window",
"window"
];
const KEYS = LIVING_KEYS.concat(OTHER_KEYS);
const skipKeys = [
"window",
"self",
"top",
"parent"
];
function getWindowKeys(global, win, additionalKeys = []) {
const keysArray = [...additionalKeys, ...KEYS];
const keys = new Set(keysArray.concat(Object.getOwnPropertyNames(win)).filter((k) => {
if (skipKeys.includes(k))
return false;
if (k in global)
return keysArray.includes(k);
return true;
}));
return keys;
}
function isClassLikeName(name) {
return name[0] === name[0].toUpperCase();
}
function populateGlobal(global, win, options = {}) {
const { bindFunctions = false } = options;
const keys = getWindowKeys(global, win, options.additionalKeys);
const originals = /* @__PURE__ */ new Map();
const overrideObject = /* @__PURE__ */ new Map();
for (const key of keys) {
const boundFunction = bindFunctions && typeof win[key] === "function" && !isClassLikeName(key) && win[key].bind(win);
if (KEYS.includes(key) && key in global)
originals.set(key, global[key]);
Object.defineProperty(global, key, {
get() {
if (overrideObject.has(key))
return overrideObject.get(key);
if (boundFunction)
return boundFunction;
return win[key];
},
set(v) {
overrideObject.set(key, v);
},
configurable: true
});
}
global.window = global;
global.self = global;
global.top = global;
global.parent = global;
if (global.global)
global.global = global;
if (global.document && global.document.defaultView) {
Object.defineProperty(global.document, "defaultView", {
get: () => global,
enumerable: true,
configurable: true
});
}
skipKeys.forEach((k) => keys.add(k));
return {
keys,
skipKeys,
originals
};
}
function catchWindowErrors(window) {
let userErrorListenerCount = 0;
function throwUnhandlerError(e) {
if (userErrorListenerCount === 0 && e.error != null)
process.emit("uncaughtException", e.error);
}
const addEventListener = window.addEventListener.bind(window);
const removeEventListener = window.removeEventListener.bind(window);
window.addEventListener("error", throwUnhandlerError);
window.addEventListener = function(...args) {
if (args[0] === "error")
userErrorListenerCount++;
return addEventListener.apply(this, args);
};
window.removeEventListener = function(...args) {
if (args[0] === "error" && userErrorListenerCount)
userErrorListenerCount--;
return removeEventListener.apply(this, args);
};
return function clearErrorHandlers() {
window.removeEventListener("error", throwUnhandlerError);
};
}
var jsdom = {
name: "jsdom",
transformMode: "web",
async setupVM({ jsdom = {} }) {
const {
CookieJar,
JSDOM,
ResourceLoader,
VirtualConsole
} = await import('jsdom');
const {
html = "<!DOCTYPE html>",
userAgent,
url = "http://localhost:3000",
contentType = "text/html",
pretendToBeVisual = true,
includeNodeLocations = false,
runScripts = "dangerously",
resources,
console = false,
cookieJar = false,
...restOptions
} = jsdom;
let dom = new JSDOM(
html,
{
pretendToBeVisual,
resources: resources ?? (userAgent ? new ResourceLoader({ userAgent }) : void 0),
runScripts,
url,
virtualConsole: console && globalThis.console ? new VirtualConsole().sendTo(globalThis.console) : void 0,
cookieJar: cookieJar ? new CookieJar() : void 0,
includeNodeLocations,
contentType,
userAgent,
...restOptions
}
);
const clearWindowErrors = catchWindowErrors(dom.window);
dom.window.Buffer = Buffer;
dom.window.jsdom = dom;
const globalNames = [
"structuredClone",
"fetch",
"Request",
"Response",
"BroadcastChannel",
"MessageChannel",
"MessagePort",
"TextEncoder",
"TextDecoder"
];
for (const name of globalNames) {
const value = globalThis[name];
if (typeof value !== "undefined" && typeof dom.window[name] === "undefined")
dom.window[name] = value;
}
return {
getVmContext() {
return dom.getInternalVMContext();
},
teardown() {
clearWindowErrors();
dom.window.close();
dom = void 0;
}
};
},
async setup(global, { jsdom = {} }) {
const {
CookieJar,
JSDOM,
ResourceLoader,
VirtualConsole
} = await import('jsdom');
const {
html = "<!DOCTYPE html>",
userAgent,
url = "http://localhost:3000",
contentType = "text/html",
pretendToBeVisual = true,
includeNodeLocations = false,
runScripts = "dangerously",
resources,
console = false,
cookieJar = false,
...restOptions
} = jsdom;
const dom = new JSDOM(
html,
{
pretendToBeVisual,
resources: resources ?? (userAgent ? new ResourceLoader({ userAgent }) : void 0),
runScripts,
url,
virtualConsole: console && global.console ? new VirtualConsole().sendTo(global.console) : void 0,
cookieJar: cookieJar ? new CookieJar() : void 0,
includeNodeLocations,
contentType,
userAgent,
...restOptions
}
);
const { keys, originals } = populateGlobal(global, dom.window, { bindFunctions: true });
const clearWindowErrors = catchWindowErrors(global);
global.jsdom = dom;
return {
teardown(global2) {
clearWindowErrors();
dom.window.close();
delete global2.jsdom;
keys.forEach((key) => delete global2[key]);
originals.forEach((v, k) => global2[k] = v);
}
};
}
};
async function teardownWindow(win) {
if (win.close && win.happyDOM.abort) {
await win.happyDOM.abort();
win.close();
} else {
win.happyDOM.cancelAsync();
}
}
var happy = {
name: "happy-dom",
transformMode: "web",
async setupVM({ happyDOM = {} }) {
const { Window } = await import('happy-dom');
let win = new Window({
...happyDOM,
console: console && globalThis.console ? globalThis.console : void 0,
url: happyDOM.url || "http://localhost:3000",
settings: {
...happyDOM.settings,
disableErrorCapturing: true
}
});
win.Buffer = Buffer;
if (typeof structuredClone !== "undefined" && !win.structuredClone)
win.structuredClone = structuredClone;
return {
getVmContext() {
return win;
},
async teardown() {
await teardownWindow(win);
win = void 0;
}
};
},
async setup(global, { happyDOM = {} }) {
const { Window, GlobalWindow } = await import('happy-dom');
const win = new (GlobalWindow || Window)({
...happyDOM,
console: console && global.console ? global.console : void 0,
url: happyDOM.url || "http://localhost:3000",
settings: {
...happyDOM.settings,
disableErrorCapturing: true
}
});
const { keys, originals } = populateGlobal(global, win, {
bindFunctions: true,
// jsdom doesn't support Request and Response, but happy-dom does
additionalKeys: ["Request", "Response"]
});
return {
async teardown(global2) {
await teardownWindow(win);
keys.forEach((key) => delete global2[key]);
originals.forEach((v, k) => global2[k] = v);
}
};
}
};
var edge = {
name: "edge-runtime",
transformMode: "ssr",
async setupVM() {
const { EdgeVM } = await import('@edge-runtime/vm');
const vm = new EdgeVM({
extend: (context) => {
context.global = context;
context.Buffer = Buffer;
return context;
}
});
return {
getVmContext() {
return vm.context;
},
teardown() {
}
};
},
async setup(global) {
const { EdgeVM } = await import('@edge-runtime/vm');
const vm = new EdgeVM({
extend: (context) => {
context.global = context;
context.Buffer = Buffer;
KEYS.forEach((key) => {
if (key in global)
context[key] = global[key];
});
return context;
}
});
const { keys, originals } = populateGlobal(global, vm.context, { bindFunctions: true });
return {
teardown(global2) {
keys.forEach((key) => delete global2[key]);
originals.forEach((v, k) => global2[k] = v);
}
};
}
};
const environments = {
node,
jsdom,
"happy-dom": happy,
"edge-runtime": edge
};
const envPackageNames = {
"jsdom": "jsdom",
"happy-dom": "happy-dom",
"edge-runtime": "@edge-runtime/vm"
};
function getEnvPackageName(env) {
if (env === "node")
return null;
if (env in envPackageNames)
return envPackageNames[env];
if (env[0] === "." || env[0] === "/")
return null;
return `vitest-environment-${env}`;
}
export { environments as e, getEnvPackageName as g, populateGlobal as p };

View File

@ -0,0 +1,12 @@
/*
@license
Rollup.js v4.12.0
Fri, 16 Feb 2024 13:31:42 GMT - commit 0146b84be33a8416b4df4b9382549a7ca19dd64a
https://github.com/rollup/rollup
Released under the MIT License.
*/
import '../native.js';
export { parseAst, parseAstAsync } from './shared/parseAst.js';
import 'node:path';

View File

@ -0,0 +1,109 @@
import { promises } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { gzip, constants } from 'node:zlib';
import { resolve, basename, dirname, relative } from 'pathe';
import c from 'picocolors';
import fg from 'fast-glob';
import { stringify } from 'flatted';
async function getModuleGraph(ctx, id) {
const graph = {};
const externalized = /* @__PURE__ */ new Set();
const inlined = /* @__PURE__ */ new Set();
function clearId(id2) {
return id2?.replace(/\?v=\w+$/, "") || "";
}
async function get(mod, seen = /* @__PURE__ */ new Map()) {
if (!mod || !mod.id)
return;
if (seen.has(mod))
return seen.get(mod);
let id2 = clearId(mod.id);
seen.set(mod, id2);
const rewrote = await ctx.vitenode.shouldExternalize(id2);
if (rewrote) {
id2 = rewrote;
externalized.add(id2);
seen.set(mod, id2);
} else {
inlined.add(id2);
}
const mods = Array.from(mod.importedModules).filter((i) => i.id && !i.id.includes("/vitest/dist/"));
graph[id2] = (await Promise.all(mods.map((m) => get(m, seen)))).filter(Boolean);
return id2;
}
await get(ctx.server.moduleGraph.getModuleById(id));
return {
graph,
externalized: Array.from(externalized),
inlined: Array.from(inlined)
};
}
function getOutputFile(config) {
if (!config?.outputFile)
return;
if (typeof config.outputFile === "string")
return config.outputFile;
return config.outputFile.html;
}
const distDir = resolve(fileURLToPath(import.meta.url), "../../dist");
class HTMLReporter {
start = 0;
ctx;
reportUIPath;
options;
constructor(options) {
this.options = options;
}
async onInit(ctx) {
this.ctx = ctx;
this.start = Date.now();
}
async onFinished() {
const result = {
paths: this.ctx.state.getPaths(),
files: this.ctx.state.getFiles(),
config: this.ctx.config,
unhandledErrors: this.ctx.state.getUnhandledErrors(),
moduleGraph: {}
};
await Promise.all(
result.files.map(async (file) => {
result.moduleGraph[file.filepath] = await getModuleGraph(this.ctx, file.filepath);
})
);
await this.writeReport(stringify(result));
}
async writeReport(report) {
const htmlFile = this.options.outputFile || getOutputFile(this.ctx.config) || "html/index.html";
const htmlFileName = basename(htmlFile);
const htmlDir = resolve(this.ctx.config.root, dirname(htmlFile));
const metaFile = resolve(htmlDir, "html.meta.json.gz");
await promises.mkdir(resolve(htmlDir, "assets"), { recursive: true });
const promiseGzip = promisify(gzip);
const data = await promiseGzip(report, {
level: constants.Z_BEST_COMPRESSION
});
await promises.writeFile(metaFile, data, "base64");
const ui = resolve(distDir, "client");
const files = fg.sync("**/*", { cwd: ui });
await Promise.all(files.map(async (f) => {
if (f === "index.html") {
const html = await promises.readFile(resolve(ui, f), "utf-8");
const filePath = relative(htmlDir, metaFile);
await promises.writeFile(
resolve(htmlDir, htmlFileName),
html.replace("<!-- !LOAD_METADATA! -->", `<script>window.METADATA_PATH="${filePath}"<\/script>`)
);
} else {
await promises.copyFile(resolve(ui, f), resolve(htmlDir, f));
}
}));
this.ctx.logger.log(`${c.bold(c.inverse(c.magenta(" HTML ")))} ${c.magenta("Report is generated")}`);
this.ctx.logger.log(`${c.dim(" You can run ")}${c.bold(`npx vite preview --outDir ${relative(this.ctx.config.root, htmlDir)}`)}${c.dim(" to see the test results.")}`);
}
}
export { HTMLReporter as default };

View File

@ -0,0 +1,14 @@
interface SnapshotEnvironment {
getVersion: () => string;
getHeader: () => string;
resolvePath: (filepath: string) => Promise<string>;
resolveRawPath: (testPath: string, rawPath: string) => Promise<string>;
saveSnapshotFile: (filepath: string, snapshot: string) => Promise<void>;
readSnapshotFile: (filepath: string) => Promise<string | null>;
removeSnapshotFile: (filepath: string) => Promise<void>;
}
interface SnapshotEnvironmentOptions {
snapshotsDirName?: string;
}
export type { SnapshotEnvironment as S, SnapshotEnvironmentOptions as a };

View File

@ -0,0 +1,333 @@
// License: MIT
// Author: Anton Medvedev <anton@medv.io>
// Source: https://github.com/antonmedv/finder
type Knot = {
name: string
penalty: number
level?: number
}
type Path = Knot[]
export type Options = {
root: Element
idName: (name: string) => boolean
className: (name: string) => boolean
tagName: (name: string) => boolean
attr: (name: string, value: string) => boolean
seedMinLength: number
optimizedMinLength: number
threshold: number
maxNumberOfTries: number
}
let config: Options
let rootDocument: Document | Element
export function finder(input: Element, options?: Partial<Options>) {
if (input.nodeType !== Node.ELEMENT_NODE) {
throw new Error(`Can't generate CSS selector for non-element node type.`)
}
if ('html' === input.tagName.toLowerCase()) {
return 'html'
}
const defaults: Options = {
root: document.body,
idName: (name: string) => true,
className: (name: string) => true,
tagName: (name: string) => true,
attr: (name: string, value: string) => false,
seedMinLength: 1,
optimizedMinLength: 2,
threshold: 1000,
maxNumberOfTries: 10000,
}
config = {...defaults, ...options}
rootDocument = findRootDocument(config.root, defaults)
let path =
bottomUpSearch(input, 'all',
() => bottomUpSearch(input, 'two',
() => bottomUpSearch(input, 'one',
() => bottomUpSearch(input, 'none'))))
if (path) {
const optimized = sort(optimize(path, input))
if (optimized.length > 0) {
path = optimized[0]
}
return selector(path)
} else {
throw new Error(`Selector was not found.`)
}
}
function findRootDocument(rootNode: Element | Document, defaults: Options) {
if (rootNode.nodeType === Node.DOCUMENT_NODE) {
return rootNode
}
if (rootNode === defaults.root) {
return rootNode.ownerDocument as Document
}
return rootNode
}
function bottomUpSearch(
input: Element,
limit: 'all' | 'two' | 'one' | 'none',
fallback?: () => Path | null
): Path | null {
let path: Path | null = null
let stack: Knot[][] = []
let current: Element | null = input
let i = 0
while (current) {
let level: Knot[] = maybe(id(current)) ||
maybe(...attr(current)) ||
maybe(...classNames(current)) ||
maybe(tagName(current)) || [any()]
const nth = index(current)
if (limit == 'all') {
if (nth) {
level = level.concat(
level.filter(dispensableNth).map((node) => nthChild(node, nth))
)
}
} else if (limit == 'two') {
level = level.slice(0, 1)
if (nth) {
level = level.concat(
level.filter(dispensableNth).map((node) => nthChild(node, nth))
)
}
} else if (limit == 'one') {
const [node] = (level = level.slice(0, 1))
if (nth && dispensableNth(node)) {
level = [nthChild(node, nth)]
}
} else if (limit == 'none') {
level = [any()]
if (nth) {
level = [nthChild(level[0], nth)]
}
}
for (let node of level) {
node.level = i
}
stack.push(level)
if (stack.length >= config.seedMinLength) {
path = findUniquePath(stack, fallback)
if (path) {
break
}
}
current = current.parentElement
i++
}
if (!path) {
path = findUniquePath(stack, fallback)
}
if (!path && fallback) {
return fallback()
}
return path
}
function findUniquePath(
stack: Knot[][],
fallback?: () => Path | null
): Path | null {
const paths = sort(combinations(stack))
if (paths.length > config.threshold) {
return fallback ? fallback() : null
}
for (let candidate of paths) {
if (unique(candidate)) {
return candidate
}
}
return null
}
function selector(path: Path): string {
let node = path[0]
let query = node.name
for (let i = 1; i < path.length; i++) {
const level = path[i].level || 0
if (node.level === level - 1) {
query = `${path[i].name} > ${query}`
} else {
query = `${path[i].name} ${query}`
}
node = path[i]
}
return query
}
function penalty(path: Path): number {
return path.map((node) => node.penalty).reduce((acc, i) => acc + i, 0)
}
function unique(path: Path) {
const css = selector(path)
switch (rootDocument.querySelectorAll(css).length) {
case 0:
throw new Error(
`Can't select any node with this selector: ${css}`
)
case 1:
return true
default:
return false
}
}
function id(input: Element): Knot | null {
const elementId = input.getAttribute('id')
if (elementId && config.idName(elementId)) {
return {
name: '#' + CSS.escape(elementId),
penalty: 0,
}
}
return null
}
function attr(input: Element): Knot[] {
const attrs = Array.from(input.attributes).filter((attr) =>
config.attr(attr.name, attr.value)
)
return attrs.map(
(attr): Knot => ({
name: `[${CSS.escape(attr.name)}="${CSS.escape(attr.value)}"]`,
penalty: 0.5,
})
)
}
function classNames(input: Element): Knot[] {
const names = Array.from(input.classList).filter(config.className)
return names.map(
(name): Knot => ({
name: '.' + CSS.escape(name),
penalty: 1,
})
)
}
function tagName(input: Element): Knot | null {
const name = input.tagName.toLowerCase()
if (config.tagName(name)) {
return {
name,
penalty: 2,
}
}
return null
}
function any(): Knot {
return {
name: '*',
penalty: 3,
}
}
function index(input: Element): number | null {
const parent = input.parentNode
if (!parent) {
return null
}
let child = parent.firstChild
if (!child) {
return null
}
let i = 0
while (child) {
if (child.nodeType === Node.ELEMENT_NODE) {
i++
}
if (child === input) {
break
}
child = child.nextSibling
}
return i
}
function nthChild(node: Knot, i: number): Knot {
return {
name: node.name + `:nth-child(${i})`,
penalty: node.penalty + 1,
}
}
function dispensableNth(node: Knot) {
return node.name !== 'html' && !node.name.startsWith('#')
}
function maybe(...level: (Knot | null)[]): Knot[] | null {
const list = level.filter(notEmpty)
if (list.length > 0) {
return list
}
return null
}
function notEmpty<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined
}
function* combinations(stack: Knot[][], path: Knot[] = []): Generator<Knot[]> {
if (stack.length > 0) {
for (let node of stack[0]) {
yield* combinations(stack.slice(1, stack.length), path.concat(node))
}
} else {
yield path
}
}
function sort(paths: Iterable<Path>): Path[] {
return [...paths].sort((a, b) => penalty(a) - penalty(b))
}
type Scope = {
counter: number
visited: Map<string, boolean>
}
function* optimize(
path: Path,
input: Element,
scope: Scope = {
counter: 0,
visited: new Map<string, boolean>(),
}
): Generator<Knot[]> {
if (path.length > 2 && path.length > config.optimizedMinLength) {
for (let i = 1; i < path.length - 1; i++) {
if (scope.counter > config.maxNumberOfTries) {
return // Okay At least I tried!
}
scope.counter += 1
const newPath = [...path]
newPath.splice(i, 1)
const newPathKey = selector(newPath)
if (scope.visited.has(newPathKey)) {
return
}
if (unique(newPath) && same(newPath, input)) {
yield newPath
scope.visited.set(newPathKey, true)
yield* optimize(newPath, input, scope)
}
}
}
}
function same(path: Path, input: Element) {
return rootDocument.querySelector(selector(path)) === input
}

View File

@ -0,0 +1,20 @@
---
import type { HTMLAttributes } from "astro/types";
const { props } = Astro;
type Link = HTMLAttributes<"link">;
---
{props.extend.link?.map((attributes: Link) => <link {...attributes} />)}
{
props.extend.meta?.map(({ content, httpEquiv, media, name, property }) => (
<meta
name={name}
property={property}
content={content}
http-equiv={httpEquiv}
media={media}
/>
))
}

View File

@ -0,0 +1,64 @@
const defaultPort = 51204;
const defaultBrowserPort = 63315;
const EXIT_CODE_RESTART = 43;
const API_PATH = "/__vitest_api__";
const extraInlineDeps = [
/^(?!.*(?:node_modules)).*\.mjs$/,
/^(?!.*(?:node_modules)).*\.cjs\.js$/,
// Vite client
/vite\w*\/dist\/client\/env.mjs/,
// Nuxt
"@nuxt/test-utils"
];
const CONFIG_NAMES = [
"vitest.config",
"vite.config"
];
const WORKSPACES_NAMES = [
"vitest.workspace",
"vitest.projects"
];
const CONFIG_EXTENSIONS = [
".ts",
".mts",
".cts",
".js",
".mjs",
".cjs"
];
const configFiles = CONFIG_NAMES.flatMap(
(name) => CONFIG_EXTENSIONS.map((ext) => name + ext)
);
const WORKSPACES_EXTENSIONS = [
...CONFIG_EXTENSIONS,
".json"
];
const workspacesFiles = WORKSPACES_NAMES.flatMap(
(name) => WORKSPACES_EXTENSIONS.map((ext) => name + ext)
);
const globalApis = [
// suite
"suite",
"test",
"describe",
"it",
// chai
"chai",
"expect",
"assert",
// typecheck
"expectTypeOf",
"assertType",
// utils
"vitest",
"vi",
// hooks
"beforeAll",
"afterAll",
"beforeEach",
"afterEach",
"onTestFinished",
"onTestFailed"
];
export { API_PATH as A, CONFIG_NAMES as C, EXIT_CODE_RESTART as E, defaultBrowserPort as a, configFiles as c, defaultPort as d, extraInlineDeps as e, globalApis as g, workspacesFiles as w };

View File

@ -0,0 +1 @@
{"files":{"package.json":{"checkedAt":1708389320419,"integrity":"sha512-2MJqk4jrPDh2/pcjHTIWJU2p63gAsIWiUcLvR08MIl78pgqAXPd3V/XV9kyLogTt40nvZj0Fv3Hyu1cqeb4zAg==","mode":420,"size":419},"README.md":{"checkedAt":1708389320420,"integrity":"sha512-5w0clYQzWCpPCMzdiw6R3wJDz9Xxt/3KdT5wZVKCz70lV7VB8JZ1W1n7kCcsC2/P+zGQxwmdlqbLWiAt92hzjw==","mode":420,"size":97},"rollup.linux-x64-musl.node":{"checkedAt":1708389320427,"integrity":"sha512-+pOX/0L0iIOpY/Z844gsliuK+Qc7DKwRn01o3Q06SsyBn3RikshSdjj1GVbYurhfeHwp7xyq+2/VR6n42y73wA==","mode":420,"size":2726936}}}

View File

@ -0,0 +1,2 @@
import type { IImage } from './interface.ts';
export declare const JP2: IImage;

View File

@ -0,0 +1,4 @@
var astro_island_prebuilt_default = `(()=>{var v=Object.defineProperty;var A=(c,s,a)=>s in c?v(c,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):c[s]=a;var d=(c,s,a)=>(A(c,typeof s!="symbol"?s+"":s,a),a);var u;{let c={0:t=>m(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t)},s=t=>{let[e,n]=t;return e in c?c[e](n):void 0},a=t=>t.map(s),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([e,n])=>[e,s(n)]));customElements.get("astro-island")||customElements.define("astro-island",(u=class extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var f;if(!this.hydrator||!this.isConnected)return;let e=(f=this.parentElement)==null?void 0:f.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let n=this.querySelectorAll("astro-slot"),r={},l=this.querySelectorAll("template[data-astro-template]");for(let o of l){let i=o.closest(this.tagName);i!=null&&i.isSameNode(this)&&(r[o.getAttribute("data-astro-template")||"default"]=o.innerHTML,o.remove())}for(let o of n){let i=o.closest(this.tagName);i!=null&&i.isSameNode(this)&&(r[o.getAttribute("name")||"default"]=o.innerHTML)}let h;try{h=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(o){let i=this.getAttribute("component-url")||"<unknown>",b=this.getAttribute("component-export");throw b&&(i+=\` (export \${b})\`),console.error(\`[hydrate] Error parsing props for component \${i}\`,this.getAttribute("props"),o),o}let p;await this.hydrator(this)(this.Component,h,r,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});d(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),n.disconnect(),this.childrenConnectedCallback()},n=new MutationObserver(()=>{var r;((r=this.lastChild)==null?void 0:r.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});n.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),n=this.getAttribute("client");if(Astro[n]===void 0){window.addEventListener(\`astro:\${n}\`,()=>this.start(),{once:!0});return}try{await Astro[n](async()=>{let r=this.getAttribute("renderer-url"),[l,{default:h}]=await Promise.all([import(this.getAttribute("component-url")),r?import(r):()=>()=>{}]),p=this.getAttribute("component-export")||"default";if(!p.includes("."))this.Component=l[p];else{this.Component=l;for(let y of p.split("."))this.Component=this.Component[y]}return this.hydrator=h,this.hydrate},e,this)}catch(r){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,r)}}attributeChangedCallback(){this.hydrate()}},d(u,"observedAttributes",["props"]),u))}})();`;
export {
astro_island_prebuilt_default as default
};

View File

@ -0,0 +1,2 @@
import type { IImage } from './interface.ts';
export declare const HEIF: IImage;

View File

@ -0,0 +1,24 @@
import { typeHandlers, types } from "./types/index.js";
const firstBytes = /* @__PURE__ */ new Map([
[56, "psd"],
[66, "bmp"],
[68, "dds"],
[71, "gif"],
[73, "tiff"],
[77, "tiff"],
[82, "webp"],
[105, "icns"],
[137, "png"],
[255, "jpg"]
]);
function detector(input) {
const byte = input[0];
const type = firstBytes.get(byte);
if (type && typeHandlers.get(type).validate(input)) {
return type;
}
return types.find((fileType) => typeHandlers.get(fileType).validate(input));
}
export {
detector
};

View File

@ -0,0 +1,2 @@
import type { IImage } from './interface.ts';
export declare const PSD: IImage;

View File

@ -0,0 +1,36 @@
import { a as createThreadsRpcOptions } from '../vendor/utils.GbToHGHI.js';
import { r as runVmTests } from '../vendor/vm.UmCkcXp-.js';
import '@vitest/utils';
import 'node:vm';
import 'node:url';
import 'pathe';
import '../chunks/runtime-console.Iloo9fIt.js';
import 'node:stream';
import 'node:console';
import 'node:path';
import '../vendor/date.Ns1pGd_X.js';
import '../vendor/execute.aFSzc0Da.js';
import 'vite-node/client';
import 'vite-node/utils';
import '@vitest/utils/error';
import '../path.js';
import 'node:fs';
import '../vendor/base.knFzp7G3.js';
import 'node:module';
import 'vite-node/constants';
import '../vendor/index.ir9i0ywP.js';
import 'std-env';
import '@vitest/runner/utils';
import '../vendor/global.CkGT_TMy.js';
class ThreadsVmWorker {
getRpcOptions(ctx) {
return createThreadsRpcOptions(ctx);
}
runTests(state) {
return runVmTests(state);
}
}
var vmThreads = new ThreadsVmWorker();
export { vmThreads as default };

View File

@ -0,0 +1,17 @@
const ASTRO_VERSION = "4.4.0";
const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
".markdown",
".mdown",
".mkdn",
".mkd",
".mdwn",
".md"
];
const MIDDLEWARE_PATH_SEGMENT_NAME = "middleware";
const ROUTE_DATA_SYMBOL = "astro.routeData";
export {
ASTRO_VERSION,
MIDDLEWARE_PATH_SEGMENT_NAME,
ROUTE_DATA_SYMBOL,
SUPPORTED_MARKDOWN_FILE_EXTENSIONS
};

View File

@ -0,0 +1,38 @@
import { V as VitestRunMode, U as UserConfig, d as VitestOptions, e as Vitest, R as ResolvedConfig, P as ProvidedContext, W as WorkspaceProject, f as RuntimeRPC, T as TestSequencer, g as WorkspaceSpec } from './reporters-QGe8gs4b.js';
export { l as BrowserProvider, k as BrowserProviderInitializationOptions, m as BrowserProviderOptions, h as ProcessPool, j as TestSequencerConstructor, i as VitestPackageInstaller, s as startVitest } from './reporters-QGe8gs4b.js';
import { UserConfig as UserConfig$1, Plugin } from 'vite';
import '@vitest/runner';
import 'vite-node';
import '@vitest/snapshot';
import '@vitest/expect';
import '@vitest/runner/utils';
import '@vitest/utils';
import 'tinybench';
import 'vite-node/client';
import '@vitest/snapshot/manager';
import 'vite-node/server';
import 'node:worker_threads';
import 'node:fs';
import 'chai';
declare function createVitest(mode: VitestRunMode, options: UserConfig, viteOverrides?: UserConfig$1, vitestOptions?: VitestOptions): Promise<Vitest>;
declare function VitestPlugin(options?: UserConfig, ctx?: Vitest): Promise<Plugin[]>;
declare function registerConsoleShortcuts(ctx: Vitest): () => void;
interface GlobalSetupContext {
config: ResolvedConfig;
provide: <T extends keyof ProvidedContext>(key: T, value: ProvidedContext[T]) => void;
}
declare function createMethodsRPC(project: WorkspaceProject): RuntimeRPC;
declare class BaseSequencer implements TestSequencer {
protected ctx: Vitest;
constructor(ctx: Vitest);
shard(files: WorkspaceSpec[]): Promise<WorkspaceSpec[]>;
sort(files: WorkspaceSpec[]): Promise<WorkspaceSpec[]>;
}
export { BaseSequencer, type GlobalSetupContext, TestSequencer, Vitest, VitestPlugin, WorkspaceProject, WorkspaceSpec, createMethodsRPC, createVitest, registerConsoleShortcuts };

View File

@ -0,0 +1,162 @@
import { B as BaseCoverageOptions, a as ResolvedCoverageOptions } from './reporters-QGe8gs4b.js';
import 'vite';
import '@vitest/runner';
import 'vite-node';
import '@vitest/snapshot';
import '@vitest/expect';
import '@vitest/runner/utils';
import '@vitest/utils';
import 'tinybench';
import 'vite-node/client';
import '@vitest/snapshot/manager';
import 'vite-node/server';
import 'node:worker_threads';
import 'node:fs';
import 'chai';
interface CoverageSummaryData {
lines: Totals;
statements: Totals;
branches: Totals;
functions: Totals;
}
declare class CoverageSummary {
constructor(data: CoverageSummary | CoverageSummaryData);
merge(obj: CoverageSummary): CoverageSummary;
toJSON(): CoverageSummaryData;
isEmpty(): boolean;
data: CoverageSummaryData;
lines: Totals;
statements: Totals;
branches: Totals;
functions: Totals;
}
interface CoverageMapData {
[key: string]: FileCoverage | FileCoverageData;
}
declare class CoverageMap {
constructor(data: CoverageMapData | CoverageMap);
addFileCoverage(pathOrObject: string | FileCoverage | FileCoverageData): void;
files(): string[];
fileCoverageFor(filename: string): FileCoverage;
filter(callback: (key: string) => boolean): void;
getCoverageSummary(): CoverageSummary;
merge(data: CoverageMapData | CoverageMap): void;
toJSON(): CoverageMapData;
data: CoverageMapData;
}
interface Location {
line: number;
column: number;
}
interface Range {
start: Location;
end: Location;
}
interface BranchMapping {
loc: Range;
type: string;
locations: Range[];
line: number;
}
interface FunctionMapping {
name: string;
decl: Range;
loc: Range;
line: number;
}
interface FileCoverageData {
path: string;
statementMap: { [key: string]: Range };
fnMap: { [key: string]: FunctionMapping };
branchMap: { [key: string]: BranchMapping };
s: { [key: string]: number };
f: { [key: string]: number };
b: { [key: string]: number[] };
}
interface Totals {
total: number;
covered: number;
skipped: number;
pct: number;
}
interface Coverage {
covered: number;
total: number;
coverage: number;
}
declare class FileCoverage implements FileCoverageData {
constructor(data: string | FileCoverage | FileCoverageData);
merge(other: FileCoverageData): void;
getBranchCoverageByLine(): { [line: number]: Coverage };
getLineCoverage(): { [line: number]: number };
getUncoveredLines(): number[];
resetHits(): void;
computeBranchTotals(): Totals;
computeSimpleTotals(): Totals;
toSummary(): CoverageSummary;
toJSON(): object;
data: FileCoverageData;
path: string;
statementMap: { [key: string]: Range };
fnMap: { [key: string]: FunctionMapping };
branchMap: { [key: string]: BranchMapping };
s: { [key: string]: number };
f: { [key: string]: number };
b: { [key: string]: number[] };
}
type Threshold = 'lines' | 'functions' | 'statements' | 'branches';
interface ResolvedThreshold {
coverageMap: CoverageMap;
name: string;
thresholds: Partial<Record<Threshold, number | undefined>>;
}
declare class BaseCoverageProvider {
/**
* Check if current coverage is above configured thresholds and bump the thresholds if needed
*/
updateThresholds({ thresholds: allThresholds, perFile, configurationFile }: {
thresholds: ResolvedThreshold[];
perFile?: boolean;
configurationFile: {
read: () => unknown;
write: () => void;
};
}): void;
/**
* Check collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
*/
checkThresholds({ thresholds: allThresholds, perFile }: {
thresholds: ResolvedThreshold[];
perFile?: boolean;
}): void;
/**
* Constructs collected coverage and users' threshold options into separate sets
* where each threshold set holds their own coverage maps. Threshold set is either
* for specific files defined by glob pattern or global for all other files.
*/
resolveThresholds({ coverageMap, thresholds, createCoverageMap }: {
coverageMap: CoverageMap;
thresholds: NonNullable<BaseCoverageOptions['thresholds']>;
createCoverageMap: () => CoverageMap;
}): ResolvedThreshold[];
/**
* Resolve reporters from various configuration options
*/
resolveReporters(configReporters: NonNullable<BaseCoverageOptions['reporter']>): ResolvedCoverageOptions['reporter'];
}
export { BaseCoverageProvider };

View File

@ -0,0 +1,35 @@
import { lookup } from "./vendor/image-size/lookup.js";
async function probe(url) {
const response = await fetch(url);
if (!response.body || !response.ok) {
throw new Error("Failed to fetch image");
}
const reader = response.body.getReader();
let done, value;
let accumulatedChunks = new Uint8Array();
while (!done) {
const readResult = await reader.read();
done = readResult.done;
if (done)
break;
if (readResult.value) {
value = readResult.value;
let tmp = new Uint8Array(accumulatedChunks.length + value.length);
tmp.set(accumulatedChunks, 0);
tmp.set(value, accumulatedChunks.length);
accumulatedChunks = tmp;
try {
const dimensions = lookup(accumulatedChunks);
if (dimensions) {
await reader.cancel();
return dimensions;
}
} catch (error) {
}
}
}
throw new Error("Failed to parse the size");
}
export {
probe
};

View File

@ -0,0 +1,12 @@
import { toUTF8String, readUInt16LE } from "./utils.js";
const gifRegexp = /^GIF8[79]a/;
const GIF = {
validate: (input) => gifRegexp.test(toUTF8String(input, 0, 6)),
calculate: (input) => ({
height: readUInt16LE(input, 8),
width: readUInt16LE(input, 6)
})
};
export {
GIF
};

View File

@ -0,0 +1,129 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, suite, test } from '@vitest/runner';
import { b as bench } from './benchmark.eeqk2rd8.js';
import { i as isFirstRun, a as runOnce } from './run-once.Olz_Zkd8.js';
import { c as createExpect, a as globalExpect, v as vi, b as vitest } from './vi.-Nr_x6dl.js';
import { g as getWorkerState } from './global.CkGT_TMy.js';
import * as chai from 'chai';
import { assert, should } from 'chai';
function getRunningMode() {
return process.env.VITEST_MODE === "WATCH" ? "watch" : "run";
}
function isWatchMode() {
return getRunningMode() === "watch";
}
function inject(key) {
const workerState = getWorkerState();
return workerState.providedContext[key];
}
var dist = {};
(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.expectTypeOf = void 0;
const fn = () => true;
/**
* Similar to Jest's `expect`, but with type-awareness.
* Gives you access to a number of type-matchers that let you make assertions about the
* form of a reference or generic type parameter.
*
* @example
* import {foo, bar} from '../foo'
* import {expectTypeOf} from 'expect-type'
*
* test('foo types', () => {
* // make sure `foo` has type {a: number}
* expectTypeOf(foo).toMatchTypeOf({a: 1})
* expectTypeOf(foo).toHaveProperty('a').toBeNumber()
*
* // make sure `bar` is a function taking a string:
* expectTypeOf(bar).parameter(0).toBeString()
* expectTypeOf(bar).returns.not.toBeAny()
* })
*
* @description
* See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples.
*/
const expectTypeOf = (_actual) => {
const nonFunctionProperties = [
'parameters',
'returns',
'resolves',
'not',
'items',
'constructorParameters',
'thisParameter',
'instance',
'guards',
'asserts',
'branded',
];
const obj = {
/* eslint-disable mmkal/@typescript-eslint/no-unsafe-assignment */
toBeAny: fn,
toBeUnknown: fn,
toBeNever: fn,
toBeFunction: fn,
toBeObject: fn,
toBeArray: fn,
toBeString: fn,
toBeNumber: fn,
toBeBoolean: fn,
toBeVoid: fn,
toBeSymbol: fn,
toBeNull: fn,
toBeUndefined: fn,
toBeNullable: fn,
toMatchTypeOf: fn,
toEqualTypeOf: fn,
toBeCallableWith: fn,
toBeConstructibleWith: fn,
/* eslint-enable mmkal/@typescript-eslint/no-unsafe-assignment */
extract: exports.expectTypeOf,
exclude: exports.expectTypeOf,
toHaveProperty: exports.expectTypeOf,
parameter: exports.expectTypeOf,
};
const getterProperties = nonFunctionProperties;
getterProperties.forEach((prop) => Object.defineProperty(obj, prop, { get: () => (0, exports.expectTypeOf)({}) }));
return obj;
};
exports.expectTypeOf = expectTypeOf;
} (dist));
function noop() {
}
const assertType = noop;
var VitestIndex = /*#__PURE__*/Object.freeze({
__proto__: null,
afterAll: afterAll,
afterEach: afterEach,
assert: assert,
assertType: assertType,
beforeAll: beforeAll,
beforeEach: beforeEach,
bench: bench,
chai: chai,
createExpect: createExpect,
describe: describe,
expect: globalExpect,
expectTypeOf: dist.expectTypeOf,
getRunningMode: getRunningMode,
inject: inject,
isFirstRun: isFirstRun,
isWatchMode: isWatchMode,
it: it,
onTestFailed: onTestFailed,
onTestFinished: onTestFinished,
runOnce: runOnce,
should: should,
suite: suite,
test: test,
vi: vi,
vitest: vitest
});
export { VitestIndex as V, isWatchMode as a, assertType as b, dist as d, getRunningMode as g, inject as i };

View File

@ -0,0 +1,15 @@
import { readUInt16LE } from "./utils.js";
const TGA = {
validate(input) {
return readUInt16LE(input, 0) === 0 && readUInt16LE(input, 4) === 0;
},
calculate(input) {
return {
height: readUInt16LE(input, 14),
width: readUInt16LE(input, 12)
};
}
};
export {
TGA
};

View File

@ -0,0 +1,120 @@
import { B as SequenceHooks, G as SequenceSetupFiles, F as File, T as Task, S as Suite, o as TaskResultPack, a as Test, C as Custom, A as TaskContext, E as ExtendedContext } from './tasks-_kyNRBhz.js';
export { g as CustomAPI, D as DoneCallback, t as Fixture, s as FixtureFn, r as FixtureOptions, u as Fixtures, v as HookCleanupCallback, H as HookListener, I as InferFixturesTypes, O as OnTestFailedHandler, i as OnTestFinishedHandler, R as RunMode, y as RuntimeContext, d as SuiteAPI, f as SuiteCollector, x as SuiteFactory, h as SuiteHooks, k as TaskBase, w as TaskCustomOptions, m as TaskMeta, l as TaskPopulated, n as TaskResult, j as TaskState, e as TestAPI, z as TestContext, p as TestFunction, q as TestOptions, U as Use } from './tasks-_kyNRBhz.js';
import { DiffOptions } from '@vitest/utils/diff';
import '@vitest/utils';
interface VitestRunnerConfig {
root: string;
setupFiles: string[] | string;
name: string;
passWithNoTests: boolean;
testNamePattern?: RegExp;
allowOnly?: boolean;
sequence: {
shuffle?: boolean;
concurrent?: boolean;
seed: number;
hooks: SequenceHooks;
setupFiles: SequenceSetupFiles;
};
chaiConfig?: {
truncateThreshold?: number;
};
maxConcurrency: number;
testTimeout: number;
hookTimeout: number;
retry: number;
diffOptions?: DiffOptions;
}
type VitestRunnerImportSource = 'collect' | 'setup';
interface VitestRunnerConstructor {
new (config: VitestRunnerConfig): VitestRunner;
}
type CancelReason = 'keyboard-input' | 'test-failure' | string & Record<string, never>;
interface VitestRunner {
/**
* First thing that's getting called before actually collecting and running tests.
*/
onBeforeCollect?: (paths: string[]) => unknown;
/**
* Called after collecting tests and before "onBeforeRun".
*/
onCollected?: (files: File[]) => unknown;
/**
* Called when test runner should cancel next test runs.
* Runner should listen for this method and mark tests and suites as skipped in
* "onBeforeRunSuite" and "onBeforeRunTask" when called.
*/
onCancel?: (reason: CancelReason) => unknown;
/**
* Called before running a single test. Doesn't have "result" yet.
*/
onBeforeRunTask?: (test: Task) => unknown;
/**
* Called before actually running the test function. Already has "result" with "state" and "startTime".
*/
onBeforeTryTask?: (test: Task, options: {
retry: number;
repeats: number;
}) => unknown;
/**
* Called after result and state are set.
*/
onAfterRunTask?: (test: Task) => unknown;
/**
* Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
*/
onAfterTryTask?: (test: Task, options: {
retry: number;
repeats: number;
}) => unknown;
/**
* Called before running a single suite. Doesn't have "result" yet.
*/
onBeforeRunSuite?: (suite: Suite) => unknown;
/**
* Called after running a single suite. Has state and result.
*/
onAfterRunSuite?: (suite: Suite) => unknown;
/**
* If defined, will be called instead of usual Vitest suite partition and handling.
* "before" and "after" hooks will not be ignored.
*/
runSuite?: (suite: Suite) => Promise<void>;
/**
* If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
* "before" and "after" hooks will not be ignored.
*/
runTask?: (test: Task) => Promise<void>;
/**
* Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
*/
onTaskUpdate?: (task: TaskResultPack[]) => Promise<void>;
/**
* Called before running all tests in collected paths.
*/
onBeforeRunFiles?: (files: File[]) => unknown;
/**
* Called right after running all tests in collected paths.
*/
onAfterRunFiles?: (files: File[]) => unknown;
/**
* Called when new context for a test is defined. Useful, if you want to add custom properties to the context.
* If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead.
*
* This method is called for both "test" and "custom" handlers.
*
* @see https://vitest.dev/advanced/runner.html#your-task-function
*/
extendTaskContext?: <T extends Test | Custom>(context: TaskContext<T>) => ExtendedContext<T>;
/**
* Called, when files are imported. Can be called in two situations: when collecting tests and when importing setup files.
*/
importFile: (filepath: string, source: VitestRunnerImportSource) => unknown;
/**
* Publicly available configuration.
*/
config: VitestRunnerConfig;
}
export { type CancelReason, Custom, ExtendedContext, File, SequenceHooks, SequenceSetupFiles, Suite, Task, TaskContext, TaskResultPack, Test, type VitestRunner, type VitestRunnerConfig, type VitestRunnerConstructor, type VitestRunnerImportSource };

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Anton Medvedev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,99 @@
const DEFAULT_TIMEOUT = 6e4;
function defaultSerialize(i) {
return i;
}
const defaultDeserialize = defaultSerialize;
const { clearTimeout, setTimeout } = globalThis;
const random = Math.random.bind(Math);
function createBirpc(functions, options) {
const {
post,
on,
eventNames = [],
serialize = defaultSerialize,
deserialize = defaultDeserialize,
resolver,
timeout = DEFAULT_TIMEOUT
} = options;
const rpcPromiseMap = /* @__PURE__ */ new Map();
let _promise;
const rpc = new Proxy({}, {
get(_, method) {
if (method === "$functions")
return functions;
const sendEvent = (...args) => {
post(serialize({ m: method, a: args, t: "q" }));
};
if (eventNames.includes(method)) {
sendEvent.asEvent = sendEvent;
return sendEvent;
}
const sendCall = async (...args) => {
await _promise;
return new Promise((resolve, reject) => {
const id = nanoid();
let timeoutId;
if (timeout >= 0) {
timeoutId = setTimeout(() => {
try {
options.onTimeoutError?.(method, args);
throw new Error(`[birpc] timeout on calling "${method}"`);
} catch (e) {
reject(e);
}
rpcPromiseMap.delete(id);
}, timeout).unref?.();
}
rpcPromiseMap.set(id, { resolve, reject, timeoutId });
post(serialize({ m: method, a: args, i: id, t: "q" }));
});
};
sendCall.asEvent = sendEvent;
return sendCall;
}
});
_promise = on(async (data, ...extra) => {
const msg = deserialize(data);
if (msg.t === "q") {
const { m: method, a: args } = msg;
let result, error;
const fn = resolver ? resolver(method, functions[method]) : functions[method];
if (!fn) {
error = new Error(`[birpc] function "${method}" not found`);
} else {
try {
result = await fn.apply(rpc, args);
} catch (e) {
error = e;
}
}
if (msg.i) {
if (error && options.onError)
options.onError(error, method, args);
post(serialize({ t: "s", i: msg.i, r: result, e: error }), ...extra);
}
} else {
const { i: ack, r: result, e: error } = msg;
const promise = rpcPromiseMap.get(ack);
if (promise) {
clearTimeout(promise.timeoutId);
if (error)
promise.reject(error);
else
promise.resolve(result);
}
rpcPromiseMap.delete(ack);
}
});
return rpc;
}
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
function nanoid(size = 21) {
let id = "";
let i = size;
while (i--)
id += urlAlphabet[random() * 64 | 0];
return id;
}
export { createBirpc as c };

View File

@ -0,0 +1,465 @@
import {Syntax} from './options';
import {PromiseOr} from './util/promise_or';
/**
* Contextual information passed to {@link Importer.canonicalize} and {@link
* FileImporter.findFileUrl}. Not all importers will need this information to
* resolve loads, but some may find it useful.
*/
export interface CanonicalizeContext {
/**
* Whether this is being invoked because of a Sass
* `@import` rule, as opposed to a `@use` or `@forward` rule.
*
* This should *only* be used for determining whether or not to load
* [import-only files](https://sass-lang.com/documentation/at-rules/import#import-only-files).
*/
fromImport: boolean;
/**
* The canonical URL of the file that contains the load, if that information
* is available.
*
* For an {@link Importer}, this is only passed when the `url` parameter is a
* relative URL _or_ when its [URL scheme] is included in {@link
* Importer.nonCanonicalScheme}. This ensures that canonical URLs are always
* resolved the same way regardless of context.
*
* [URL scheme]: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL#scheme
*
* For a {@link FileImporter}, this is always available as long as Sass knows
* the canonical URL of the containing file.
*/
containingUrl: URL | null;
}
/**
* A special type of importer that redirects all loads to existing files on
* disk. Although this is less powerful than a full {@link Importer}, it
* automatically takes care of Sass features like resolving partials and file
* extensions and of loading the file from disk.
*
* Like all importers, this implements custom Sass loading logic for [`@use`
* rules](https://sass-lang.com/documentation/at-rules/use) and [`@import`
* rules](https://sass-lang.com/documentation/at-rules/import). It can be passed
* to {@link Options.importers} or {@link StringOptionsWithImporter.importer}.
*
* @typeParam sync - A `FileImporter<'sync'>`'s {@link findFileUrl} must return
* synchronously, but in return it can be passed to {@link compile} and {@link
* compileString} in addition to {@link compileAsync} and {@link
* compileStringAsync}.
*
* A `FileImporter<'async'>`'s {@link findFileUrl} may either return
* synchronously or asynchronously, but it can only be used with {@link
* compileAsync} and {@link compileStringAsync}.
*
* @example
*
* ```js
* const {pathToFileURL} = require('url');
*
* sass.compile('style.scss', {
* importers: [{
* // An importer that redirects relative URLs starting with "~" to
* // `node_modules`.
* findFileUrl(url) {
* if (!url.startsWith('~')) return null;
* return new URL(url.substring(1), pathToFileURL('node_modules'));
* }
* }]
* });
* ```
*
* @category Importer
*/
export interface FileImporter<
sync extends 'sync' | 'async' = 'sync' | 'async'
> {
/**
* A callback that's called to partially resolve a load (such as
* [`@use`](https://sass-lang.com/documentation/at-rules/use) or
* [`@import`](https://sass-lang.com/documentation/at-rules/import)) to a file
* on disk.
*
* Unlike an {@link Importer}, the compiler will automatically handle relative
* loads for a {@link FileImporter}. See {@link Options.importers} for more
* details on the way loads are resolved.
*
* @param url - The loaded URL. Since this might be relative, it's represented
* as a string rather than a {@link URL} object.
*
* @returns An absolute `file:` URL if this importer recognizes the `url`.
* This may be only partially resolved: the compiler will automatically look
* for [partials](https://sass-lang.com/documentation/at-rules/use#partials),
* [index files](https://sass-lang.com/documentation/at-rules/use#index-files),
* and file extensions based on the returned URL. An importer may also return
* a fully resolved URL if it so chooses.
*
* If this importer doesn't recognize the URL, it should return `null` instead
* to allow other importers or {@link Options.loadPaths | load paths} to
* handle it.
*
* This may also return a `Promise`, but if it does the importer may only be
* passed to {@link compileAsync} and {@link compileStringAsync}, not {@link
* compile} or {@link compileString}.
*
* @throws any - If this importer recognizes `url` but determines that it's
* invalid, it may throw an exception that will be wrapped by Sass. If the
* exception object has a `message` property, it will be used as the wrapped
* exception's message; otherwise, the exception object's `toString()` will be
* used. This means it's safe for importers to throw plain strings.
*/
findFileUrl(
url: string,
context: CanonicalizeContext
): PromiseOr<URL | null, sync>;
/** @hidden */
canonicalize?: never;
}
/**
* An object that implements custom Sass loading logic for [`@use`
* rules](https://sass-lang.com/documentation/at-rules/use) and [`@import`
* rules](https://sass-lang.com/documentation/at-rules/import). It can be passed
* to {@link Options.importers} or {@link StringOptionsWithImporter.importer}.
*
* Importers that simply redirect to files on disk are encouraged to use the
* {@link FileImporter} interface instead.
*
* ### Resolving a Load
*
* This is the process of resolving a load using a custom importer:
*
* - The compiler encounters `@use "db:foo/bar/baz"`.
* - It calls {@link canonicalize} with `"db:foo/bar/baz"`.
* - {@link canonicalize} returns `new URL("db:foo/bar/baz/_index.scss")`.
* - If the compiler has already loaded a stylesheet with this canonical URL, it
* re-uses the existing module.
* - Otherwise, it calls {@link load} with `new
* URL("db:foo/bar/baz/_index.scss")`.
* - {@link load} returns an {@link ImporterResult} that the compiler uses as
* the contents of the module.
*
* See {@link Options.importers} for more details on the way loads are resolved
* using multiple importers and load paths.
*
* @typeParam sync - An `Importer<'sync'>`'s {@link canonicalize} and {@link
* load} must return synchronously, but in return it can be passed to {@link
* compile} and {@link compileString} in addition to {@link compileAsync} and
* {@link compileStringAsync}.
*
* An `Importer<'async'>`'s {@link canonicalize} and {@link load} may either
* return synchronously or asynchronously, but it can only be used with {@link
* compileAsync} and {@link compileStringAsync}.
*
* @example
*
* ```js
* sass.compile('style.scss', {
* // An importer for URLs like `bgcolor:orange` that generates a
* // stylesheet with the given background color.
* importers: [{
* canonicalize(url) {
* if (!url.startsWith('bgcolor:')) return null;
* return new URL(url);
* },
* load(canonicalUrl) {
* return {
* contents: `body {background-color: ${canonicalUrl.pathname}}`,
* syntax: 'scss'
* };
* }
* }]
* });
* ```
*
* @category Importer
*/
export interface Importer<sync extends 'sync' | 'async' = 'sync' | 'async'> {
/**
* If `url` is recognized by this importer, returns its canonical format.
*
* If Sass has already loaded a stylesheet with the returned canonical URL, it
* re-uses the existing parse tree (and the loaded module for `@use`). This
* means that importers **must ensure** that the same canonical URL always
* refers to the same stylesheet, *even across different importers*. As such,
* importers are encouraged to use unique URL schemes to disambiguate between
* one another.
*
* As much as possible, custom importers should canonicalize URLs the same way
* as the built-in filesystem importer:
*
* - The importer should look for stylesheets by adding the prefix `_` to the
* URL's basename, and by adding the extensions `.sass` and `.scss` if the
* URL doesn't already have one of those extensions. For example, if the
* URL was `foo/bar/baz`, the importer would look for:
* - `foo/bar/baz.sass`
* - `foo/bar/baz.scss`
* - `foo/bar/_baz.sass`
* - `foo/bar/_baz.scss`
*
* If the URL was `foo/bar/baz.scss`, the importer would just look for:
* - `foo/bar/baz.scss`
* - `foo/bar/_baz.scss`
*
* If the importer finds a stylesheet at more than one of these URLs, it
* should throw an exception indicating that the URL is ambiguous. Note that
* if the extension is explicitly specified, a stylesheet with the opposite
* extension is allowed to exist.
*
* - If none of the possible paths is valid, the importer should perform the
* same resolution on the URL followed by `/index`. In the example above,
* it would look for:
* - `foo/bar/baz/index.sass`
* - `foo/bar/baz/index.scss`
* - `foo/bar/baz/_index.sass`
* - `foo/bar/baz/_index.scss`
*
* As above, if the importer finds a stylesheet at more than one of these
* URLs, it should throw an exception indicating that the import is
* ambiguous.
*
* If no stylesheets are found, the importer should return `null`.
*
* Calling {@link canonicalize} multiple times with the same URL must return
* the same result. Calling {@link canonicalize} with a URL returned by a
* previous call to {@link canonicalize} must return that URL.
*
* Relative loads in stylesheets loaded from an importer are handled by
* resolving the loaded URL relative to the canonical URL of the stylesheet
* that contains it, and passing that URL back to the importer's {@link
* canonicalize} method. For example, suppose the "Resolving a Load" example
* {@link Importer | above} returned a stylesheet that contained `@use
* "mixins"`:
*
* - The compiler resolves the URL `mixins` relative to the current
* stylesheet's canonical URL `db:foo/bar/baz/_index.scss` to get
* `db:foo/bar/baz/mixins`.
* - It calls {@link canonicalize} with `"db:foo/bar/baz/mixins"`.
* - {@link canonicalize} returns `new URL("db:foo/bar/baz/_mixins.scss")`.
*
* Because of this, {@link canonicalize} must return a meaningful result when
* called with a URL relative to one returned by an earlier call to {@link
* canonicalize}.
*
* @param url - The loaded URL. Since this might be relative, it's represented
* as a string rather than a {@link URL} object.
*
* @returns An absolute URL if this importer recognizes the `url`, or `null`
* if it doesn't. If this returns `null`, other importers or {@link
* Options.loadPaths | load paths} may handle the load.
*
* This may also return a `Promise`, but if it does the importer may only be
* passed to {@link compileAsync} and {@link compileStringAsync}, not {@link
* compile} or {@link compileString}.
*
* @throws any - If this importer recognizes `url` but determines that it's
* invalid, it may throw an exception that will be wrapped by Sass. If the
* exception object has a `message` property, it will be used as the wrapped
* exception's message; otherwise, the exception object's `toString()` will be
* used. This means it's safe for importers to throw plain strings.
*/
canonicalize(
url: string,
context: CanonicalizeContext
): PromiseOr<URL | null, sync>;
/**
* Loads the Sass text for the given `canonicalUrl`, or returns `null` if this
* importer can't find the stylesheet it refers to.
*
* @param canonicalUrl - The canonical URL of the stylesheet to load. This is
* guaranteed to come from a call to {@link canonicalize}, although not every
* call to {@link canonicalize} will result in a call to {@link load}.
*
* @returns The contents of the stylesheet at `canonicalUrl` if it can be
* loaded, or `null` if it can't.
*
* This may also return a `Promise`, but if it does the importer may only be
* passed to {@link compileAsync} and {@link compileStringAsync}, not {@link
* compile} or {@link compileString}.
*
* @throws any - If this importer finds a stylesheet at `url` but it fails to
* load for some reason, or if `url` is uniquely associated with this importer
* but doesn't refer to a real stylesheet, the importer may throw an exception
* that will be wrapped by Sass. If the exception object has a `message`
* property, it will be used as the wrapped exception's message; otherwise,
* the exception object's `toString()` will be used. This means it's safe for
* importers to throw plain strings.
*/
load(canonicalUrl: URL): PromiseOr<ImporterResult | null, sync>;
/** @hidden */
findFileUrl?: never;
/**
* A URL scheme or set of schemes (without the `:`) that this importer
* promises never to use for URLs returned by {@link canonicalize}. If it does
* return a URL with one of these schemes, that's an error.
*
* If this is set, any call to canonicalize for a URL with a non-canonical
* scheme will be passed {@link CanonicalizeContext.containingUrl} if it's
* known.
*
* These schemes may only contain lowercase ASCII letters, ASCII numerals,
* `+`, `-`, and `.`. They may not be empty.
*/
nonCanonicalScheme?: string | string[];
}
declare const nodePackageImporterKey: unique symbol;
/**
* The built-in Node.js package importer. This loads pkg: URLs from node_modules
* according to the standard Node.js resolution algorithm.
*
* A Node.js package importer is exposed as a class that can be added to the
* `importers` option.
*
*```js
* const sass = require('sass');
* sass.compileString('@use "pkg:vuetify', {
* importers: [new sass.NodePackageImporter()]
* });
*```
*
* ## Writing Sass packages
*
* Package authors can control what is exposed to their users through their
* `package.json` manifest. The recommended method is to add a `sass`
* conditional export to `package.json`.
*
* ```json
* // node_modules/uicomponents/package.json
* {
* "exports": {
* ".": {
* "sass": "./src/scss/index.scss",
* "import": "./dist/js/index.mjs",
* "default": "./dist/js/index.js"
* }
* }
* }
* ```
*
* This allows a package user to write `@use "pkg:uicomponents"` to load the
* file at `node_modules/uicomponents/src/scss/index.scss`.
*
* The Node.js package importer supports the variety of formats supported by
* Node.js [package entry points], allowing authors to expose multiple subpaths.
*
* [package entry points]:
* https://nodejs.org/api/packages.html#package-entry-points
*
* ```json
* // node_modules/uicomponents/package.json
* {
* "exports": {
* ".": {
* "sass": "./src/scss/index.scss",
* },
* "./colors": {
* "sass": "./src/scss/_colors.scss",
* },
* "./theme/*": {
* "sass": "./src/scss/theme/*.scss",
* },
* }
* }
* ```
*
* This allows a package user to write:
*
* - `@use "pkg:uicomponents";` to import the root export.
* - `@use "pkg:uicomponents/colors";` to import the colors partial.
* - `@use "pkg:uicomponents/theme/purple";` to import a purple theme.
*
* Note that while library users can rely on the importer to resolve
* [partials](https://sass-lang.com/documentation/at-rules/use#partials), [index
* files](https://sass-lang.com/documentation/at-rules/use#index-files), and
* extensions, library authors must specify the entire file path in `exports`.
*
* In addition to the `sass` condition, the `style` condition is also
* acceptable. Sass will match the `default` condition if it's a relevant file
* type, but authors are discouraged from relying on this. Notably, the key
* order matters, and the importer will resolve to the first value with a key
* that is `sass`, `style`, or `default`, so you should always put `default`
* last.
*
* To help package authors who haven't transitioned to package entry points
* using the `exports` field, the Node.js package importer provides several
* fallback options. If the `pkg:` URL does not have a subpath, the Node.js
* package importer will look for a `sass` or `style` key at the root of
* `package.json`.
*
* ```json
* // node_modules/uicomponents/package.json
* {
* "sass": "./src/scss/index.scss",
* }
* ```
*
* This allows a user to write `@use "pkg:uicomponents";` to import the
* `index.scss` file.
*
* Finally, the Node.js package importer will look for an `index` file at the
* package root, resolving partials and extensions. For example, if the file
* `_index.scss` exists in the package root of `uicomponents`, a user can import
* that with `@use "pkg:uicomponents";`.
*
* If a `pkg:` URL includes a subpath that doesn't have a match in package entry
* points, the Node.js importer will attempt to find that file relative to the
* package root, resolving for file extensions, partials and index files. For
* example, if the file `src/sass/_colors.scss` exists in the `uicomponents`
* package, a user can import that file using `@use
* "pkg:uicomponents/src/sass/colors";`.
*
* @compatibility dart: "2.0", node: false
* @category Importer
*/
export class NodePackageImporter {
/** Used to distinguish this type from any arbitrary object. */
private readonly [nodePackageImporterKey]: true;
/**
* The NodePackageImporter has an optional `entryPointDirectory` option, which
* is the directory where the Node Package Importer should start when
* resolving `pkg:` URLs in sources other than files on disk. This will be
* used as the `parentURL` in the [Node Module
* Resolution](https://nodejs.org/api/esm.html#resolution-algorithm-specification)
* algorithm.
*
* In order to be found by the Node Package Importer, a package will need to
* be inside a node_modules folder located in the `entryPointDirectory`, or
* one of its parent directories, up to the filesystem root.
*
* Relative paths will be resolved relative to the current working directory.
* If a path is not provided, the default value of `require.main.filename`
* will be used.
*/
constructor(entryPointDirectory?: string);
}
/**
* The result of successfully loading a stylesheet with an {@link Importer}.
*
* @category Importer
*/
export interface ImporterResult {
/** The contents of the stylesheet. */
contents: string;
/** The syntax with which to parse {@link contents}. */
syntax: Syntax;
/**
* The URL to use to link to the loaded stylesheet's source code in source
* maps. A `file:` URL is ideal because it's accessible to both browsers and
* other build tools, but an `http:` URL is also acceptable.
*
* If this isn't set, it defaults to a `data:` URL that contains the contents
* of the loaded stylesheet.
*/
sourceMapUrl?: URL;
}

View File

@ -0,0 +1,66 @@
import { readUInt, toHexString, toUTF8String } from "./utils.js";
function readIFD(input, isBigEndian) {
const ifdOffset = readUInt(input, 32, 4, isBigEndian);
return input.slice(ifdOffset + 2);
}
function readValue(input, isBigEndian) {
const low = readUInt(input, 16, 8, isBigEndian);
const high = readUInt(input, 16, 10, isBigEndian);
return (high << 16) + low;
}
function nextTag(input) {
if (input.length > 24) {
return input.slice(12);
}
}
function extractTags(input, isBigEndian) {
const tags = {};
let temp = input;
while (temp && temp.length) {
const code = readUInt(temp, 16, 0, isBigEndian);
const type = readUInt(temp, 16, 2, isBigEndian);
const length = readUInt(temp, 32, 4, isBigEndian);
if (code === 0) {
break;
} else {
if (length === 1 && (type === 3 || type === 4)) {
tags[code] = readValue(temp, isBigEndian);
}
temp = nextTag(temp);
}
}
return tags;
}
function determineEndianness(input) {
const signature = toUTF8String(input, 0, 2);
if ("II" === signature) {
return "LE";
} else if ("MM" === signature) {
return "BE";
}
}
const signatures = [
// '492049', // currently not supported
"49492a00",
// Little endian
"4d4d002a"
// Big Endian
// '4d4d002a', // BigTIFF > 4GB. currently not supported
];
const TIFF = {
validate: (input) => signatures.includes(toHexString(input, 0, 4)),
calculate(input) {
const isBigEndian = determineEndianness(input) === "BE";
const ifdBuffer = readIFD(input, isBigEndian);
const tags = extractTags(ifdBuffer, isBigEndian);
const width = tags[256];
const height = tags[257];
if (!width || !height) {
throw new TypeError("Invalid Tiff. Missing tags");
}
return { height, width };
}
};
export {
TIFF
};

View File

@ -0,0 +1,573 @@
import { bold } from "kleur/colors";
import { createRequire } from "module";
import nodeFs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { getPrerenderDefault } from "../../../prerender/utils.js";
import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from "../../constants.js";
import { MissingIndexForInternationalization } from "../../errors/errors-data.js";
import { AstroError } from "../../errors/index.js";
import { removeLeadingForwardSlash, slash } from "../../path.js";
import { resolvePages } from "../../util.js";
import { getRouteGenerator } from "./generator.js";
const require2 = createRequire(import.meta.url);
function countOccurrences(needle, haystack) {
let count = 0;
for (const hay of haystack) {
if (hay === needle)
count += 1;
}
return count;
}
function getParts(part, file) {
const result = [];
part.split(/\[(.+?\(.+?\)|.+?)\]/).map((str, i) => {
if (!str)
return;
const dynamic = i % 2 === 1;
const [, content] = dynamic ? /([^(]+)$/.exec(str) || [null, null] : [null, str];
if (!content || dynamic && !/^(?:\.\.\.)?[\w$]+$/.test(content)) {
throw new Error(`Invalid route ${file} \u2014 parameter name must match /^[a-zA-Z0-9_$]+$/`);
}
result.push({
content,
dynamic,
spread: dynamic && /^\.{3}.+$/.test(content)
});
});
return result;
}
function getPattern(segments, config, addTrailingSlash) {
const base = config.base;
const pathname = segments.map((segment) => {
if (segment.length === 1 && segment[0].spread) {
return "(?:\\/(.*?))?";
} else {
return "\\/" + segment.map((part) => {
if (part.spread) {
return "(.*?)";
} else if (part.dynamic) {
return "([^/]+?)";
} else {
return part.content.normalize().replace(/\?/g, "%3F").replace(/#/g, "%23").replace(/%5B/g, "[").replace(/%5D/g, "]").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
}).join("");
}
}).join("");
const trailing = addTrailingSlash && segments.length ? getTrailingSlashPattern(addTrailingSlash) : "$";
let initial = "\\/";
if (addTrailingSlash === "never" && base !== "/") {
initial = "";
}
return new RegExp(`^${pathname || initial}${trailing}`);
}
function getTrailingSlashPattern(addTrailingSlash) {
if (addTrailingSlash === "always") {
return "\\/$";
}
if (addTrailingSlash === "never") {
return "$";
}
return "\\/?$";
}
function validateSegment(segment, file = "") {
if (!file)
file = segment;
if (/\]\[/.test(segment)) {
throw new Error(`Invalid route ${file} \u2014 parameters must be separated`);
}
if (countOccurrences("[", segment) !== countOccurrences("]", segment)) {
throw new Error(`Invalid route ${file} \u2014 brackets are unbalanced`);
}
if ((/.+\[\.\.\.[^\]]+\]/.test(segment) || /\[\.\.\.[^\]]+\].+/.test(segment)) && file.endsWith(".astro")) {
throw new Error(`Invalid route ${file} \u2014 rest parameter must be a standalone segment`);
}
}
function isSemanticallyEqualSegment(segmentA, segmentB) {
if (segmentA.length !== segmentB.length) {
return false;
}
for (const [index, partA] of segmentA.entries()) {
const partB = segmentB[index];
if (partA.dynamic !== partB.dynamic || partA.spread !== partB.spread) {
return false;
}
if (!partA.dynamic && partA.content !== partB.content) {
return false;
}
}
return true;
}
function routeComparator(a, b) {
const commonLength = Math.min(a.segments.length, b.segments.length);
for (let index = 0; index < commonLength; index++) {
const aSegment = a.segments[index];
const bSegment = b.segments[index];
const aIsStatic = aSegment.every((part) => !part.dynamic && !part.spread);
const bIsStatic = bSegment.every((part) => !part.dynamic && !part.spread);
if (aIsStatic && bIsStatic) {
const aContent = aSegment.map((part) => part.content).join("");
const bContent = bSegment.map((part) => part.content).join("");
if (aContent !== bContent) {
return aContent.localeCompare(bContent);
}
}
if (aIsStatic !== bIsStatic) {
return aIsStatic ? -1 : 1;
}
const aHasSpread = aSegment.some((part) => part.spread);
const bHasSpread = bSegment.some((part) => part.spread);
if (aHasSpread !== bHasSpread) {
return aHasSpread ? 1 : -1;
}
}
const aLength = a.segments.length;
const bLength = b.segments.length;
if (aLength !== bLength) {
const aEndsInRest = a.segments.at(-1)?.some((part) => part.spread);
const bEndsInRest = b.segments.at(-1)?.some((part) => part.spread);
if (aEndsInRest !== bEndsInRest && Math.abs(aLength - bLength) === 1) {
if (aLength > bLength && aEndsInRest) {
return 1;
}
if (bLength > aLength && bEndsInRest) {
return -1;
}
}
return aLength > bLength ? -1 : 1;
}
if (a.type === "endpoint" !== (b.type === "endpoint")) {
return a.type === "endpoint" ? -1 : 1;
}
return a.route.localeCompare(b.route);
}
function createFileBasedRoutes({ settings, cwd, fsMod }, logger) {
const components = [];
const routes = [];
const validPageExtensions = /* @__PURE__ */ new Set([
".astro",
...SUPPORTED_MARKDOWN_FILE_EXTENSIONS,
...settings.pageExtensions
]);
const validEndpointExtensions = /* @__PURE__ */ new Set([".js", ".ts"]);
const localFs = fsMod ?? nodeFs;
const prerender = getPrerenderDefault(settings.config);
function walk(fs, dir, parentSegments, parentParams) {
let items = [];
const files = fs.readdirSync(dir);
for (const basename of files) {
const resolved = path.join(dir, basename);
const file = slash(path.relative(cwd || fileURLToPath(settings.config.root), resolved));
const isDir = fs.statSync(resolved).isDirectory();
const ext = path.extname(basename);
const name = ext ? basename.slice(0, -ext.length) : basename;
if (name[0] === "_") {
continue;
}
if (basename[0] === "." && basename !== ".well-known") {
continue;
}
if (!isDir && !validPageExtensions.has(ext) && !validEndpointExtensions.has(ext)) {
logger.warn(
null,
`Unsupported file type ${bold(
resolved
)} found. Prefix filename with an underscore (\`_\`) to ignore.`
);
continue;
}
const segment = isDir ? basename : name;
validateSegment(segment, file);
const parts = getParts(segment, file);
const isIndex = isDir ? false : basename.startsWith("index.");
const routeSuffix = basename.slice(basename.indexOf("."), -ext.length);
const isPage = validPageExtensions.has(ext);
items.push({
basename,
ext,
parts,
file: file.replace(/\\/g, "/"),
isDir,
isIndex,
isPage,
routeSuffix
});
}
for (const item of items) {
const segments = parentSegments.slice();
if (item.isIndex) {
if (item.routeSuffix) {
if (segments.length > 0) {
const lastSegment = segments[segments.length - 1].slice();
const lastPart = lastSegment[lastSegment.length - 1];
if (lastPart.dynamic) {
lastSegment.push({
dynamic: false,
spread: false,
content: item.routeSuffix
});
} else {
lastSegment[lastSegment.length - 1] = {
dynamic: false,
spread: false,
content: `${lastPart.content}${item.routeSuffix}`
};
}
segments[segments.length - 1] = lastSegment;
} else {
segments.push(item.parts);
}
}
} else {
segments.push(item.parts);
}
const params = parentParams.slice();
params.push(...item.parts.filter((p) => p.dynamic).map((p) => p.content));
if (item.isDir) {
walk(fsMod ?? fs, path.join(dir, item.basename), segments, params);
} else {
components.push(item.file);
const component = item.file;
const { trailingSlash } = settings.config;
const pattern = getPattern(segments, settings.config, trailingSlash);
const generate = getRouteGenerator(segments, trailingSlash);
const pathname = segments.every((segment) => segment.length === 1 && !segment[0].dynamic) ? `/${segments.map((segment) => segment[0].content).join("/")}` : null;
const route = `/${segments.map(([{ dynamic, content }]) => dynamic ? `[${content}]` : content).join("/")}`.toLowerCase();
routes.push({
route,
isIndex: item.isIndex,
type: item.isPage ? "page" : "endpoint",
pattern,
segments,
params,
component,
generate,
pathname: pathname || void 0,
prerender,
fallbackRoutes: []
});
}
}
}
const { config } = settings;
const pages = resolvePages(config);
if (localFs.existsSync(pages)) {
walk(localFs, fileURLToPath(pages), [], []);
} else if (settings.injectedRoutes.length === 0) {
const pagesDirRootRelative = pages.href.slice(settings.config.root.href.length);
logger.warn(null, `Missing pages directory: ${pagesDirRootRelative}`);
}
return routes;
}
function createInjectedRoutes({ settings, cwd }) {
const { config } = settings;
const prerender = getPrerenderDefault(config);
const routes = {
normal: [],
legacy: []
};
const priority = computeRoutePriority(config);
for (const injectedRoute of settings.injectedRoutes) {
const { pattern: name, entrypoint, prerender: prerenderInjected } = injectedRoute;
let resolved;
try {
resolved = require2.resolve(entrypoint, { paths: [cwd || fileURLToPath(config.root)] });
} catch (e) {
resolved = fileURLToPath(new URL(entrypoint, config.root));
}
const component = slash(path.relative(cwd || fileURLToPath(config.root), resolved));
const segments = removeLeadingForwardSlash(name).split(path.posix.sep).filter(Boolean).map((s) => {
validateSegment(s);
return getParts(s, component);
});
const type = resolved.endsWith(".astro") ? "page" : "endpoint";
const isPage = type === "page";
const trailingSlash = isPage ? config.trailingSlash : "never";
const pattern = getPattern(segments, settings.config, trailingSlash);
const generate = getRouteGenerator(segments, trailingSlash);
const pathname = segments.every((segment) => segment.length === 1 && !segment[0].dynamic) ? `/${segments.map((segment) => segment[0].content).join("/")}` : null;
const params = segments.flat().filter((p) => p.dynamic).map((p) => p.content);
const route = `/${segments.map(([{ dynamic, content }]) => dynamic ? `[${content}]` : content).join("/")}`.toLowerCase();
routes[priority].push({
type,
// For backwards compatibility, an injected route is never considered an index route.
isIndex: false,
route,
pattern,
segments,
params,
component,
generate,
pathname: pathname || void 0,
prerender: prerenderInjected ?? prerender,
fallbackRoutes: []
});
}
return routes;
}
function createRedirectRoutes({ settings }, routeMap, logger) {
const { config } = settings;
const trailingSlash = config.trailingSlash;
const routes = {
normal: [],
legacy: []
};
const priority = computeRoutePriority(settings.config);
for (const [from, to] of Object.entries(settings.config.redirects)) {
const segments = removeLeadingForwardSlash(from).split(path.posix.sep).filter(Boolean).map((s) => {
validateSegment(s);
return getParts(s, from);
});
const pattern = getPattern(segments, settings.config, trailingSlash);
const generate = getRouteGenerator(segments, trailingSlash);
const pathname = segments.every((segment) => segment.length === 1 && !segment[0].dynamic) ? `/${segments.map((segment) => segment[0].content).join("/")}` : null;
const params = segments.flat().filter((p) => p.dynamic).map((p) => p.content);
const route = `/${segments.map(([{ dynamic, content }]) => dynamic ? `[${content}]` : content).join("/")}`.toLowerCase();
let destination;
if (typeof to === "string") {
destination = to;
} else {
destination = to.destination;
}
if (/^https?:\/\//.test(destination)) {
logger.warn(
"redirects",
`Redirecting to an external URL is not officially supported: ${from} -> ${destination}`
);
}
routes[priority].push({
type: "redirect",
// For backwards compatibility, a redirect is never considered an index route.
isIndex: false,
route,
pattern,
segments,
params,
component: from,
generate,
pathname: pathname || void 0,
prerender: false,
redirect: to,
redirectRoute: routeMap.get(destination),
fallbackRoutes: []
});
}
return routes;
}
function isStaticSegment(segment) {
return segment.every((part) => !part.dynamic && !part.spread);
}
function detectRouteCollision(a, b, config, logger) {
if (a.type === "fallback" || b.type === "fallback") {
return;
}
if (a.route === b.route && a.segments.every(isStaticSegment) && b.segments.every(isStaticSegment)) {
logger.warn(
"router",
`The route "${a.route}" is defined in both "${a.component}" and "${b.component}". A static route cannot be defined more than once.`
);
logger.warn(
"router",
"A collision will result in an hard error in following versions of Astro."
);
return;
}
if (a.prerender || b.prerender) {
return;
}
if (a.segments.length !== b.segments.length) {
return;
}
const segmentCount = a.segments.length;
for (let index = 0; index < segmentCount; index++) {
const segmentA = a.segments[index];
const segmentB = b.segments[index];
if (!isSemanticallyEqualSegment(segmentA, segmentB)) {
return;
}
}
logger.warn(
"router",
`The route "${a.route}" is defined in both "${a.component}" and "${b.component}" using SSR mode. A dynamic SSR route cannot be defined more than once.`
);
logger.warn("router", "A collision will result in an hard error in following versions of Astro.");
}
function createRouteManifest(params, logger) {
const { settings } = params;
const { config } = settings;
const routeMap = /* @__PURE__ */ new Map();
const fileBasedRoutes = createFileBasedRoutes(params, logger);
for (const route of fileBasedRoutes) {
routeMap.set(route.route, route);
}
const injectedRoutes = createInjectedRoutes(params);
for (const [, routes2] of Object.entries(injectedRoutes)) {
for (const route of routes2) {
routeMap.set(route.route, route);
}
}
const redirectRoutes = createRedirectRoutes(params, routeMap, logger);
const routes = [
...injectedRoutes["legacy"].sort(routeComparator),
...[...fileBasedRoutes, ...injectedRoutes["normal"], ...redirectRoutes["normal"]].sort(
routeComparator
),
...redirectRoutes["legacy"].sort(routeComparator)
];
if (config.experimental.globalRoutePriority) {
for (const [index, higherRoute] of routes.entries()) {
for (const lowerRoute of routes.slice(index + 1)) {
detectRouteCollision(higherRoute, lowerRoute, config, logger);
}
}
}
const i18n = settings.config.i18n;
if (i18n) {
if (i18n.routing === "pathname-prefix-always") {
let index = routes.find((route) => route.route === "/");
if (!index) {
let relativePath = path.relative(
fileURLToPath(settings.config.root),
fileURLToPath(new URL("pages", settings.config.srcDir))
);
throw new AstroError({
...MissingIndexForInternationalization,
message: MissingIndexForInternationalization.message(i18n.defaultLocale),
hint: MissingIndexForInternationalization.hint(relativePath)
});
}
}
const routesByLocale = /* @__PURE__ */ new Map();
const setRoutes = new Set(routes.filter((route) => route.type === "page"));
const filteredLocales = i18n.locales.filter((loc) => {
if (typeof loc === "string") {
return loc !== i18n.defaultLocale;
}
return loc.path !== i18n.defaultLocale;
}).map((locale) => {
if (typeof locale === "string") {
return locale;
}
return locale.path;
});
for (const locale of filteredLocales) {
for (const route of setRoutes) {
if (!route.route.includes(`/${locale}`)) {
continue;
}
const currentRoutes = routesByLocale.get(locale);
if (currentRoutes) {
currentRoutes.push(route);
routesByLocale.set(locale, currentRoutes);
} else {
routesByLocale.set(locale, [route]);
}
setRoutes.delete(route);
}
}
for (const route of setRoutes) {
const currentRoutes = routesByLocale.get(i18n.defaultLocale);
if (currentRoutes) {
currentRoutes.push(route);
routesByLocale.set(i18n.defaultLocale, currentRoutes);
} else {
routesByLocale.set(i18n.defaultLocale, [route]);
}
setRoutes.delete(route);
}
if (i18n.routing === "pathname-prefix-always") {
const defaultLocaleRoutes = routesByLocale.get(i18n.defaultLocale);
if (defaultLocaleRoutes) {
const indexDefaultRoute = defaultLocaleRoutes.find(({ route }) => route === "/") ?? defaultLocaleRoutes.find(({ route }) => route === `/${i18n.defaultLocale}`);
if (indexDefaultRoute) {
const pathname = "/";
const route = "/";
const segments = removeLeadingForwardSlash(route).split(path.posix.sep).filter(Boolean).map((s) => {
validateSegment(s);
return getParts(s, route);
});
routes.push({
...indexDefaultRoute,
pathname,
route,
segments,
pattern: getPattern(segments, config, config.trailingSlash),
type: "fallback"
});
}
}
}
if (i18n.fallback) {
let fallback = Object.entries(i18n.fallback);
if (fallback.length > 0) {
for (const [fallbackFromLocale, fallbackToLocale] of fallback) {
let fallbackToRoutes;
if (fallbackToLocale === i18n.defaultLocale) {
fallbackToRoutes = routesByLocale.get(i18n.defaultLocale);
} else {
fallbackToRoutes = routesByLocale.get(fallbackToLocale);
}
const fallbackFromRoutes = routesByLocale.get(fallbackFromLocale);
if (!fallbackToRoutes) {
continue;
}
for (const fallbackToRoute of fallbackToRoutes) {
const hasRoute = fallbackFromRoutes && // we check if the fallback from locale (the origin) has already this route
fallbackFromRoutes.some((route) => {
if (fallbackToLocale === i18n.defaultLocale) {
return route.route.replace(`/${fallbackFromLocale}`, "") === fallbackToRoute.route;
} else {
return route.route.replace(`/${fallbackToLocale}`, `/${fallbackFromLocale}`) === fallbackToRoute.route;
}
});
if (!hasRoute) {
let pathname;
let route;
if (fallbackToLocale === i18n.defaultLocale && i18n.routing === "pathname-prefix-other-locales") {
if (fallbackToRoute.pathname) {
pathname = `/${fallbackFromLocale}${fallbackToRoute.pathname}`;
}
route = `/${fallbackFromLocale}${fallbackToRoute.route}`;
} else {
pathname = fallbackToRoute.pathname?.replace(`/${fallbackToLocale}/`, `/${fallbackFromLocale}/`).replace(`/${fallbackToLocale}`, `/${fallbackFromLocale}`);
route = fallbackToRoute.route.replace(`/${fallbackToLocale}`, `/${fallbackFromLocale}`).replace(`/${fallbackToLocale}/`, `/${fallbackFromLocale}/`);
}
const segments = removeLeadingForwardSlash(route).split(path.posix.sep).filter(Boolean).map((s) => {
validateSegment(s);
return getParts(s, route);
});
const generate = getRouteGenerator(segments, config.trailingSlash);
const index = routes.findIndex((r) => r === fallbackToRoute);
if (index >= 0) {
const fallbackRoute = {
...fallbackToRoute,
pathname,
route,
segments,
generate,
pattern: getPattern(segments, config, config.trailingSlash),
type: "fallback",
fallbackRoutes: []
};
const routeData = routes[index];
routeData.fallbackRoutes.push(fallbackRoute);
}
}
}
}
}
}
}
return {
routes
};
}
function computeRoutePriority(config) {
if (config.experimental.globalRoutePriority) {
return "normal";
}
return "legacy";
}
export {
createRouteManifest
};

View File

@ -0,0 +1,323 @@
/*
@license
Rollup.js v4.12.0
Fri, 16 Feb 2024 13:31:42 GMT - commit 0146b84be33a8416b4df4b9382549a7ca19dd64a
https://github.com/rollup/rollup
Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const node_path = require('node:path');
const process = require('node:process');
const rollup = require('./rollup.js');
const node_os = require('node:os');
const index = require('./index.js');
require('./parseAst.js');
require('../native.js');
require('tty');
require('path');
require('node:perf_hooks');
require('node:fs/promises');
require('fs');
require('util');
require('stream');
require('os');
require('./fsevents-importer.js');
require('events');
class FileWatcher {
constructor(task, chokidarOptions) {
this.transformWatchers = new Map();
this.chokidarOptions = chokidarOptions;
this.task = task;
this.watcher = this.createWatcher(null);
}
close() {
this.watcher.close();
for (const watcher of this.transformWatchers.values()) {
watcher.close();
}
}
unwatch(id) {
this.watcher.unwatch(id);
const transformWatcher = this.transformWatchers.get(id);
if (transformWatcher) {
this.transformWatchers.delete(id);
transformWatcher.close();
}
}
watch(id, isTransformDependency) {
if (isTransformDependency) {
const watcher = this.transformWatchers.get(id) ?? this.createWatcher(id);
watcher.add(id);
this.transformWatchers.set(id, watcher);
}
else {
this.watcher.add(id);
}
}
createWatcher(transformWatcherId) {
const task = this.task;
const isLinux = node_os.platform() === 'linux';
const isTransformDependency = transformWatcherId !== null;
const handleChange = (id, event) => {
const changedId = transformWatcherId || id;
if (isLinux) {
// unwatching and watching fixes an issue with chokidar where on certain systems,
// a file that was unlinked and immediately recreated would create a change event
// but then no longer any further events
watcher.unwatch(changedId);
watcher.add(changedId);
}
task.invalidate(changedId, { event, isTransformDependency });
};
const watcher = index.chokidar
.watch([], this.chokidarOptions)
.on('add', id => handleChange(id, 'create'))
.on('change', id => handleChange(id, 'update'))
.on('unlink', id => handleChange(id, 'delete'));
return watcher;
}
}
const eventsRewrites = {
create: {
create: 'buggy',
delete: null, //delete file from map
update: 'create'
},
delete: {
create: 'update',
delete: 'buggy',
update: 'buggy'
},
update: {
create: 'buggy',
delete: 'delete',
update: 'update'
}
};
class Watcher {
constructor(optionsList, emitter) {
this.buildDelay = 0;
this.buildTimeout = null;
this.closed = false;
this.invalidatedIds = new Map();
this.rerun = false;
this.running = true;
this.emitter = emitter;
emitter.close = this.close.bind(this);
this.tasks = optionsList.map(options => new Task(this, options));
for (const { watch } of optionsList) {
if (watch && typeof watch.buildDelay === 'number') {
this.buildDelay = Math.max(this.buildDelay, watch.buildDelay);
}
}
process.nextTick(() => this.run());
}
async close() {
if (this.closed)
return;
this.closed = true;
if (this.buildTimeout)
clearTimeout(this.buildTimeout);
for (const task of this.tasks) {
task.close();
}
await this.emitter.emit('close');
this.emitter.removeAllListeners();
}
invalidate(file) {
if (file) {
const previousEvent = this.invalidatedIds.get(file.id);
const event = previousEvent ? eventsRewrites[previousEvent][file.event] : file.event;
if (event === 'buggy') {
//TODO: throws or warn? Currently just ignore, uses new event
this.invalidatedIds.set(file.id, file.event);
}
else if (event === null) {
this.invalidatedIds.delete(file.id);
}
else {
this.invalidatedIds.set(file.id, event);
}
}
if (this.running) {
this.rerun = true;
return;
}
if (this.buildTimeout)
clearTimeout(this.buildTimeout);
this.buildTimeout = setTimeout(async () => {
this.buildTimeout = null;
try {
await Promise.all([...this.invalidatedIds].map(([id, event]) => this.emitter.emit('change', id, { event })));
this.invalidatedIds.clear();
await this.emitter.emit('restart');
this.emitter.removeListenersForCurrentRun();
this.run();
}
catch (error) {
this.invalidatedIds.clear();
await this.emitter.emit('event', {
code: 'ERROR',
error,
result: null
});
await this.emitter.emit('event', {
code: 'END'
});
}
}, this.buildDelay);
}
async run() {
this.running = true;
await this.emitter.emit('event', {
code: 'START'
});
for (const task of this.tasks) {
await task.run();
}
this.running = false;
await this.emitter.emit('event', {
code: 'END'
});
if (this.rerun) {
this.rerun = false;
this.invalidate();
}
}
}
class Task {
constructor(watcher, options) {
this.cache = { modules: [] };
this.watchFiles = [];
this.closed = false;
this.invalidated = true;
this.watched = new Set();
this.watcher = watcher;
this.options = options;
this.skipWrite = Boolean(options.watch && options.watch.skipWrite);
this.outputs = this.options.output;
this.outputFiles = this.outputs.map(output => {
if (output.file || output.dir)
return node_path.resolve(output.file || output.dir);
return undefined;
});
const watchOptions = this.options.watch || {};
this.filter = rollup.createFilter(watchOptions.include, watchOptions.exclude);
this.fileWatcher = new FileWatcher(this, {
...watchOptions.chokidar,
disableGlobbing: true,
ignoreInitial: true
});
}
close() {
this.closed = true;
this.fileWatcher.close();
}
invalidate(id, details) {
this.invalidated = true;
if (details.isTransformDependency) {
for (const module of this.cache.modules) {
if (!module.transformDependencies.includes(id))
continue;
// effective invalidation
module.originalCode = null;
}
}
this.watcher.invalidate({ event: details.event, id });
}
async run() {
if (!this.invalidated)
return;
this.invalidated = false;
const options = {
...this.options,
cache: this.cache
};
const start = Date.now();
await this.watcher.emitter.emit('event', {
code: 'BUNDLE_START',
input: this.options.input,
output: this.outputFiles
});
let result = null;
try {
result = await rollup.rollupInternal(options, this.watcher.emitter);
if (this.closed) {
return;
}
this.updateWatchedFiles(result);
if (!this.skipWrite) {
await Promise.all(this.outputs.map(output => result.write(output)));
if (this.closed) {
return;
}
this.updateWatchedFiles(result);
}
await this.watcher.emitter.emit('event', {
code: 'BUNDLE_END',
duration: Date.now() - start,
input: this.options.input,
output: this.outputFiles,
result
});
}
catch (error) {
if (!this.closed) {
if (Array.isArray(error.watchFiles)) {
for (const id of error.watchFiles) {
this.watchFile(id);
}
}
if (error.id) {
this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
}
}
await this.watcher.emitter.emit('event', {
code: 'ERROR',
error,
result
});
}
}
updateWatchedFiles(result) {
const previouslyWatched = this.watched;
this.watched = new Set();
this.watchFiles = result.watchFiles;
this.cache = result.cache;
for (const id of this.watchFiles) {
this.watchFile(id);
}
for (const module of this.cache.modules) {
for (const depId of module.transformDependencies) {
this.watchFile(depId, true);
}
}
for (const id of previouslyWatched) {
if (!this.watched.has(id)) {
this.fileWatcher.unwatch(id);
}
}
}
watchFile(id, isTransformDependency = false) {
if (!this.filter(id))
return;
this.watched.add(id);
if (this.outputFiles.includes(id)) {
throw new Error('Cannot import the generated bundle');
}
// this is necessary to ensure that any 'renamed' files
// continue to be watched following an error
this.fileWatcher.watch(id, isTransformDependency);
}
}
exports.Task = Task;
exports.Watcher = Watcher;
//# sourceMappingURL=watch.js.map

View File

@ -0,0 +1,25 @@
import { readUInt32BE, findBox } from "./utils.js";
const JP2 = {
validate(input) {
if (readUInt32BE(input, 4) !== 1783636e3 || readUInt32BE(input, 0) < 1)
return false;
const ftypBox = findBox(input, "ftyp", 0);
if (!ftypBox)
return false;
return readUInt32BE(input, ftypBox.offset + 4) === 1718909296;
},
calculate(input) {
const jp2hBox = findBox(input, "jp2h", 0);
const ihdrBox = jp2hBox && findBox(input, "ihdr", jp2hBox.offset + 8);
if (ihdrBox) {
return {
height: readUInt32BE(input, ihdrBox.offset + 8),
width: readUInt32BE(input, ihdrBox.offset + 12)
};
}
throw new TypeError("Unsupported JPEG 2000 format");
}
};
export {
JP2
};

View File

@ -0,0 +1,245 @@
{
"name": "rollup",
"version": "4.12.0",
"description": "Next-generation ES module bundler",
"main": "dist/rollup.js",
"module": "dist/es/rollup.js",
"types": "dist/rollup.d.ts",
"bin": {
"rollup": "dist/bin/rollup"
},
"napi": {
"name": "rollup",
"package": {
"name": "@rollup/rollup"
},
"triples": {
"defaults": false,
"additional": [
"aarch64-apple-darwin",
"aarch64-linux-android",
"aarch64-pc-windows-msvc",
"aarch64-unknown-linux-gnu",
"aarch64-unknown-linux-musl",
"armv7-linux-androideabi",
"armv7-unknown-linux-gnueabihf",
"i686-pc-windows-msvc",
"riscv64gc-unknown-linux-gnu",
"x86_64-apple-darwin",
"x86_64-pc-windows-msvc",
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl"
]
}
},
"scripts": {
"build": "concurrently -c green,blue \"npm run build:wasm\" \"npm:build:ast-converters\" && concurrently -c green,blue \"npm run build:napi -- --release\" \"npm:build:js\" && npm run build:copy-native",
"build:quick": "concurrently -c green,blue 'npm:build:napi' 'npm:build:cjs' && npm run build:copy-native",
"build:napi": "napi build --platform --dts native.d.ts --js false --cargo-cwd rust -p bindings_napi --cargo-name bindings_napi",
"build:wasm": "wasm-pack build rust/bindings_wasm --out-dir ../../wasm --target web --no-pack && shx rm wasm/.gitignore",
"build:wasm:node": "wasm-pack build rust/bindings_wasm --out-dir ../../wasm-node --target nodejs --no-pack && shx rm wasm-node/.gitignore",
"update:napi": "npm run build:napi && npm run build:copy-native",
"build:js": "rollup --config rollup.config.ts --configPlugin typescript --forceExit",
"build:js:node": "rollup --config rollup.config.ts --configPlugin typescript --configIsBuildNode --forceExit",
"build:prepare": "concurrently -c green,blue \"npm run build:napi -- --release\" \"npm:build:js:node\" && npm run build:copy-native",
"update:js": "npm run build:js && npm run build:copy-native",
"build:copy-native": "shx mkdir -p dist && shx cp rollup.*.node dist/",
"dev": "vitepress dev docs",
"build:cjs": "rollup --config rollup.config.ts --configPlugin typescript --configTest --forceExit",
"build:bootstrap": "shx mv dist dist-build && node dist-build/bin/rollup --config rollup.config.ts --configPlugin typescript --forceExit && shx rm -rf dist-build",
"build:docs": "vitepress build docs",
"build:ast-converters": "node scripts/generate-ast-converters.js",
"preview:docs": "vitepress preview docs",
"ci:artifacts": "napi artifacts",
"ci:lint": "concurrently -c red,yellow,green,blue 'npm:lint:js:nofix' 'npm:lint:native-js' 'npm:lint:markdown:nofix' 'npm:lint:rust:nofix'",
"ci:test:only": "npm run build:cjs && npm run build:copy-native && npm run build:bootstrap && npm run build:copy-native && npm run test:only",
"ci:test:all": "npm run build:cjs && npm run build:copy-native && npm run build:bootstrap && npm run build:copy-native && concurrently --kill-others-on-fail -c green,blue,magenta,cyan 'npm:test:only' 'npm:test:typescript' 'npm:test:leak' 'npm:test:browser'",
"ci:coverage": "npm run build:cjs && npm run build:copy-native && npm run build:bootstrap && npm run build:copy-native && nyc --reporter lcovonly mocha",
"lint": "concurrently -c red,yellow,green,blue 'npm:lint:js' 'npm:lint:native-js' 'npm:lint:markdown' 'npm:lint:rust'",
"lint:js": "eslint . --fix --cache",
"lint:js:nofix": "eslint . --cache",
"lint:native-js": "node scripts/lint-native-js.js",
"lint:markdown": "prettier --write \"**/*.md\"",
"lint:markdown:nofix": "prettier --check \"**/*.md\"",
"lint:rust": "cd rust && cargo fmt && cargo clippy --fix --allow-dirty",
"lint:rust:nofix": "cd rust && cargo fmt --check && cargo clippy",
"perf": "npm run build && node --expose-gc scripts/perf.js",
"prepare": "husky && node scripts/check-release.js || npm run build:prepare",
"prepublishOnly": "node scripts/check-release.js && node scripts/prepublish.js",
"postpublish": "node scripts/postpublish.js",
"prepublish:napi": "napi prepublish --skip-gh-release",
"release": "node scripts/prepare-release.js",
"release:docs": "git fetch --update-head-ok origin master:master && git branch --force documentation-published master && git push origin documentation-published",
"test": "npm run build && npm run test:all",
"test:update-snapshots": "node scripts/update-snapshots.js",
"test:cjs": "npm run build:cjs && npm run test:only",
"test:quick": "mocha -b test/test.js",
"test:all": "concurrently --kill-others-on-fail -c green,blue,magenta,cyan,red 'npm:test:only' 'npm:test:browser' 'npm:test:typescript' 'npm:test:package' 'npm:test:options'",
"test:coverage": "npm run build:cjs && shx rm -rf coverage/* && nyc --reporter html mocha test/test.js",
"test:coverage:browser": "npm run build && shx rm -rf coverage/* && nyc mocha test/browser/index.js",
"test:leak": "node --expose-gc test/leak/index.js",
"test:package": "node scripts/test-package.js",
"test:options": "node scripts/test-options.js",
"test:only": "mocha test/test.js",
"test:typescript": "shx rm -rf test/typescript/dist && shx cp -r dist test/typescript/ && tsc --noEmit -p test/typescript && tsc --noEmit && tsc --noEmit -p scripts",
"test:browser": "mocha test/browser/index.js",
"watch": "rollup --config rollup.config.ts --configPlugin typescript --watch"
},
"repository": "rollup/rollup",
"keywords": [
"modules",
"bundler",
"bundling",
"es6",
"optimizer"
],
"author": "Rich Harris",
"license": "MIT",
"bugs": {
"url": "https://github.com/rollup/rollup/issues"
},
"homepage": "https://rollupjs.org/",
"optionalDependencies": {
"fsevents": "~2.3.2",
"@rollup/rollup-darwin-arm64": "4.12.0",
"@rollup/rollup-android-arm64": "4.12.0",
"@rollup/rollup-win32-arm64-msvc": "4.12.0",
"@rollup/rollup-linux-arm64-gnu": "4.12.0",
"@rollup/rollup-linux-arm64-musl": "4.12.0",
"@rollup/rollup-android-arm-eabi": "4.12.0",
"@rollup/rollup-linux-arm-gnueabihf": "4.12.0",
"@rollup/rollup-win32-ia32-msvc": "4.12.0",
"@rollup/rollup-linux-riscv64-gnu": "4.12.0",
"@rollup/rollup-darwin-x64": "4.12.0",
"@rollup/rollup-win32-x64-msvc": "4.12.0",
"@rollup/rollup-linux-x64-gnu": "4.12.0",
"@rollup/rollup-linux-x64-musl": "4.12.0"
},
"dependencies": {
"@types/estree": "1.0.5"
},
"devDependenciesComments": {
"@types/node": "Version 18.19.0 breaks chokidar and vite types",
"vitepress": "Version 1.0.0-rc.40 breaks npm run dev",
"core-js": "We only update manually as every update requires a snapshot update"
},
"devDependencies": {
"@codemirror/commands": "^6.3.3",
"@codemirror/lang-javascript": "^6.2.1",
"@codemirror/language": "^6.10.1",
"@codemirror/search": "^6.5.6",
"@codemirror/state": "^6.4.0",
"@codemirror/view": "^6.24.0",
"@jridgewell/sourcemap-codec": "^1.4.15",
"@mermaid-js/mermaid-cli": "^10.8.0",
"@napi-rs/cli": "^2.18.0",
"@rollup/plugin-alias": "^5.1.0",
"@rollup/plugin-buble": "^1.0.3",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-replace": "^5.0.5",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"@rollup/pluginutils": "^5.1.0",
"@types/eslint": "^8.56.2",
"@types/inquirer": "^9.0.7",
"@types/mocha": "^10.0.6",
"@types/node": "~18.18.14",
"@types/yargs-parser": "^21.0.3",
"@typescript-eslint/eslint-plugin": "^7.0.1",
"@typescript-eslint/parser": "^7.0.1",
"@vue/eslint-config-prettier": "^9.0.0",
"@vue/eslint-config-typescript": "^12.0.0",
"acorn": "^8.11.3",
"acorn-import-assertions": "^1.9.0",
"buble": "^0.20.0",
"builtin-modules": "^3.3.0",
"chokidar": "^3.6.0",
"colorette": "^2.0.20",
"concurrently": "^8.2.2",
"core-js": "3.36.0",
"date-time": "^4.0.0",
"es5-shim": "^4.6.7",
"es6-shim": "^0.35.8",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-unicorn": "^51.0.1",
"eslint-plugin-vue": "^9.21.1",
"fixturify": "^3.0.0",
"flru": "^1.0.2",
"fs-extra": "^11.2.0",
"github-api": "^3.4.0",
"husky": "^9.0.10",
"inquirer": "^9.2.14",
"is-reference": "^3.0.2",
"lint-staged": "^15.2.2",
"locate-character": "^3.0.0",
"magic-string": "^0.30.7",
"mocha": "^10.3.0",
"nyc": "^15.1.0",
"pinia": "^2.1.7",
"prettier": "^3.2.5",
"pretty-bytes": "^6.1.1",
"pretty-ms": "^9.0.0",
"requirejs": "^2.3.6",
"rollup": "^4.10.0",
"rollup-plugin-license": "^3.2.0",
"rollup-plugin-string": "^3.0.0",
"semver": "^7.6.0",
"shx": "^0.3.4",
"signal-exit": "^4.1.0",
"source-map": "^0.7.4",
"source-map-support": "^0.5.21",
"systemjs": "^6.14.3",
"terser": "^5.27.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vite": "^5.1.1",
"vitepress": "1.0.0-rc.39",
"vue": "^3.4.18",
"wasm-pack": "^0.12.1",
"weak-napi": "^2.0.2",
"yargs-parser": "^21.1.1"
},
"overrides": {
"axios": "^1.6.7",
"semver": "^7.6.0"
},
"files": [
"dist/*.node",
"dist/**/*.js",
"dist/*.d.ts",
"dist/bin/rollup",
"dist/es/package.json"
],
"engines": {
"node": ">=18.0.0",
"npm": ">=8.0.0"
},
"exports": {
".": {
"types": "./dist/rollup.d.ts",
"require": "./dist/rollup.js",
"import": "./dist/es/rollup.js"
},
"./loadConfigFile": {
"types": "./dist/loadConfigFile.d.ts",
"require": "./dist/loadConfigFile.js",
"default": "./dist/loadConfigFile.js"
},
"./getLogFilter": {
"types": "./dist/getLogFilter.d.ts",
"require": "./dist/getLogFilter.js",
"import": "./dist/es/getLogFilter.js"
},
"./parseAst": {
"types": "./dist/parseAst.d.ts",
"require": "./dist/parseAst.js",
"import": "./dist/es/parseAst.js"
},
"./dist/*": "./dist/*"
}
}

View File

@ -0,0 +1,38 @@
import { ModuleCacheMap } from 'vite-node/client';
import { p as provideWorkerState } from './global.CkGT_TMy.js';
import { g as getDefaultRequestStubs, s as startVitestExecutor } from './execute.aFSzc0Da.js';
let _viteNode;
const moduleCache = new ModuleCacheMap();
const mockMap = /* @__PURE__ */ new Map();
async function startViteNode(options) {
if (_viteNode)
return _viteNode;
_viteNode = await startVitestExecutor(options);
return _viteNode;
}
async function runBaseTests(state) {
const { ctx } = state;
state.moduleCache = moduleCache;
state.mockMap = mockMap;
provideWorkerState(globalThis, state);
if (ctx.invalidates) {
ctx.invalidates.forEach((fsPath) => {
moduleCache.delete(fsPath);
moduleCache.delete(`mock:${fsPath}`);
});
}
ctx.files.forEach((i) => state.moduleCache.delete(i));
const [executor, { run }] = await Promise.all([
startViteNode({ state, requestStubs: getDefaultRequestStubs() }),
import('../chunks/runtime-runBaseTests.0UwIvo_U.js')
]);
await run(
ctx.files,
ctx.config,
{ environment: state.environment, options: ctx.environment.options },
executor
);
}
export { runBaseTests as r };

View File

@ -0,0 +1,589 @@
import vm from 'node:vm';
import { pathToFileURL } from 'node:url';
import { ViteNodeRunner, DEFAULT_REQUEST_STUBS } from 'vite-node/client';
import { isNodeBuiltin, isInternalRequest, toFilePath, isPrimitive } from 'vite-node/utils';
import { resolve, isAbsolute, dirname, join, basename, extname, normalize, relative } from 'pathe';
import { processError } from '@vitest/utils/error';
import { distDir } from '../path.js';
import { existsSync, readdirSync } from 'node:fs';
import { highlight, getType } from '@vitest/utils';
import { g as getAllMockableProperties } from './base.knFzp7G3.js';
const spyModulePath = resolve(distDir, "spy.js");
class RefTracker {
idMap = /* @__PURE__ */ new Map();
mockedValueMap = /* @__PURE__ */ new Map();
getId(value) {
return this.idMap.get(value);
}
getMockedValue(id) {
return this.mockedValueMap.get(id);
}
track(originalValue, mockedValue) {
const newId = this.idMap.size;
this.idMap.set(originalValue, newId);
this.mockedValueMap.set(newId, mockedValue);
return newId;
}
}
function isSpecialProp(prop, parentType) {
return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop);
}
class VitestMocker {
constructor(executor) {
this.executor = executor;
const context = this.executor.options.context;
if (context)
this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
else
this.primitives = { Object, Error, Function, RegExp, Symbol: globalThis.Symbol, Array, Map };
const Symbol2 = this.primitives.Symbol;
this.filterPublicKeys = ["__esModule", Symbol2.asyncIterator, Symbol2.hasInstance, Symbol2.isConcatSpreadable, Symbol2.iterator, Symbol2.match, Symbol2.matchAll, Symbol2.replace, Symbol2.search, Symbol2.split, Symbol2.species, Symbol2.toPrimitive, Symbol2.toStringTag, Symbol2.unscopables];
}
static pendingIds = [];
spyModule;
resolveCache = /* @__PURE__ */ new Map();
primitives;
filterPublicKeys;
mockContext = {
callstack: null
};
get root() {
return this.executor.options.root;
}
get mockMap() {
return this.executor.options.mockMap;
}
get moduleCache() {
return this.executor.moduleCache;
}
get moduleDirectories() {
return this.executor.options.moduleDirectories || [];
}
async initializeSpyModule() {
this.spyModule = await this.executor.executeId(spyModulePath);
}
deleteCachedItem(id) {
const mockId = this.getMockPath(id);
if (this.moduleCache.has(mockId))
this.moduleCache.delete(mockId);
}
isAModuleDirectory(path) {
return this.moduleDirectories.some((dir) => path.includes(dir));
}
getSuiteFilepath() {
return this.executor.state.filepath || "global";
}
createError(message, codeFrame) {
const Error2 = this.primitives.Error;
const error = new Error2(message);
Object.assign(error, { codeFrame });
return error;
}
getMocks() {
const suite = this.getSuiteFilepath();
const suiteMocks = this.mockMap.get(suite);
const globalMocks = this.mockMap.get("global");
return {
...globalMocks,
...suiteMocks
};
}
async resolvePath(rawId, importer) {
let id;
let fsPath;
try {
[id, fsPath] = await this.executor.originalResolveUrl(rawId, importer);
} catch (error) {
if (error.code === "ERR_MODULE_NOT_FOUND") {
const { id: unresolvedId } = error[Symbol.for("vitest.error.not_found.data")];
id = unresolvedId;
fsPath = unresolvedId;
} else {
throw error;
}
}
const external = !isAbsolute(fsPath) || this.isAModuleDirectory(fsPath) ? rawId : null;
return {
id,
fsPath,
external
};
}
async resolveMocks() {
if (!VitestMocker.pendingIds.length)
return;
await Promise.all(VitestMocker.pendingIds.map(async (mock) => {
const { fsPath, external } = await this.resolvePath(mock.id, mock.importer);
if (mock.type === "unmock")
this.unmockPath(fsPath);
if (mock.type === "mock")
this.mockPath(mock.id, fsPath, external, mock.factory);
}));
VitestMocker.pendingIds = [];
}
async callFunctionMock(dep, mock) {
var _a, _b;
const cached = (_a = this.moduleCache.get(dep)) == null ? void 0 : _a.exports;
if (cached)
return cached;
let exports;
try {
exports = await mock();
} catch (err) {
const vitestError = this.createError(
'[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock'
);
vitestError.cause = err;
throw vitestError;
}
const filepath = dep.slice(5);
const mockpath = ((_b = this.resolveCache.get(this.getSuiteFilepath())) == null ? void 0 : _b[filepath]) || filepath;
if (exports === null || typeof exports !== "object")
throw this.createError(`[vitest] vi.mock("${mockpath}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
const moduleExports = new Proxy(exports, {
get: (target, prop) => {
const val = target[prop];
if (prop === "then") {
if (target instanceof Promise)
return target.then.bind(target);
} else if (!(prop in target)) {
if (this.filterPublicKeys.includes(prop))
return void 0;
throw this.createError(
`[vitest] No "${String(prop)}" export is defined on the "${mockpath}" mock. Did you forget to return it from "vi.mock"?
If you need to partially mock a module, you can use "importOriginal" helper inside:
`,
highlight(`vi.mock("${mockpath}", async (importOriginal) => {
const actual = await importOriginal()
return {
...actual,
// your mocked methods
}
})`)
);
}
return val;
}
});
this.moduleCache.set(dep, { exports: moduleExports });
return moduleExports;
}
getMockContext() {
return this.mockContext;
}
getMockPath(dep) {
return `mock:${dep}`;
}
getDependencyMock(id) {
return this.getMocks()[id];
}
normalizePath(path) {
return this.moduleCache.normalizePath(path);
}
resolveMockPath(mockPath, external) {
const path = external || mockPath;
if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
const mockDirname = dirname(path);
const mockFolder = join(this.root, "__mocks__", mockDirname);
if (!existsSync(mockFolder))
return null;
const files = readdirSync(mockFolder);
const baseOriginal = basename(path);
for (const file of files) {
const baseFile = basename(file, extname(file));
if (baseFile === baseOriginal)
return resolve(mockFolder, file);
}
return null;
}
const dir = dirname(path);
const baseId = basename(path);
const fullPath = resolve(dir, "__mocks__", baseId);
return existsSync(fullPath) ? fullPath : null;
}
mockObject(object, mockExports = {}) {
const finalizers = new Array();
const refs = new RefTracker();
const define = (container, key, value) => {
try {
container[key] = value;
return true;
} catch {
return false;
}
};
const mockPropertiesOf = (container, newContainer) => {
const containerType = getType(container);
const isModule = containerType === "Module" || !!container.__esModule;
for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, this.primitives)) {
if (!isModule && descriptor.get) {
try {
Object.defineProperty(newContainer, property, descriptor);
} catch (error) {
}
continue;
}
if (isSpecialProp(property, containerType))
continue;
const value = container[property];
const refId = refs.getId(value);
if (refId !== void 0) {
finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
continue;
}
const type = getType(value);
if (Array.isArray(value)) {
define(newContainer, property, []);
continue;
}
const isFunction = type.includes("Function") && typeof value === "function";
if ((!isFunction || value.__isMockFunction) && type !== "Object" && type !== "Module") {
define(newContainer, property, value);
continue;
}
if (!define(newContainer, property, isFunction ? value : {}))
continue;
if (isFunction) {
let mockFunction2 = function() {
if (this instanceof newContainer[property]) {
for (const { key, descriptor: descriptor2 } of getAllMockableProperties(this, false, primitives)) {
if (descriptor2.get)
continue;
const value2 = this[key];
const type2 = getType(value2);
const isFunction2 = type2.includes("Function") && typeof value2 === "function";
if (isFunction2) {
const original = this[key];
const mock2 = spyModule.spyOn(this, key).mockImplementation(original);
mock2.mockRestore = () => {
mock2.mockReset();
mock2.mockImplementation(original);
return mock2;
};
}
}
}
};
if (!this.spyModule)
throw this.createError("[vitest] `spyModule` is not defined. This is Vitest error. Please open a new issue with reproduction.");
const spyModule = this.spyModule;
const primitives = this.primitives;
const mock = spyModule.spyOn(newContainer, property).mockImplementation(mockFunction2);
mock.mockRestore = () => {
mock.mockReset();
mock.mockImplementation(mockFunction2);
return mock;
};
Object.defineProperty(newContainer[property], "length", { value: 0 });
}
refs.track(value, newContainer[property]);
mockPropertiesOf(value, newContainer[property]);
}
};
const mockedObject = mockExports;
mockPropertiesOf(object, mockedObject);
for (const finalizer of finalizers)
finalizer();
return mockedObject;
}
unmockPath(path) {
const suitefile = this.getSuiteFilepath();
const id = this.normalizePath(path);
const mock = this.mockMap.get(suitefile);
if (mock && id in mock)
delete mock[id];
this.deleteCachedItem(id);
}
mockPath(originalId, path, external, factory) {
const id = this.normalizePath(path);
const suitefile = this.getSuiteFilepath();
const mocks = this.mockMap.get(suitefile) || {};
const resolves = this.resolveCache.get(suitefile) || {};
mocks[id] = factory || this.resolveMockPath(path, external);
resolves[id] = originalId;
this.mockMap.set(suitefile, mocks);
this.resolveCache.set(suitefile, resolves);
this.deleteCachedItem(id);
}
async importActual(rawId, importer, callstack) {
const { id, fsPath } = await this.resolvePath(rawId, importer);
const result = await this.executor.cachedRequest(id, fsPath, callstack || [importer]);
return result;
}
async importMock(rawId, importee) {
const { id, fsPath, external } = await this.resolvePath(rawId, importee);
const normalizedId = this.normalizePath(fsPath);
let mock = this.getDependencyMock(normalizedId);
if (mock === void 0)
mock = this.resolveMockPath(fsPath, external);
if (mock === null) {
const mod = await this.executor.cachedRequest(id, fsPath, [importee]);
return this.mockObject(mod);
}
if (typeof mock === "function")
return this.callFunctionMock(fsPath, mock);
return this.executor.dependencyRequest(mock, mock, [importee]);
}
async requestWithMock(url, callstack) {
const id = this.normalizePath(url);
const mock = this.getDependencyMock(id);
const mockPath = this.getMockPath(id);
if (mock === null) {
const cache = this.moduleCache.get(mockPath);
if (cache.exports)
return cache.exports;
const exports = {};
this.moduleCache.set(mockPath, { exports });
const mod = await this.executor.directRequest(url, url, callstack);
this.mockObject(mod, exports);
return exports;
}
if (typeof mock === "function" && !callstack.includes(mockPath) && !callstack.includes(url)) {
try {
callstack.push(mockPath);
this.mockContext.callstack = callstack;
return await this.callFunctionMock(mockPath, mock);
} finally {
this.mockContext.callstack = null;
const indexMock = callstack.indexOf(mockPath);
callstack.splice(indexMock, 1);
}
}
if (typeof mock === "string" && !callstack.includes(mock))
return mock;
}
queueMock(id, importer, factory, throwIfCached = false) {
VitestMocker.pendingIds.push({ type: "mock", id, importer, factory, throwIfCached });
}
queueUnmock(id, importer, throwIfCached = false) {
VitestMocker.pendingIds.push({ type: "unmock", id, importer, throwIfCached });
}
}
async function createVitestExecutor(options) {
const runner = new VitestExecutor(options);
await runner.executeId("/@vite/env");
await runner.mocker.initializeSpyModule();
return runner;
}
const externalizeMap = /* @__PURE__ */ new Map();
const bareVitestRegexp = /^@?vitest(\/|$)/;
const dispose = [];
function listenForErrors(state) {
dispose.forEach((fn) => fn());
dispose.length = 0;
function catchError(err, type) {
var _a;
const worker = state();
const error = processError(err);
if (!isPrimitive(error)) {
error.VITEST_TEST_NAME = (_a = worker.current) == null ? void 0 : _a.name;
if (worker.filepath)
error.VITEST_TEST_PATH = relative(state().config.root, worker.filepath);
error.VITEST_AFTER_ENV_TEARDOWN = worker.environmentTeardownRun;
}
state().rpc.onUnhandledError(error, type);
}
const uncaughtException = (e) => catchError(e, "Uncaught Exception");
const unhandledRejection = (e) => catchError(e, "Unhandled Rejection");
process.on("uncaughtException", uncaughtException);
process.on("unhandledRejection", unhandledRejection);
dispose.push(() => {
process.off("uncaughtException", uncaughtException);
process.off("unhandledRejection", unhandledRejection);
});
}
async function startVitestExecutor(options) {
const state = () => globalThis.__vitest_worker__ || options.state;
const rpc = () => state().rpc;
process.exit = (code = process.exitCode || 0) => {
throw new Error(`process.exit unexpectedly called with "${code}"`);
};
listenForErrors(state);
const getTransformMode = () => {
return state().environment.transformMode ?? "ssr";
};
return await createVitestExecutor({
async fetchModule(id) {
if (externalizeMap.has(id))
return { externalize: externalizeMap.get(id) };
if (id.includes(distDir)) {
const { path } = toFilePath(id, state().config.root);
const externalize = pathToFileURL(path).toString();
externalizeMap.set(id, externalize);
return { externalize };
}
if (bareVitestRegexp.test(id)) {
externalizeMap.set(id, id);
return { externalize: id };
}
return rpc().fetch(id, getTransformMode());
},
resolveId(id, importer) {
return rpc().resolveId(id, importer, getTransformMode());
},
get moduleCache() {
return state().moduleCache;
},
get mockMap() {
return state().mockMap;
},
get interopDefault() {
return state().config.deps.interopDefault;
},
get moduleDirectories() {
return state().config.deps.moduleDirectories;
},
get root() {
return state().config.root;
},
get base() {
return state().config.base;
},
...options
});
}
function updateStyle(id, css) {
if (typeof document === "undefined")
return;
const element = document.querySelector(`[data-vite-dev-id="${id}"]`);
if (element) {
element.textContent = css;
return;
}
const head = document.querySelector("head");
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.setAttribute("data-vite-dev-id", id);
style.textContent = css;
head == null ? void 0 : head.appendChild(style);
}
function removeStyle(id) {
if (typeof document === "undefined")
return;
const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
if (sheet)
document.head.removeChild(sheet);
}
function getDefaultRequestStubs(context) {
if (!context) {
const clientStub2 = { ...DEFAULT_REQUEST_STUBS["@vite/client"], updateStyle, removeStyle };
return {
"/@vite/client": clientStub2,
"@vite/client": clientStub2
};
}
const clientStub = vm.runInContext(
`(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`,
context
)(DEFAULT_REQUEST_STUBS["@vite/client"]);
return {
"/@vite/client": clientStub,
"@vite/client": clientStub
};
}
class VitestExecutor extends ViteNodeRunner {
constructor(options) {
super({
...options,
// interop is done inside the external executor instead
interopDefault: options.context ? false : options.interopDefault
});
this.options = options;
this.mocker = new VitestMocker(this);
if (!options.context) {
Object.defineProperty(globalThis, "__vitest_mocker__", {
value: this.mocker,
writable: true,
configurable: true
});
this.primitives = { Object, Reflect, Symbol };
} else if (options.externalModulesExecutor) {
this.primitives = vm.runInContext("({ Object, Reflect, Symbol })", options.context);
this.externalModules = options.externalModulesExecutor;
} else {
throw new Error("When context is provided, externalModulesExecutor must be provided as well.");
}
}
mocker;
externalModules;
primitives;
getContextPrimitives() {
return this.primitives;
}
get state() {
return globalThis.__vitest_worker__ || this.options.state;
}
shouldResolveId(id, _importee) {
var _a;
if (isInternalRequest(id) || id.startsWith("data:"))
return false;
const transformMode = ((_a = this.state.environment) == null ? void 0 : _a.transformMode) ?? "ssr";
return transformMode === "ssr" ? !isNodeBuiltin(id) : !id.startsWith("node:");
}
async originalResolveUrl(id, importer) {
return super.resolveUrl(id, importer);
}
async resolveUrl(id, importer) {
if (VitestMocker.pendingIds.length)
await this.mocker.resolveMocks();
if (importer && importer.startsWith("mock:"))
importer = importer.slice(5);
try {
return await super.resolveUrl(id, importer);
} catch (error) {
if (error.code === "ERR_MODULE_NOT_FOUND") {
const { id: id2 } = error[Symbol.for("vitest.error.not_found.data")];
const path = this.mocker.normalizePath(id2);
const mock = this.mocker.getDependencyMock(path);
if (mock !== void 0)
return [id2, id2];
}
throw error;
}
}
async runModule(context, transformed) {
const vmContext = this.options.context;
if (!vmContext || !this.externalModules)
return super.runModule(context, transformed);
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
const code = `${codeDefinition}${transformed}
}}`;
const options = {
filename: context.__filename,
lineOffset: 0,
columnOffset: -codeDefinition.length
};
const fn = vm.runInContext(code, vmContext, {
...options,
// if we encountered an import, it's not inlined
importModuleDynamically: this.externalModules.importModuleDynamically
});
await fn(...Object.values(context));
}
async importExternalModule(path) {
if (this.externalModules)
return this.externalModules.import(path);
return super.importExternalModule(path);
}
async dependencyRequest(id, fsPath, callstack) {
const mocked = await this.mocker.requestWithMock(fsPath, callstack);
if (typeof mocked === "string")
return super.dependencyRequest(mocked, mocked, callstack);
if (mocked && typeof mocked === "object")
return mocked;
return super.dependencyRequest(id, fsPath, callstack);
}
prepareContext(context) {
if (this.state.filepath && normalize(this.state.filepath) === normalize(context.__filename)) {
const globalNamespace = this.options.context || globalThis;
Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", { get: () => globalNamespace.__vitest_index__ });
}
if (this.options.context && this.externalModules)
context.require = this.externalModules.createRequire(context.__filename);
return context;
}
}
export { VitestExecutor as V, getDefaultRequestStubs as g, startVitestExecutor as s };

View File

@ -0,0 +1,2 @@
import type { IImage } from './interface.ts';
export declare const DDS: IImage;

View File

@ -0,0 +1,252 @@
import { EventEmitter } from 'node:events';
import c from 'picocolors';
import createDebug from 'debug';
import { normalizeRequestId } from './utils.mjs';
function createHmrEmitter() {
const emitter = new EventEmitter();
return emitter;
}
function viteNodeHmrPlugin() {
const emitter = createHmrEmitter();
return {
name: "vite-node:hmr",
config() {
if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
return {
server: {
watch: {
useFsEvents: false,
usePolling: false
}
}
};
}
},
configureServer(server) {
const _send = server.ws.send;
server.emitter = emitter;
server.ws.send = function(payload) {
_send(payload);
emitter.emit("message", payload);
};
if (process.env.VITE_TEST_WATCHER_DEBUG) {
server.watcher.on("ready", () => {
console.log("[debug] watcher is ready");
});
}
}
};
}
const debugHmr = createDebug("vite-node:hmr");
const cache = /* @__PURE__ */ new WeakMap();
function getCache(runner) {
if (!cache.has(runner)) {
cache.set(runner, {
hotModulesMap: /* @__PURE__ */ new Map(),
dataMap: /* @__PURE__ */ new Map(),
disposeMap: /* @__PURE__ */ new Map(),
pruneMap: /* @__PURE__ */ new Map(),
customListenersMap: /* @__PURE__ */ new Map(),
ctxToListenersMap: /* @__PURE__ */ new Map(),
messageBuffer: [],
isFirstUpdate: false,
pending: false,
queued: []
});
}
return cache.get(runner);
}
function sendMessageBuffer(runner, emitter) {
const maps = getCache(runner);
maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
maps.messageBuffer.length = 0;
}
async function reload(runner, files) {
Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
if (!fsPath.includes("node_modules"))
runner.moduleCache.delete(fsPath);
});
return Promise.all(files.map((file) => runner.executeId(file)));
}
async function notifyListeners(runner, event, data) {
const maps = getCache(runner);
const cbs = maps.customListenersMap.get(event);
if (cbs)
await Promise.all(cbs.map((cb) => cb(data)));
}
async function queueUpdate(runner, p) {
const maps = getCache(runner);
maps.queued.push(p);
if (!maps.pending) {
maps.pending = true;
await Promise.resolve();
maps.pending = false;
const loading = [...maps.queued];
maps.queued = [];
(await Promise.all(loading)).forEach((fn) => fn && fn());
}
}
async function fetchUpdate(runner, { path, acceptedPath }) {
path = normalizeRequestId(path);
acceptedPath = normalizeRequestId(acceptedPath);
const maps = getCache(runner);
const mod = maps.hotModulesMap.get(path);
if (!mod) {
return;
}
const isSelfUpdate = path === acceptedPath;
let fetchedModule;
const qualifiedCallbacks = mod.callbacks.filter(
({ deps }) => deps.includes(acceptedPath)
);
if (isSelfUpdate || qualifiedCallbacks.length > 0) {
const disposer = maps.disposeMap.get(acceptedPath);
if (disposer)
await disposer(maps.dataMap.get(acceptedPath));
try {
[fetchedModule] = await reload(runner, [acceptedPath]);
} catch (e) {
warnFailedFetch(e, acceptedPath);
}
}
return () => {
for (const { deps, fn } of qualifiedCallbacks)
fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
};
}
function warnFailedFetch(err, path) {
if (!err.message.match("fetch"))
console.error(err);
console.error(
`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}
async function handleMessage(runner, emitter, files, payload) {
const maps = getCache(runner);
switch (payload.type) {
case "connected":
sendMessageBuffer(runner, emitter);
break;
case "update":
await notifyListeners(runner, "vite:beforeUpdate", payload);
await Promise.all(payload.updates.map((update) => {
if (update.type === "js-update")
return queueUpdate(runner, fetchUpdate(runner, update));
console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
return null;
}));
await notifyListeners(runner, "vite:afterUpdate", payload);
break;
case "full-reload":
await notifyListeners(runner, "vite:beforeFullReload", payload);
maps.customListenersMap.delete("vite:beforeFullReload");
await reload(runner, files);
break;
case "custom":
await notifyListeners(runner, payload.event, payload.data);
break;
case "prune":
await notifyListeners(runner, "vite:beforePrune", payload);
payload.paths.forEach((path) => {
const fn = maps.pruneMap.get(path);
if (fn)
fn(maps.dataMap.get(path));
});
break;
case "error": {
await notifyListeners(runner, "vite:error", payload);
const err = payload.err;
console.error(`${c.cyan("[vite-node]")} Internal Server Error
${err.message}
${err.stack}`);
break;
}
}
}
function createHotContext(runner, emitter, files, ownerPath) {
debugHmr("createHotContext", ownerPath);
const maps = getCache(runner);
if (!maps.dataMap.has(ownerPath))
maps.dataMap.set(ownerPath, {});
const mod = maps.hotModulesMap.get(ownerPath);
if (mod)
mod.callbacks = [];
const newListeners = /* @__PURE__ */ new Map();
maps.ctxToListenersMap.set(ownerPath, newListeners);
function acceptDeps(deps, callback = () => {
}) {
const mod2 = maps.hotModulesMap.get(ownerPath) || {
id: ownerPath,
callbacks: []
};
mod2.callbacks.push({
deps,
fn: callback
});
maps.hotModulesMap.set(ownerPath, mod2);
}
const hot = {
get data() {
return maps.dataMap.get(ownerPath);
},
acceptExports(_, callback) {
acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
},
accept(deps, callback) {
if (typeof deps === "function" || !deps) {
acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
} else if (typeof deps === "string") {
acceptDeps([deps], ([mod2]) => callback && callback(mod2));
} else if (Array.isArray(deps)) {
acceptDeps(deps, callback);
} else {
throw new TypeError("invalid hot.accept() usage.");
}
},
dispose(cb) {
maps.disposeMap.set(ownerPath, cb);
},
prune(cb) {
maps.pruneMap.set(ownerPath, cb);
},
invalidate() {
notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
return reload(runner, files);
},
on(event, cb) {
const addToMap = (map) => {
const existing = map.get(event) || [];
existing.push(cb);
map.set(event, existing);
};
addToMap(maps.customListenersMap);
addToMap(newListeners);
},
off(event, cb) {
const removeFromMap = (map) => {
const existing = map.get(event);
if (existing === void 0)
return;
const pruned = existing.filter((l) => l !== cb);
if (pruned.length === 0) {
map.delete(event);
return;
}
map.set(event, pruned);
};
removeFromMap(maps.customListenersMap);
removeFromMap(newListeners);
},
send(event, data) {
maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
sendMessageBuffer(runner, emitter);
}
};
return hot;
}
export { createHotContext as a, createHmrEmitter as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v };

View File

@ -0,0 +1 @@
{"files":{"package.json":{"checkedAt":1708389320421,"integrity":"sha512-AXhyoGz4yBanWX3ATGMtM+D3q9mA0UiIH+SVDxoIha8ewtljoSCIUfGzSBqVXjN9jH4emWgRl2wBvwl3dWX6pg==","mode":420,"size":417},"README.md":{"checkedAt":1708389320422,"integrity":"sha512-JfylgMnN67sEVrDeTJWU9LPg41B+KsNLLvXH2JHHaqBNw6qpjnfNng//L52tyyS6mexyHlfUW7zF2U1HdfL0gw==","mode":420,"size":95},"rollup.linux-x64-gnu.node":{"checkedAt":1708389320432,"integrity":"sha512-VUFe0A4u0712hqnAO9i2u/W+Q/TGjxREWX2/7vnmMaI7N+KkA4LU/Nb+LJ4EfzjPWwC+WMKg0PYMKY8F+GhipQ==","mode":420,"size":2731200}}}

View File

@ -0,0 +1,75 @@
import { isatty } from 'node:tty';
import { createRequire } from 'node:module';
import util from 'node:util';
import timers from 'node:timers';
import { performance } from 'node:perf_hooks';
import { startTests } from '@vitest/runner';
import { setupColors, createColors } from '@vitest/utils';
import { installSourcemapsSupport } from 'vite-node/source-map';
import { V as VitestSnapshotEnvironment, s as setupChaiConfig, r as resolveTestRunner } from '../vendor/index.CKbXK54q.js';
import { a as startCoverageInsideWorker, s as stopCoverageInsideWorker } from '../vendor/coverage.E7sG1b3r.js';
import { g as getWorkerState } from '../vendor/global.CkGT_TMy.js';
import { V as VitestIndex } from '../vendor/index.n-Ib4UWN.js';
import { s as setupCommonEnv } from '../vendor/setup-common.NSpEdAQm.js';
import 'chai';
import '@vitest/snapshot/environment';
import 'pathe';
import '../path.js';
import 'node:url';
import '../vendor/rpc.joBhAkyK.js';
import '../vendor/index.8bPxjt7g.js';
import '../vendor/benchmark.eeqk2rd8.js';
import '@vitest/runner/utils';
import '../vendor/index.ir9i0ywP.js';
import 'std-env';
import '../vendor/run-once.Olz_Zkd8.js';
import '../vendor/vi.-Nr_x6dl.js';
import '../vendor/_commonjsHelpers.jjO7Zipk.js';
import '@vitest/expect';
import '@vitest/snapshot';
import '@vitest/utils/error';
import '../vendor/tasks.IknbGB2n.js';
import '@vitest/utils/source-map';
import '../vendor/base.knFzp7G3.js';
import '../vendor/date.Ns1pGd_X.js';
import '@vitest/spy';
async function run(files, config, executor) {
const workerState = getWorkerState();
await setupCommonEnv(config);
Object.defineProperty(globalThis, "__vitest_index__", {
value: VitestIndex,
enumerable: false
});
config.snapshotOptions.snapshotEnvironment = new VitestSnapshotEnvironment(workerState.rpc);
setupColors(createColors(isatty(1)));
if (workerState.environment.transformMode === "web") {
const _require = createRequire(import.meta.url);
_require.extensions[".css"] = () => ({});
_require.extensions[".scss"] = () => ({});
_require.extensions[".sass"] = () => ({});
_require.extensions[".less"] = () => ({});
}
globalThis.__vitest_required__ = {
util,
timers
};
installSourcemapsSupport({
getSourceMap: (source) => workerState.moduleCache.getSourceMap(source)
});
await startCoverageInsideWorker(config.coverage, executor);
if (config.chaiConfig)
setupChaiConfig(config.chaiConfig);
const runner = await resolveTestRunner(config, executor);
workerState.durations.prepare = performance.now() - workerState.durations.prepare;
const { vi } = VitestIndex;
for (const file of files) {
workerState.filepath = file;
await startTests([file], runner);
vi.resetConfig();
vi.restoreAllMocks();
}
await stopCoverageInsideWorker(config.coverage, executor);
}
export { run };

View File

@ -0,0 +1,148 @@
import { diff } from './diff.js';
import { f as format, s as stringify } from './chunk-display.js';
import { deepClone, getOwnProperties, getType } from './helpers.js';
import 'pretty-format';
import 'diff-sequences';
import './chunk-colors.js';
import 'loupe';
const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@";
const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@";
function isImmutable(v) {
return v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]);
}
const OBJECT_PROTO = Object.getPrototypeOf({});
function getUnserializableMessage(err) {
if (err instanceof Error)
return `<unserializable>: ${err.message}`;
if (typeof err === "string")
return `<unserializable>: ${err}`;
return "<unserializable>";
}
function serializeError(val, seen = /* @__PURE__ */ new WeakMap()) {
if (!val || typeof val === "string")
return val;
if (typeof val === "function")
return `Function<${val.name || "anonymous"}>`;
if (typeof val === "symbol")
return val.toString();
if (typeof val !== "object")
return val;
if (isImmutable(val))
return serializeError(val.toJSON(), seen);
if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction")
return "Promise";
if (typeof Element !== "undefined" && val instanceof Element)
return val.tagName;
if (typeof val.asymmetricMatch === "function")
return `${val.toString()} ${format(val.sample)}`;
if (seen.has(val))
return seen.get(val);
if (Array.isArray(val)) {
const clone = new Array(val.length);
seen.set(val, clone);
val.forEach((e, i) => {
try {
clone[i] = serializeError(e, seen);
} catch (err) {
clone[i] = getUnserializableMessage(err);
}
});
return clone;
} else {
const clone = /* @__PURE__ */ Object.create(null);
seen.set(val, clone);
let obj = val;
while (obj && obj !== OBJECT_PROTO) {
Object.getOwnPropertyNames(obj).forEach((key) => {
if (key in clone)
return;
try {
clone[key] = serializeError(val[key], seen);
} catch (err) {
delete clone[key];
clone[key] = getUnserializableMessage(err);
}
});
obj = Object.getPrototypeOf(obj);
}
return clone;
}
}
function normalizeErrorMessage(message) {
return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "");
}
function processError(err, diffOptions) {
if (!err || typeof err !== "object")
return { message: err };
if (err.stack)
err.stackStr = String(err.stack);
if (err.name)
err.nameStr = String(err.name);
if (err.showDiff || err.showDiff === void 0 && err.expected !== void 0 && err.actual !== void 0) {
const clonedActual = deepClone(err.actual, { forceWritable: true });
const clonedExpected = deepClone(err.expected, { forceWritable: true });
const { replacedActual, replacedExpected } = replaceAsymmetricMatcher(clonedActual, clonedExpected);
err.diff = diff(replacedExpected, replacedActual, { ...diffOptions, ...err.diffOptions });
}
if (typeof err.expected !== "string")
err.expected = stringify(err.expected, 10);
if (typeof err.actual !== "string")
err.actual = stringify(err.actual, 10);
try {
if (typeof err.message === "string")
err.message = normalizeErrorMessage(err.message);
if (typeof err.cause === "object" && typeof err.cause.message === "string")
err.cause.message = normalizeErrorMessage(err.cause.message);
} catch {
}
try {
return serializeError(err);
} catch (e) {
return serializeError(new Error(`Failed to fully serialize error: ${e == null ? void 0 : e.message}
Inner error message: ${err == null ? void 0 : err.message}`));
}
}
function isAsymmetricMatcher(data) {
const type = getType(data);
return type === "Object" && typeof data.asymmetricMatch === "function";
}
function isReplaceable(obj1, obj2) {
const obj1Type = getType(obj1);
const obj2Type = getType(obj2);
return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array");
}
function replaceAsymmetricMatcher(actual, expected, actualReplaced = /* @__PURE__ */ new WeakSet(), expectedReplaced = /* @__PURE__ */ new WeakSet()) {
if (!isReplaceable(actual, expected))
return { replacedActual: actual, replacedExpected: expected };
if (actualReplaced.has(actual) || expectedReplaced.has(expected))
return { replacedActual: actual, replacedExpected: expected };
actualReplaced.add(actual);
expectedReplaced.add(expected);
getOwnProperties(expected).forEach((key) => {
const expectedValue = expected[key];
const actualValue = actual[key];
if (isAsymmetricMatcher(expectedValue)) {
if (expectedValue.asymmetricMatch(actualValue))
actual[key] = expectedValue;
} else if (isAsymmetricMatcher(actualValue)) {
if (actualValue.asymmetricMatch(expectedValue))
expected[key] = actualValue;
} else if (isReplaceable(actualValue, expectedValue)) {
const replaced = replaceAsymmetricMatcher(
actualValue,
expectedValue,
actualReplaced,
expectedReplaced
);
actual[key] = replaced.replacedActual;
expected[key] = replaced.replacedExpected;
}
});
return {
replacedActual: actual,
replacedExpected: expected
};
}
export { processError, replaceAsymmetricMatcher, serializeError };

View File

@ -0,0 +1,76 @@
import jsTokens from 'js-tokens';
function stripLiteralJsTokens(code, options) {
const FILL = options?.fillChar ?? " ";
const FILL_COMMENT = " ";
let result = "";
const filter = options?.filter ?? (() => true);
const tokens = [];
for (const token of jsTokens(code, { jsx: false })) {
tokens.push(token);
if (token.type === "SingleLineComment") {
result += FILL_COMMENT.repeat(token.value.length);
continue;
}
if (token.type === "MultiLineComment") {
result += token.value.replace(/[^\n]/g, FILL_COMMENT);
continue;
}
if (token.type === "StringLiteral") {
const body = token.value.slice(1, -1);
if (filter(body)) {
result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
continue;
}
}
if (token.type === "NoSubstitutionTemplate") {
const body = token.value.slice(1, -1);
if (filter(body)) {
result += `\`${body.replace(/[^\n]/g, FILL)}\``;
continue;
}
}
if (token.type === "RegularExpressionLiteral") {
const body = token.value;
if (filter(body)) {
result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
continue;
}
}
if (token.type === "TemplateHead") {
const body = token.value.slice(1, -2);
if (filter(body)) {
result += `\`${body.replace(/[^\n]/g, FILL)}\${`;
continue;
}
}
if (token.type === "TemplateTail") {
const body = token.value.slice(0, -2);
if (filter(body)) {
result += `}${body.replace(/[^\n]/g, FILL)}\``;
continue;
}
}
if (token.type === "TemplateMiddle") {
const body = token.value.slice(1, -2);
if (filter(body)) {
result += `}${body.replace(/[^\n]/g, FILL)}\${`;
continue;
}
}
result += token.value;
}
return {
result,
tokens
};
}
function stripLiteral(code, options) {
return stripLiteralDetailed(code, options).result;
}
function stripLiteralDetailed(code, options) {
return stripLiteralJsTokens(code, options);
}
export { stripLiteral, stripLiteralDetailed, stripLiteralJsTokens };

View File

@ -0,0 +1,14 @@
# js-tokens
The tiny, regex powered, lenient, _almost_ spec-compliant JavaScript tokenizer that never fails.
```js
const jsTokens = require("js-tokens");
const jsString = 'JSON.stringify({k:3.14**2}, null /*replacer*/, "\\t")';
Array.from(jsTokens(jsString), (token) => token.value).join("|");
// JSON|.|stringify|(|{|k|:|3.14|**|2|}|,| |null| |/*replacer*/|,| |"\t"|)
```
**[➡️ Full readme](https://github.com/lydell/js-tokens/)**

View File

@ -0,0 +1 @@
{"files":{"LICENSE":{"checkedAt":1708389320570,"integrity":"sha512-fTH7zgvddH0Uz1hkigVSiaNYj2CbQ0loGMi290iomsK/Od0D0ynnP4zhBam5uULMt5lvZw0U6qXeLWwHJl8/+g==","mode":420,"size":1139},"index.js":{"checkedAt":1708389320570,"integrity":"sha512-2qCw92/NWflY55+9MuZWYDqK0rex59YQlOIow4j52RADU8M126eFw6WUr0NoYwN/ygVucdG9vzJDxhJc95hRNg==","mode":420,"size":12436},"package.json":{"checkedAt":1708389320571,"integrity":"sha512-/r7x7k7FPGP+pf/PqsOjOsWom2mbDmlnkp1S99TB8NPoXAhTv+6V/9dUCU4K6CUcxEBpsdHtbXLqYHkQ7unpDA==","mode":420,"size":391},"README.md":{"checkedAt":1708389320577,"integrity":"sha512-UDyEFwICVWlhfQgu6XP6wiU7oQ6jaJKsMPksVWIEHMX7NFKYVhGYf1vbcXqXn+Q9Q/k2Sd7DPzR3esLWaTKhng==","mode":420,"size":440},"index.d.ts":{"checkedAt":1708389320577,"integrity":"sha512-zLEI1BZ6JfROwy98C+4AZO2D5a90MzAkY07EI9jnk0RmoqDPUPeBwlbaq6Xmp8d1McdPqnuomooDLLckTLh6Ng==","mode":420,"size":1428}}}

View File

@ -0,0 +1,167 @@
{
const propTypes = {
0: (value) => reviveObject(value),
1: (value) => reviveArray(value),
2: (value) => new RegExp(value),
3: (value) => new Date(value),
4: (value) => new Map(reviveArray(value)),
5: (value) => new Set(reviveArray(value)),
6: (value) => BigInt(value),
7: (value) => new URL(value),
8: (value) => new Uint8Array(value),
9: (value) => new Uint16Array(value),
10: (value) => new Uint32Array(value)
};
const reviveTuple = (raw) => {
const [type, value] = raw;
return type in propTypes ? propTypes[type](value) : void 0;
};
const reviveArray = (raw) => raw.map(reviveTuple);
const reviveObject = (raw) => {
if (typeof raw !== "object" || raw === null)
return raw;
return Object.fromEntries(Object.entries(raw).map(([key, value]) => [key, reviveTuple(value)]));
};
if (!customElements.get("astro-island")) {
customElements.define(
"astro-island",
class extends HTMLElement {
Component;
hydrator;
static observedAttributes = ["props"];
disconnectedCallback() {
document.removeEventListener("astro:after-swap", this.unmount);
document.addEventListener("astro:after-swap", this.unmount, { once: true });
}
connectedCallback() {
if (!this.hasAttribute("await-children") || document.readyState === "interactive" || document.readyState === "complete") {
this.childrenConnectedCallback();
} else {
const onConnected = () => {
document.removeEventListener("DOMContentLoaded", onConnected);
mo.disconnect();
this.childrenConnectedCallback();
};
const mo = new MutationObserver(() => {
if (this.lastChild?.nodeType === Node.COMMENT_NODE && this.lastChild.nodeValue === "astro:end") {
this.lastChild.remove();
onConnected();
}
});
mo.observe(this, { childList: true });
document.addEventListener("DOMContentLoaded", onConnected);
}
}
async childrenConnectedCallback() {
let beforeHydrationUrl = this.getAttribute("before-hydration-url");
if (beforeHydrationUrl) {
await import(beforeHydrationUrl);
}
this.start();
}
async start() {
const opts = JSON.parse(this.getAttribute("opts"));
const directive = this.getAttribute("client");
if (Astro[directive] === void 0) {
window.addEventListener(`astro:${directive}`, () => this.start(), { once: true });
return;
}
try {
await Astro[directive](
async () => {
const rendererUrl = this.getAttribute("renderer-url");
const [componentModule, { default: hydrator }] = await Promise.all([
import(this.getAttribute("component-url")),
rendererUrl ? import(rendererUrl) : () => () => {
}
]);
const componentExport = this.getAttribute("component-export") || "default";
if (!componentExport.includes(".")) {
this.Component = componentModule[componentExport];
} else {
this.Component = componentModule;
for (const part of componentExport.split(".")) {
this.Component = this.Component[part];
}
}
this.hydrator = hydrator;
return this.hydrate;
},
opts,
this
);
} catch (e) {
console.error(
`[astro-island] Error hydrating ${this.getAttribute("component-url")}`,
e
);
}
}
hydrate = async () => {
if (!this.hydrator)
return;
if (!this.isConnected)
return;
const parentSsrIsland = this.parentElement?.closest("astro-island[ssr]");
if (parentSsrIsland) {
parentSsrIsland.addEventListener("astro:hydrate", this.hydrate, { once: true });
return;
}
const slotted = this.querySelectorAll("astro-slot");
const slots = {};
const templates = this.querySelectorAll("template[data-astro-template]");
for (const template of templates) {
const closest = template.closest(this.tagName);
if (!closest?.isSameNode(this))
continue;
slots[template.getAttribute("data-astro-template") || "default"] = template.innerHTML;
template.remove();
}
for (const slot of slotted) {
const closest = slot.closest(this.tagName);
if (!closest?.isSameNode(this))
continue;
slots[slot.getAttribute("name") || "default"] = slot.innerHTML;
}
let props;
try {
props = this.hasAttribute("props") ? reviveObject(JSON.parse(this.getAttribute("props"))) : {};
} catch (e) {
let componentName = this.getAttribute("component-url") || "<unknown>";
const componentExport = this.getAttribute("component-export");
if (componentExport) {
componentName += ` (export ${componentExport})`;
}
console.error(
`[hydrate] Error parsing props for component ${componentName}`,
this.getAttribute("props"),
e
);
throw e;
}
let hydrationTimeStart;
const hydrator = this.hydrator(this);
if (process.env.NODE_ENV === "development")
hydrationTimeStart = performance.now();
await hydrator(this.Component, props, slots, {
client: this.getAttribute("client")
});
if (process.env.NODE_ENV === "development" && hydrationTimeStart)
this.setAttribute(
"client-render-time",
(performance.now() - hydrationTimeStart).toString()
);
this.removeAttribute("ssr");
this.dispatchEvent(new CustomEvent("astro:hydrate"));
};
attributeChangedCallback() {
this.hydrate();
}
unmount = () => {
if (!this.isConnected)
this.dispatchEvent(new CustomEvent("astro:unmount"));
};
}
);
}
}

View File

@ -0,0 +1,26 @@
import { relative } from 'pathe';
import 'std-env';
import '@vitest/runner/utils';
import '@vitest/utils';
import { g as getWorkerState } from './global.CkGT_TMy.js';
var _a;
const isNode = typeof process < "u" && typeof process.stdout < "u" && !((_a = process.versions) == null ? void 0 : _a.deno) && !globalThis.window;
const isWindows = isNode && process.platform === "win32";
function getRunMode() {
return getWorkerState().config.mode;
}
function isRunningInBenchmark() {
return getRunMode() === "benchmark";
}
const relativePath = relative;
function removeUndefinedValues(obj) {
for (const key in Object.keys(obj)) {
if (obj[key] === void 0)
delete obj[key];
}
return obj;
}
export { isNode as a, removeUndefinedValues as b, isWindows as c, isRunningInBenchmark as i, relativePath as r };

View File

@ -0,0 +1,126 @@
'use strict';
var path = require('node:path');
var cac = require('cac');
var c = require('picocolors');
var vite = require('vite');
var server = require('./server.cjs');
var client = require('./client.cjs');
var utils = require('./utils.cjs');
var hmr = require('./chunk-hmr.cjs');
var sourceMap = require('./source-map.cjs');
require('node:perf_hooks');
require('node:fs');
require('node:assert');
require('pathe');
require('debug');
require('./constants.cjs');
require('node:module');
require('node:url');
require('node:vm');
require('node:events');
var version = "1.3.0";
const cli = cac("vite-node");
cli.option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-m, --mode <mode>", "Set env mode").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--script", "Use vite-node as a script runner").option("--options <options>", "Use specified Vite server options").option("-v, --version", "Output the version number").option("-h, --help", "Display help for command");
cli.command("[...files]").allowUnknownOptions().action(run);
cli.parse(process.argv, { run: false });
if (cli.args.length === 0) {
cli.runMatchedCommand();
} else {
const i = cli.rawArgs.indexOf(cli.args[0]) + 1;
const scriptArgs = cli.rawArgs.slice(i).filter((it) => it !== "--");
const executeArgs = [...cli.rawArgs.slice(0, i), "--", ...scriptArgs];
cli.parse(executeArgs);
}
async function run(files, options = {}) {
var _a;
if (options.script) {
files = [files[0]];
options = {};
process.argv = [process.argv[0], path.resolve(files[0]), ...process.argv.slice(2).filter((arg) => arg !== "--script" && arg !== files[0])];
} else {
process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
}
if (options.version) {
cli.version(version);
cli.outputVersion();
process.exit(0);
}
if (options.help) {
cli.version(version).outputHelp();
process.exit(0);
}
if (!files.length) {
console.error(c.red("No files specified."));
cli.version(version).outputHelp();
process.exit(1);
}
const serverOptions = options.options ? parseServerOptions(options.options) : {};
const server$1 = await vite.createServer({
logLevel: "error",
configFile: options.config,
root: options.root,
mode: options.mode,
server: {
hmr: !!options.watch
},
plugins: [
options.watch && hmr.viteNodeHmrPlugin()
]
});
await server$1.pluginContainer.buildStart({});
const node = new server.ViteNodeServer(server$1, serverOptions);
sourceMap.installSourcemapsSupport({
getSourceMap: (source) => node.getSourceMap(source)
});
const runner = new client.ViteNodeRunner({
root: server$1.config.root,
base: server$1.config.base,
fetchModule(id) {
return node.fetchModule(id);
},
resolveId(id, importer) {
return node.resolveId(id, importer);
},
createHotContext(runner2, url) {
return hmr.createHotContext(runner2, server$1.emitter, files, url);
}
});
await runner.executeId("/@vite/env");
for (const file of files)
await runner.executeFile(file);
if (!options.watch)
await server$1.close();
(_a = server$1.emitter) == null ? void 0 : _a.on("message", (payload) => {
hmr.handleMessage(runner, server$1.emitter, files, payload);
});
if (options.watch) {
process.on("uncaughtException", (err) => {
console.error(c.red("[vite-node] Failed to execute file: \n"), err);
});
}
}
function parseServerOptions(serverOptions) {
var _a, _b, _c, _d, _e, _f, _g;
const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : utils.toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline);
return {
...serverOptions,
deps: {
...serverOptions.deps,
inline: inlineOptions !== true ? inlineOptions.map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
}) : true,
external: utils.toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
}),
moduleDirectories: ((_d = serverOptions.deps) == null ? void 0 : _d.moduleDirectories) ? utils.toArray((_e = serverOptions.deps) == null ? void 0 : _e.moduleDirectories) : void 0
},
transformMode: {
...serverOptions.transformMode,
ssr: utils.toArray((_f = serverOptions.transformMode) == null ? void 0 : _f.ssr).map((dep) => new RegExp(dep)),
web: utils.toArray((_g = serverOptions.transformMode) == null ? void 0 : _g.web).map((dep) => new RegExp(dep))
}
};
}

View File

@ -0,0 +1,30 @@
import { g as globalApis } from '../vendor/constants.K-Wf1PUy.js';
import { V as VitestIndex } from '../vendor/index.n-Ib4UWN.js';
import '@vitest/runner';
import '../vendor/benchmark.eeqk2rd8.js';
import '@vitest/runner/utils';
import '@vitest/utils';
import '../vendor/index.ir9i0ywP.js';
import 'pathe';
import 'std-env';
import '../vendor/global.CkGT_TMy.js';
import '../vendor/run-once.Olz_Zkd8.js';
import '../vendor/vi.-Nr_x6dl.js';
import 'chai';
import '../vendor/_commonjsHelpers.jjO7Zipk.js';
import '@vitest/expect';
import '@vitest/snapshot';
import '@vitest/utils/error';
import '../vendor/tasks.IknbGB2n.js';
import '@vitest/utils/source-map';
import '../vendor/base.knFzp7G3.js';
import '../vendor/date.Ns1pGd_X.js';
import '@vitest/spy';
function registerApiGlobally() {
globalApis.forEach((api) => {
globalThis[api] = VitestIndex[api];
});
}
export { registerApiGlobally };

View File

@ -0,0 +1,69 @@
/*
@license
Rollup.js v4.12.0
Fri, 16 Feb 2024 13:31:42 GMT - commit 0146b84be33a8416b4df4b9382549a7ca19dd64a
https://github.com/rollup/rollup
Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const getLogFilter = filters => {
if (filters.length === 0)
return () => true;
const normalizedFilters = filters.map(filter => filter.split('&').map(subFilter => {
const inverted = subFilter.startsWith('!');
if (inverted)
subFilter = subFilter.slice(1);
const [key, ...value] = subFilter.split(':');
return { inverted, key: key.split('.'), parts: value.join(':').split('*') };
}));
return (log) => {
nextIntersectedFilter: for (const intersectedFilters of normalizedFilters) {
for (const { inverted, key, parts } of intersectedFilters) {
const isFilterSatisfied = testFilter(log, key, parts);
if (inverted ? isFilterSatisfied : !isFilterSatisfied) {
continue nextIntersectedFilter;
}
}
return true;
}
return false;
};
};
const testFilter = (log, key, parts) => {
let rawValue = log;
for (let index = 0; index < key.length; index++) {
if (!rawValue) {
return false;
}
const part = key[index];
if (!(part in rawValue)) {
return false;
}
rawValue = rawValue[part];
}
let value = typeof rawValue === 'object' ? JSON.stringify(rawValue) : String(rawValue);
if (parts.length === 1) {
return value === parts[0];
}
if (!value.startsWith(parts[0])) {
return false;
}
const lastPartIndex = parts.length - 1;
for (let index = 1; index < lastPartIndex; index++) {
const part = parts[index];
const position = value.indexOf(part);
if (position === -1) {
return false;
}
value = value.slice(position + part.length);
}
return value.endsWith(parts[lastPartIndex]);
};
exports.getLogFilter = getLogFilter;
//# sourceMappingURL=getLogFilter.js.map

View File

@ -0,0 +1,251 @@
import { setState, GLOBAL_EXPECT, getState } from '@vitest/expect';
import { g as getSnapshotClient, c as createExpect, v as vi } from './vendor/vi.-Nr_x6dl.js';
import './vendor/index.ir9i0ywP.js';
import { r as rpc } from './vendor/rpc.joBhAkyK.js';
import { g as getFullName } from './vendor/tasks.IknbGB2n.js';
import { g as getWorkerState } from './vendor/global.CkGT_TMy.js';
import { getTests, getNames } from '@vitest/runner/utils';
import { updateTask } from '@vitest/runner';
import { createDefer, getSafeTimers } from '@vitest/utils';
import { a as getBenchOptions, g as getBenchFn } from './vendor/benchmark.eeqk2rd8.js';
import 'chai';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import '@vitest/snapshot';
import '@vitest/utils/error';
import '@vitest/utils/source-map';
import './vendor/base.knFzp7G3.js';
import './vendor/date.Ns1pGd_X.js';
import '@vitest/spy';
import 'pathe';
import 'std-env';
import './vendor/index.8bPxjt7g.js';
class VitestTestRunner {
constructor(config) {
this.config = config;
}
snapshotClient = getSnapshotClient();
workerState = getWorkerState();
__vitest_executor;
cancelRun = false;
importFile(filepath, source) {
if (source === "setup")
this.workerState.moduleCache.delete(filepath);
return this.__vitest_executor.executeId(filepath);
}
onBeforeRunFiles() {
this.snapshotClient.clear();
}
async onAfterRunSuite(suite) {
if (this.config.logHeapUsage && typeof process !== "undefined")
suite.result.heap = process.memoryUsage().heapUsed;
if (suite.mode !== "skip" && typeof suite.filepath !== "undefined") {
for (const test of getTests(suite)) {
if (test.mode === "skip") {
const name = getNames(test).slice(1).join(" > ");
this.snapshotClient.skipTestSnapshots(name);
}
}
const result = await this.snapshotClient.finishCurrentRun();
if (result)
await rpc().snapshotSaved(result);
}
}
onAfterRunTask(test) {
this.snapshotClient.clearTest();
if (this.config.logHeapUsage && typeof process !== "undefined")
test.result.heap = process.memoryUsage().heapUsed;
this.workerState.current = void 0;
}
onCancel(_reason) {
this.cancelRun = true;
}
async onBeforeRunTask(test) {
if (this.cancelRun)
test.mode = "skip";
if (test.mode !== "run")
return;
clearModuleMocks(this.config);
this.workerState.current = test;
}
async onBeforeRunSuite(suite) {
if (this.cancelRun)
suite.mode = "skip";
if (suite.mode !== "skip" && typeof suite.filepath !== "undefined") {
await this.snapshotClient.startCurrentRun(suite.filepath, "__default_name_", this.workerState.config.snapshotOptions);
}
}
onBeforeTryTask(test) {
var _a, _b;
setState({
assertionCalls: 0,
isExpectingAssertions: false,
isExpectingAssertionsError: null,
expectedAssertionsNumber: null,
expectedAssertionsNumberErrorGen: null,
testPath: (_b = (_a = test.suite) == null ? void 0 : _a.file) == null ? void 0 : _b.filepath,
currentTestName: getFullName(test),
snapshotState: this.snapshotClient.snapshotState
}, globalThis[GLOBAL_EXPECT]);
}
onAfterTryTask(test) {
const {
assertionCalls,
expectedAssertionsNumber,
expectedAssertionsNumberErrorGen,
isExpectingAssertions,
isExpectingAssertionsError
// @ts-expect-error _local is untyped
} = "context" in test && test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber)
throw expectedAssertionsNumberErrorGen();
if (isExpectingAssertions === true && assertionCalls === 0)
throw isExpectingAssertionsError;
}
extendTaskContext(context) {
let _expect;
Object.defineProperty(context, "expect", {
get() {
if (!_expect)
_expect = createExpect(context.task);
return _expect;
}
});
Object.defineProperty(context, "_local", {
get() {
return _expect != null;
}
});
return context;
}
}
function clearModuleMocks(config) {
const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = config;
if (restoreMocks)
vi.restoreAllMocks();
else if (mockReset)
vi.resetAllMocks();
else if (clearMocks)
vi.clearAllMocks();
if (unstubEnvs)
vi.unstubAllEnvs();
if (unstubGlobals)
vi.unstubAllGlobals();
}
function createBenchmarkResult(name) {
return {
name,
rank: 0,
rme: 0,
samples: []
};
}
const benchmarkTasks = /* @__PURE__ */ new WeakMap();
async function runBenchmarkSuite(suite, runner) {
var _a;
const { Task, Bench } = await runner.importTinybench();
const start = performance.now();
const benchmarkGroup = [];
const benchmarkSuiteGroup = [];
for (const task of suite.tasks) {
if (task.mode !== "run")
continue;
if ((_a = task.meta) == null ? void 0 : _a.benchmark)
benchmarkGroup.push(task);
else if (task.type === "suite")
benchmarkSuiteGroup.push(task);
}
if (benchmarkSuiteGroup.length)
await Promise.all(benchmarkSuiteGroup.map((subSuite) => runBenchmarkSuite(subSuite, runner)));
if (benchmarkGroup.length) {
const defer = createDefer();
suite.result = {
state: "run",
startTime: start,
benchmark: createBenchmarkResult(suite.name)
};
updateTask$1(suite);
const addBenchTaskListener = (task, benchmark) => {
task.addEventListener("complete", (e) => {
const task2 = e.task;
const taskRes = task2.result;
const result = benchmark.result.benchmark;
Object.assign(result, taskRes);
updateTask$1(benchmark);
}, {
once: true
});
task.addEventListener("error", (e) => {
const task2 = e.task;
defer.reject(benchmark ? task2.result.error : e);
}, {
once: true
});
};
benchmarkGroup.forEach((benchmark) => {
const options = getBenchOptions(benchmark);
const benchmarkInstance = new Bench(options);
const benchmarkFn = getBenchFn(benchmark);
benchmark.result = {
state: "run",
startTime: start,
benchmark: createBenchmarkResult(benchmark.name)
};
const task = new Task(benchmarkInstance, benchmark.name, benchmarkFn);
benchmarkTasks.set(benchmark, task);
addBenchTaskListener(task, benchmark);
updateTask$1(benchmark);
});
const { setTimeout } = getSafeTimers();
const tasks = [];
for (const benchmark of benchmarkGroup) {
const task = benchmarkTasks.get(benchmark);
await task.warmup();
tasks.push([
await new Promise((resolve) => setTimeout(async () => {
resolve(await task.run());
})),
benchmark
]);
}
suite.result.duration = performance.now() - start;
suite.result.state = "pass";
tasks.sort(([taskA], [taskB]) => taskA.result.mean - taskB.result.mean).forEach(([, benchmark], idx) => {
benchmark.result.state = "pass";
if (benchmark) {
const result = benchmark.result.benchmark;
result.rank = Number(idx) + 1;
updateTask$1(benchmark);
}
});
updateTask$1(suite);
defer.resolve(null);
await defer;
}
function updateTask$1(task) {
updateTask(task, runner);
}
}
class NodeBenchmarkRunner {
constructor(config) {
this.config = config;
}
__vitest_executor;
async importTinybench() {
return await import('tinybench');
}
importFile(filepath, source) {
if (source === "setup")
getWorkerState().moduleCache.delete(filepath);
return this.__vitest_executor.executeId(filepath);
}
async runSuite(suite) {
await runBenchmarkSuite(suite, this);
}
async runTask() {
throw new Error("`test()` and `it()` is only available in test mode.");
}
}
export { NodeBenchmarkRunner, VitestTestRunner };

View File

@ -0,0 +1,25 @@
import { S as Suite, T as Task, a as Test, C as Custom } from './tasks-_kyNRBhz.js';
export { b as ChainableFunction, c as createChainable } from './tasks-_kyNRBhz.js';
import { Arrayable } from '@vitest/utils';
/**
* If any tasks been marked as `only`, mark all other tasks as `skip`.
*/
declare function interpretTaskModes(suite: Suite, namePattern?: string | RegExp, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void;
declare function someTasksAreOnly(suite: Suite): boolean;
declare function generateHash(str: string): string;
declare function calculateSuiteHash(parent: Suite): void;
/**
* Partition in tasks groups by consecutive concurrent
*/
declare function partitionSuiteChildren(suite: Suite): Task[][];
declare function getTests(suite: Arrayable<Task>): (Test | Custom)[];
declare function getTasks(tasks?: Arrayable<Task>): Task[];
declare function getSuites(suite: Arrayable<Task>): Suite[];
declare function hasTests(suite: Arrayable<Suite>): boolean;
declare function hasFailed(suite: Arrayable<Task>): boolean;
declare function getNames(task: Task): string[];
export { calculateSuiteHash, generateHash, getNames, getSuites, getTasks, getTests, hasFailed, hasTests, interpretTaskModes, partitionSuiteChildren, someTasksAreOnly };

View File

@ -0,0 +1,10 @@
import type { imageType } from './types/index.js';
import type { ISizeCalculationResult } from './types/interface.ts';
/**
* Return size information based on an Uint8Array
*
* @param {Uint8Array} input
* @returns {ISizeCalculationResult}
*/
export declare function lookup(input: Uint8Array): ISizeCalculationResult;
export declare const disableTypes: (types: imageType[]) => void;

View File

@ -0,0 +1,660 @@
import {Logger} from '../logger';
import {LegacyImporter} from './importer';
import {LegacyFunction} from './function';
import {NodePackageImporter} from '../importer';
/**
* Options for {@link render} and {@link renderSync} that are shared between
* {@link LegacyFileOptions} and {@link LegacyStringOptions}.
*
* @typeParam sync - This lets the TypeScript checker verify that {@link
* LegacyAsyncImporter}s and {@link LegacyAsyncFunction}s aren't passed to
* {@link renderSync}.
*
* @category Legacy
* @deprecated This only works with the legacy {@link render} and {@link
* renderSync} APIs. Use {@link Options} with {@link compile}, {@link
* compileString}, {@link compileAsync}, and {@link compileStringAsync} instead.
*/
export interface LegacySharedOptions<sync extends 'sync' | 'async'> {
/**
* This array of strings option provides [load
* paths](https://sass-lang.com/documentation/at-rules/import#load-paths) for
* Sass to look for stylesheets. Earlier load paths will take precedence over
* later ones.
*
* ```js
* sass.renderSync({
* file: "style.scss",
* includePaths: ["node_modules/bootstrap/dist/css"]
* });
* ```
*
* Load paths are also loaded from the `SASS_PATH` environment variable, if
* its set. This variable should be a list of paths separated by `;` (on
* Windows) or `:` (on other operating systems). Load paths from the
* `includePaths` option take precedence over load paths from `SASS_PATH`.
*
* ```sh
* $ SASS_PATH=node_modules/bootstrap/dist/css sass style.scss style.css
* ```
*
* @category Input
* @compatibility feature: "SASS_PATH", dart: "1.15.0", node: "3.9.0"
*
* Earlier versions of Dart Sass and Node Sass didnt support the `SASS_PATH`
* environment variable.
*/
includePaths?: string[];
/**
* Whether the generated CSS should use spaces or tabs for indentation.
*
* ```js
* const result = sass.renderSync({
* file: "style.scss",
* indentType: "tab",
* indentWidth: 1
* });
*
* result.css.toString();
* // "h1 {\n\tfont-size: 40px;\n}\n"
* ```
*
* @defaultValue `'space'`
* @category Output
* @compatibility dart: true, node: "3.0.0"
*/
indentType?: 'space' | 'tab';
/**
* How many spaces or tabs (depending on {@link indentType}) should be used
* per indentation level in the generated CSS. It must be between 0 and 10
* (inclusive).
*
* @defaultValue `2`
* @category Output
* @compatibility dart: true, node: "3.0.0"
*/
indentWidth?: number;
/**
* Which character sequence to use at the end of each line in the generated
* CSS. It can have the following values:
*
* * `'lf'` uses U+000A LINE FEED.
* * `'lfcr'` uses U+000A LINE FEED followed by U+000D CARRIAGE RETURN.
* * `'cr'` uses U+000D CARRIAGE RETURN.
* * `'crlf'` uses U+000D CARRIAGE RETURN followed by U+000A LINE FEED.
*
* @defaultValue `'lf'`
* @category Output
* @compatibility dart: true, node: "3.0.0"
*/
linefeed?: 'cr' | 'crlf' | 'lf' | 'lfcr';
/**
* If `true`, Sass won't add a link from the generated CSS to the source map.
*
* ```js
* const result = sass.renderSync({
* file: "style.scss",
* sourceMap: "out.map",
* omitSourceMapUrl: true
* })
* console.log(result.css.toString());
* // h1 {
* // font-size: 40px;
* // }
* ```
*
* @defaultValue `false`
* @category Source Maps
*/
omitSourceMapUrl?: boolean;
/**
* The location that Sass expects the generated CSS to be saved to. Its used
* to determine the URL used to link from the generated CSS to the source map,
* and from the source map to the Sass source files.
*
* **Heads up!** Despite the name, Sass does *not* write the CSS output to
* this file. The caller must do that themselves.
*
* ```js
* result = sass.renderSync({
* file: "style.scss",
* sourceMap: true,
* outFile: "out.css"
* })
* console.log(result.css.toString());
* // h1 {
* // font-size: 40px;
* // }
* // /*# sourceMappingURL=out.css.map * /
* ```
*
* @category Source Maps
*/
outFile?: string;
/**
* The output style of the compiled CSS. There are four possible output styles:
*
* * `"expanded"` (the default for Dart Sass) writes each selector and
* declaration on its own line.
*
* * `"compressed"` removes as many extra characters as possible, and writes
* the entire stylesheet on a single line.
*
* * `"nested"` (the default for Node Sass, not supported by Dart Sass)
* indents CSS rules to match the nesting of the Sass source.
*
* * `"compact"` (not supported by Dart Sass) puts each CSS rule on its own single line.
*
* @example
*
* ```js
* const source = `
* h1 {
* font-size: 40px;
* code {
* font-face: Roboto Mono;
* }
* }`;
*
* let result = sass.renderSync({
* data: source,
* outputStyle: "expanded"
* });
* console.log(result.css.toString());
* // h1 {
* // font-size: 40px;
* // }
* // h1 code {
* // font-face: Roboto Mono;
* // }
*
* result = sass.renderSync({
* data: source,
* outputStyle: "compressed"
* });
* console.log(result.css.toString());
* // h1{font-size:40px}h1 code{font-face:Roboto Mono}
*
* result = sass.renderSync({
* data: source,
* outputStyle: "nested"
* });
* console.log(result.css.toString());
* // h1 {
* // font-size: 40px; }
* // h1 code {
* // font-face: Roboto Mono; }
*
* result = sass.renderSync({
* data: source,
* outputStyle: "compact"
* });
* console.log(result.css.toString());
* // h1 { font-size: 40px; }
* // h1 code { font-face: Roboto Mono; }
* ```
*
* @category Output
*/
outputStyle?: 'compressed' | 'expanded' | 'nested' | 'compact';
/**
* Whether or not Sass should generate a source map. If it does, the source
* map will be available as {@link LegacyResult.map} (unless {@link
* sourceMapEmbed} is `true`).
*
* If this option is a string, its the path that the source map is expected
* to be written to, which is used to link to the source map from the
* generated CSS and to link *from* the source map to the Sass source files.
* Note that if `sourceMap` is a string and {@link outFile} isnt passed, Sass
* assumes that the CSS will be written to the same directory as the file
* option if its passed.
*
* If this option is `true`, the path is assumed to be {@link outFile} with
* `.map` added to the end. If its `true` and {@link outFile} isnt passed,
* it has no effect.
*
* @example
*
* ```js
* let result = sass.renderSync({
* file: "style.scss",
* sourceMap: "out.map"
* })
* console.log(result.css.toString());
* // h1 {
* // font-size: 40px;
* // }
* // /*# sourceMappingURL=out.map * /
*
* result = sass.renderSync({
* file: "style.scss",
* sourceMap: true,
* outFile: "out.css"
* })
* console.log(result.css.toString());
* // h1 {
* // font-size: 40px;
* // }
* // /*# sourceMappingURL=out.css.map * /
* ```
*
* @defaultValue `false`
* @category Source Maps
*/
sourceMap?: boolean | string;
/**
* Whether to embed the entire contents of the Sass files that contributed to
* the generated CSS in the source map. This may produce very large source
* maps, but it guarantees that the source will be available on any computer
* no matter how the CSS is served.
*
* @example
*
* ```js
* sass.renderSync({
* file: "style.scss",
* sourceMap: "out.map",
* sourceMapContents: true
* })
* ```
*
* @defaultValue `false`
* @category Source Maps
*/
sourceMapContents?: boolean;
/**
* Whether to embed the contents of the source map file in the generated CSS,
* rather than creating a separate file and linking to it from the CSS.
*
* @example
*
* ```js
* sass.renderSync({
* file: "style.scss",
* sourceMap: "out.map",
* sourceMapEmbed: true
* });
* ```
*
* @defaultValue `false`
* @category Source Maps
*/
sourceMapEmbed?: boolean;
/**
* If this is passed, it's prepended to all the links from the source map to
* the Sass source files.
*
* @category Source Maps
*/
sourceMapRoot?: string;
/**
* Additional handler(s) for loading files when a [`@use`
* rule](https://sass-lang.com/documentation/at-rules/use) or an [`@import`
* rule](https://sass-lang.com/documentation/at-rules/import) is encountered.
* It can either be a single {@link LegacyImporter} function, or an array of
* {@link LegacyImporter}s.
*
* Importers take the URL of the `@import` or `@use` rule and return a {@link
* LegacyImporterResult} indicating how to handle that rule. For more details,
* see {@link LegacySyncImporter} and {@link LegacyAsyncImporter}.
*
* Loads are resolved by trying, in order:
*
* * Loading a file from disk relative to the file in which the `@use` or
* `@import` appeared.
*
* * Each custom importer.
*
* * Loading a file relative to the current working directory.
*
* * Each load path in {@link includePaths}.
*
* * Each load path specified in the `SASS_PATH` environment variable, which
* should be semicolon-separated on Windows and colon-separated elsewhere.
*
* @example
*
* ```js
* sass.render({
* file: "style.scss",
* importer: [
* // This importer uses the synchronous API, and can be passed to either
* // renderSync() or render().
* function(url, prev) {
* // This generates a stylesheet from scratch for `@use "big-headers"`.
* if (url != "big-headers") return null;
*
* return {
* contents: `
* h1 {
* font-size: 40px;
* }`
* };
* },
*
* // This importer uses the asynchronous API, and can only be passed to
* // render().
* function(url, prev, done) {
* // Convert `@use "foo/bar"` to "node_modules/foo/sass/bar".
* const components = url.split('/');
* const innerPath = components.slice(1).join('/');
* done({
* file: `node_modules/${components.first}/sass/${innerPath}`
* });
* }
* ]
* }, function(err, result) {
* // ...
* });
* ```
*
* @category Plugins
* @compatibility dart: true, node: "3.0.0"
*
* Versions of Node Sass before 3.0.0 dont support arrays of importers, nor
* do they support importers that return `Error` objects.
*
* Versions of Node Sass before 2.0.0 dont support the `importer` option at
* all.
*
* @compatibility feature: "Import order", dart: "1.20.2", node: false
*
* Versions of Dart Sass before 1.20.2 preferred resolving imports using
* {@link includePaths} before resolving them using custom importers.
*
* All versions of Node Sass currently pass imports to importers before
* loading them relative to the file in which the `@import` appears. This
* behavior is considered incorrect and should not be relied on because it
* violates the principle of *locality*, which says that it should be possible
* to reason about a stylesheet without knowing everything about how the
* entire system is set up. If a user tries to import a stylesheet relative to
* another stylesheet, that import should *always* work. It shouldnt be
* possible for some configuration somewhere else to break it.
*/
importer?: LegacyImporter<sync> | LegacyImporter<sync>[];
/**
* Additional built-in Sass functions that are available in all stylesheets.
* This option takes an object whose keys are Sass function signatures and
* whose values are {@link LegacyFunction}s. Each function should take the
* same arguments as its signature.
*
* Functions are passed subclasses of {@link LegacyValue}, and must return the
* same.
*
* **Heads up!** When writing custom functions, its important to ensure that
* all the arguments are the types you expect. Otherwise, users stylesheets
* could crash in hard-to-debug ways or, worse, compile to meaningless CSS.
*
* @example
*
* ```js
* sass.render({
* data: `
* h1 {
* font-size: pow(2, 5) * 1px;
* }`,
* functions: {
* // This function uses the synchronous API, and can be passed to either
* // renderSync() or render().
* 'pow($base, $exponent)': function(base, exponent) {
* if (!(base instanceof sass.types.Number)) {
* throw "$base: Expected a number.";
* } else if (base.getUnit()) {
* throw "$base: Expected a unitless number.";
* }
*
* if (!(exponent instanceof sass.types.Number)) {
* throw "$exponent: Expected a number.";
* } else if (exponent.getUnit()) {
* throw "$exponent: Expected a unitless number.";
* }
*
* return new sass.types.Number(
* Math.pow(base.getValue(), exponent.getValue()));
* },
*
* // This function uses the asynchronous API, and can only be passed to
* // render().
* 'sqrt($number)': function(number, done) {
* if (!(number instanceof sass.types.Number)) {
* throw "$number: Expected a number.";
* } else if (number.getUnit()) {
* throw "$number: Expected a unitless number.";
* }
*
* done(new sass.types.Number(Math.sqrt(number.getValue())));
* }
* }
* }, function(err, result) {
* console.log(result.css.toString());
* // h1 {
* // font-size: 32px;
* // }
* });
* ```
*
* @category Plugins
*/
functions?: {[key: string]: LegacyFunction<sync>};
/**
* By default, if the CSS document contains non-ASCII characters, Sass adds a
* `@charset` declaration (in expanded output mode) or a byte-order mark (in
* compressed mode) to indicate its encoding to browsers or other consumers.
* If `charset` is `false`, these annotations are omitted.
*
* @category Output
* @compatibility dart: "1.39.0", node: false
*/
charset?: boolean;
/**
* If this option is set to `true`, Sass wont print warnings that are caused
* by dependencies. A “dependency” is defined as any file thats loaded
* through {@link includePaths} or {@link importer}. Stylesheets that are
* imported relative to the entrypoint are not considered dependencies.
*
* This is useful for silencing deprecation warnings that you cant fix on
* your own. However, please <em>also</em> notify your dependencies of the deprecations
* so that they can get fixed as soon as possible!
*
* **Heads up!** If {@link render} or {@link renderSync} is called without
* {@link LegacyFileOptions.file} or {@link LegacyStringOptions.file},
* <em>all</em> stylesheets it loads will be considered dependencies. Since it
* doesnt have a path of its own, everything it loads is coming from a load
* path rather than a relative import.
*
* @defaultValue `false`
* @category Messages
* @compatibility dart: "1.35.0", node: false
*/
quietDeps?: boolean;
/**
* By default, Dart Sass will print only five instances of the same
* deprecation warning per compilation to avoid deluging users in console
* noise. If you set `verbose` to `true`, it will instead print every
* deprecation warning it encounters.
*
* @defaultValue `false`
* @category Messages
* @compatibility dart: "1.35.0", node: false
*/
verbose?: boolean;
/**
* An object to use to handle warnings and/or debug messages from Sass.
*
* By default, Sass emits warnings and debug messages to standard error, but
* if {@link Logger.warn} or {@link Logger.debug} is set, this will invoke
* them instead.
*
* The special value {@link Logger.silent} can be used to easily silence all
* messages.
*
* @category Messages
* @compatibility dart: "1.43.0", node: false
*/
logger?: Logger;
/**
* If this option is set to an instance of `NodePackageImporter`, Sass will
* use the built-in Node.js package importer to resolve Sass files with a
* `pkg:` URL scheme. Details for library authors and users can be found in
* the {@link NodePackageImporter} documentation.
*
* @example
* ```js
* sass.renderSync({
* data: '@use "pkg:vuetify";',
* pkgImporter: new sass.NodePackageImporter()
* });
* ```
* @category Plugins
* @compatibility dart: "2.0", node: false
*/
pkgImporter?: NodePackageImporter;
}
/**
* If {@link file} is passed without {@link data}, Sass will load the stylesheet
* at {@link file} and compile it to CSS.
*
* @typeParam sync - This lets the TypeScript checker verify that {@link
* LegacyAsyncImporter}s and {@link LegacyAsyncFunction}s aren't passed to
* {@link renderSync}.
*/
export interface LegacyFileOptions<sync extends 'sync' | 'async'>
extends LegacySharedOptions<sync> {
/**
* The path to the file for Sass to load and compile. If the files extension
* is `.scss`, it will be parsed as SCSS; if its `.sass`, it will be parsed
* as the indented syntax; and if its `.css`, it will be parsed as plain CSS.
* If it has no extension, it will be parsed as SCSS.
*
* @example
*
* ```js
* sass.renderSync({file: "style.scss"});
* ```
*
* @category Input
* @compatibility feature: "Plain CSS files", dart: "1.11.0", node: "partial"
*
* Node Sass and older versions of Dart Sass support loading files with the
* extension `.css`, but contrary to the specification theyre treated as SCSS
* files rather than being parsed as CSS. This behavior has been deprecated
* and should not be relied on. Any files that use Sass features should use
* the `.scss` extension.
*
* All versions of Node Sass and Dart Sass otherwise support the file option
* as described below.
*/
file: string;
/**
* See {@link LegacyStringOptions.file} for documentation of passing {@link
* file} along with {@link data}.
*
* @category Input
*/
data?: never;
}
/**
* If {@link data} is passed, Sass will use it as the contents of the stylesheet
* to compile.
*
* @typeParam sync - This lets the TypeScript checker verify that {@link
* LegacyAsyncImporter}s and {@link LegacyAsyncFunction}s aren't passed to
* {@link renderSync}.
*
* @category Legacy
* @deprecated This only works with the legacy {@link render} and {@link
* renderSync} APIs. Use {@link StringOptions} with {@link compile}, {@link
* compileString}, {@link compileAsync}, and {@link compileStringAsync} instead.
*/
export interface LegacyStringOptions<sync extends 'sync' | 'async'>
extends LegacySharedOptions<sync> {
/**
* The contents of the stylesheet to compile. Unless {@link file} is passed as
* well, the stylesheets URL is set to `"stdin"`.
*
* By default, this stylesheet is parsed as SCSS. This can be controlled using
* {@link indentedSyntax}.
*
* @example
*
* ```js
* sass.renderSync({
* data: `
* h1 {
* font-size: 40px;
* }`
* });
* ```
*
* @category Input
*/
data: string;
/**
* If `file` and {@link data} are both passed, `file` is used as the path of
* the stylesheet for error reporting, but {@link data} is used as the
* contents of the stylesheet. In this case, `file`s extension is not used to
* determine the syntax of the stylesheet.
*
* @category Input
*/
file?: string;
/**
* This flag controls whether {@link data} is parsed as the indented syntax or
* not.
*
* @example
*
* ```js
* sass.renderSync({
* data: `
* h1
* font-size: 40px`,
* indentedSyntax: true
* });
* ```
*
* @defaultValue `false`
* @category Input
*/
indentedSyntax?: boolean;
}
/**
* Options for {@link render} and {@link renderSync}. This can either be {@link
* LegacyFileOptions} to load a file from disk, or {@link LegacyStringOptions}
* to compile a string of Sass code.
*
* See {@link LegacySharedOptions} for options that are shared across both file
* and string inputs.
*
* @category Legacy
* @deprecated This only works with the legacy {@link render} and {@link
* renderSync} APIs. Use {@link Options} with {@link compile}, {@link
* compileString}, {@link compileAsync}, and {@link compileStringAsync} instead.
*/
export type LegacyOptions<sync extends 'sync' | 'async'> =
| LegacyFileOptions<sync>
| LegacyStringOptions<sync>;

View File

@ -0,0 +1,385 @@
import { isDefinedIcon } from "../ui-library/icons.js";
import { colorForIntegration, iconForIntegration } from "./utils/icons.js";
import { createWindowElement } from "./utils/window.js";
const astroLogo = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 99 26" width="100"><path fill="#fff" d="M6.70402 22.1453c-1.17459-1.0737-1.51748-3.3297-1.02811-4.9641.84853 1.0304 2.02424 1.3569 3.24204 1.5411 1.88005.2844 3.72635.178 5.47285-.6813.1998-.0984.3844-.2292.6027-.3617.1639.4755.2065.9554.1493 1.4439-.1392 1.1898-.7313 2.1088-1.673 2.8054-.3765.2787-.775.5278-1.1639.7905-1.1948.8075-1.518 1.7544-1.0691 3.1318.0107.0336.0202.0671.0444.149-.6101-.273-1.0557-.6705-1.39518-1.1931-.3586-.5517-.52921-1.1619-.53819-1.8221-.00449-.3213-.00449-.6455-.0477-.9623-.10551-.7722-.46804-1.118-1.15102-1.1379-.70094-.0205-1.2554.4129-1.40244 1.0953-.01122.0523-.02749.1041-.04377.1649l.00112.0006Z"/><path fill="url(#paint0_linear_386_2739)" d="M6.70402 22.1453c-1.17459-1.0737-1.51748-3.3297-1.02811-4.9641.84853 1.0304 2.02424 1.3569 3.24204 1.5411 1.88005.2844 3.72635.178 5.47285-.6813.1998-.0984.3844-.2292.6027-.3617.1639.4755.2065.9554.1493 1.4439-.1392 1.1898-.7313 2.1088-1.673 2.8054-.3765.2787-.775.5278-1.1639.7905-1.1948.8075-1.518 1.7544-1.0691 3.1318.0107.0336.0202.0671.0444.149-.6101-.273-1.0557-.6705-1.39518-1.1931-.3586-.5517-.52921-1.1619-.53819-1.8221-.00449-.3213-.00449-.6455-.0477-.9623-.10551-.7722-.46804-1.118-1.15102-1.1379-.70094-.0205-1.2554.4129-1.40244 1.0953-.01122.0523-.02749.1041-.04377.1649l.00112.0006Z"/><path fill="#fff" d="M0 16.909s3.47815-1.6944 6.96603-1.6944l2.62973-8.13858c.09846-.39359.38592-.66106.71044-.66106.3246 0 .612.26747.7105.66106l2.6297 8.13858c4.1309 0 6.966 1.6944 6.966 1.6944S14.7045.814589 14.693.782298C14.5234.306461 14.2371 0 13.8512 0H6.76183c-.38593 0-.66063.306461-.84174.782298C5.90733.81398 0 16.909 0 16.909ZM36.671 11.7318c0 1.4262-1.7739 2.2779-4.2302 2.2779-1.5985 0-2.1638-.3962-2.1638-1.2281 0-.8715.7018-1.2875 2.3003-1.2875 1.4426 0 2.6707.0198 4.0937.1981v.0396Zm.0195-1.7629c-.8772-.19808-2.2028-.31693-3.7818-.31693-4.6006 0-6.7644 1.08943-6.7644 3.62483 0 2.6344 1.4815 3.6446 4.9125 3.6446 2.9046 0 4.8735-.7328 5.5947-2.5354h.117c-.0195.4358-.039.8716-.039 1.2083 0 .931.156 1.0102.9162 1.0102h3.5869c-.1949-.5546-.3119-2.1194-.3119-3.4663 0-1.446.0585-2.5355.0585-4.00123 0-2.99098-1.7934-4.89253-7.4077-4.89253-2.4173 0-5.1074.41596-7.1543 1.03.1949.81213.4679 2.45617.6043 3.5258 1.774-.83193 4.2887-1.18847 6.2381-1.18847 2.6902 0 3.4309.61404 3.4309 1.86193v.4952ZM46.5325 12.5637c-.4874.0594-1.1502.0594-1.8325.0594-.7213 0-1.3841-.0198-1.8324-.0792 0 .1585-.0195.3367-.0195.4952 0 2.476 1.618 3.922 7.3102 3.922 5.3609 0 7.0958-1.4262 7.0958-3.9418 0-2.3769-1.1501-3.5456-6.238-3.8031-3.9573-.17827-4.3082-.61404-4.3082-1.10924 0-.57442.5068-.87154 3.158-.87154 2.7487 0 3.4894.37635 3.4894 1.16866v.17827c.3899-.01981 1.0917-.03961 1.813-.03961.6823 0 1.423.0198 1.8519.05942 0-.17827.0195-.33674.0195-.47539 0-2.91175-2.4172-3.86252-7.0958-3.86252-5.2634 0-7.0373 1.2875-7.0373 3.8031 0 2.25805 1.423 3.66445 6.472 3.88235 3.7233.1188 4.1327.5348 4.1327 1.1092 0 .6141-.6043.8914-3.2165.8914-3.0021 0-3.7623-.416-3.7623-1.2677v-.1189ZM63.6883 2.125c-1.423 1.32712-3.9768 2.65425-5.3998 3.01079.0195.73289.0195 2.07982.0195 2.81271l1.3061.01981c-.0195 1.40635-.039 3.10979-.039 4.23889 0 2.6344 1.3841 4.6152 5.6922 4.6152 1.813 0 3.0216-.1981 4.5226-.515-.1559-.9706-.3314-2.4562-.3898-3.5852-.8968.2971-2.0274.4556-3.275.4556-1.735 0-2.4368-.4754-2.4368-1.8422 0-1.1884 0-2.29767.0195-3.32768 2.2223.01981 4.4446.05943 5.7507.09904-.0195-1.03.0195-2.51559.078-3.50598-1.8909.03961-4.0157.05942-5.7702.05942.0195-.87154.039-1.70347.0585-2.5354h-.1365ZM75.3313 7.35427c.0195-1.03001.039-1.90156.0585-2.75329h-3.9183c.0585 1.70347.0585 3.44656.0585 6.00172 0 2.5553-.0195 4.3182-.0585 6.0018h4.4836c-.078-1.1885-.0975-3.189-.0975-4.8925 0-2.69388 1.0917-3.46638 3.5674-3.46638 1.1502 0 1.9689.13865 2.6902.39615.0195-1.01019.2144-2.97117.3314-3.84271-.7408-.21789-1.5595-.35655-2.5537-.35655-2.1249-.0198-3.6844.85174-4.4056 2.93156l-.156-.0198ZM94.8501 10.5235c0 2.1591-1.5595 3.1693-4.0157 3.1693-2.4368 0-3.9963-.9508-3.9963-3.1693 0-2.21846 1.579-3.05039 3.9963-3.05039 2.4367 0 4.0157.89135 4.0157 3.05039Zm4.0743-.099c0-4.29832-3.353-6.21968-8.09-6.21968-4.7566 0-7.9926 1.92136-7.9926 6.21968 0 4.2785 3.0216 6.5762 7.9731 6.5762 4.9904 0 8.1095-2.2977 8.1095-6.5762Z"/><defs><linearGradient id="paint0_linear_386_2739" x1="5.46011" x2="16.8017" y1="25.9999" y2="20.6412" gradientUnits="userSpaceOnUse"><stop stop-color="#D83333"/><stop offset="1" stop-color="#F041FF"/></linearGradient></defs></svg>';
let integrationData;
var astro_default = {
id: "astro:home",
name: "Menu",
icon: "astro:logo",
async init(canvas, eventTarget) {
createCanvas();
document.addEventListener("astro:after-swap", createCanvas);
eventTarget.addEventListener("app-toggled", async (event) => {
resetDebugButton();
if (!(event instanceof CustomEvent))
return;
if (event.detail.state === true) {
if (!integrationData)
fetch("https://astro.build/api/v1/dev-overlay/", {
cache: "no-cache"
}).then((res) => res.json()).then((data) => {
integrationData = data;
integrationData.data = integrationData.data.map((integration) => {
return integration;
});
refreshIntegrationList();
});
}
});
function createCanvas() {
const links = [
{
icon: "bug",
name: "Report a Bug",
link: "https://github.com/withastro/astro/issues/new/choose"
},
{
icon: "lightbulb",
name: "Feedback",
link: "https://github.com/withastro/roadmap/discussions/new/choose"
},
{
icon: "file-search",
name: "Documentation",
link: "https://docs.astro.build"
},
{
icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 17 14"><path fill="currentColor" d="M14.3451 1.9072c-1.0375-.47613-2.1323-.81595-3.257-1.010998-.0102-.001716-.0207-.000234-.03.004243s-.017.011728-.022.020757c-.141.249998-.297.576998-.406.832998-1.2124-.18399-2.44561-.18399-3.658 0-.12159-.28518-.25914-.56328-.412-.832998-.00513-.00893-.01285-.016098-.02213-.02056-.00928-.004462-.0197-.00601-.02987-.00444-1.125.193998-2.22.533998-3.257 1.010998-.00888.00339-.0163.00975-.021.018-2.074 3.099-2.643004 6.122-2.364004 9.107.001.014.01.028.021.037 1.207724.8946 2.558594 1.5777 3.995004 2.02.01014.0032.02103.0031.03111-.0003.01007-.0034.01878-.01.02489-.0187.308-.42.582-.863.818-1.329.00491-.0096.0066-.0205.0048-.0312-.00181-.0106-.007-.0204-.0148-.0278-.00517-.0049-.0113-.0086-.018-.011-.43084-.1656-.84811-.3645-1.248-.595-.01117-.0063-.01948-.0167-.0232-.029-.00373-.0123-.00258-.0255.0032-.037.0034-.0074.00854-.014.015-.019.084-.063.168-.129.248-.195.00706-.0057.01554-.0093.02453-.0106.00898-.0012.01813 0 .02647.0036 2.619 1.196 5.454 1.196 8.041 0 .0086-.0037.0181-.0051.0275-.0038.0093.0012.0181.0049.0255.0108.08.066.164.132.248.195.0068.005.0123.0116.0159.0192.0036.0076.0053.016.0049.0244-.0003.0084-.0028.0166-.0072.0238-.0043.0072-.0104.0133-.0176.0176-.399.2326-.8168.4313-1.249.594-.0069.0025-.0132.0065-.0183.0117-.0052.0051-.0092.0114-.0117.0183-.0023.0067-.0032.0138-.0027.0208.0005.0071.0024.0139.0057.0202.24.465.515.909.817 1.329.0061.0087.0148.0153.0249.0187.0101.0034.021.0035.0311.0003 1.4388-.441 2.7919-1.1241 4.001-2.02.0061-.0042.0111-.0097.0147-.0161.0037-.0064.0058-.0135.0063-.0209.334-3.451-.559-6.449-2.366-9.106-.0018-.00439-.0045-.00834-.008-.01162-.0034-.00327-.0075-.00578-.012-.00738Zm-8.198 7.307c-.789 0-1.438-.724-1.438-1.612 0-.889.637-1.613 1.438-1.613.807 0 1.45.73 1.438 1.613 0 .888-.637 1.612-1.438 1.612Zm5.316 0c-.788 0-1.438-.724-1.438-1.612 0-.889.637-1.613 1.438-1.613.807 0 1.451.73 1.438 1.613 0 .888-.631 1.612-1.438 1.612Z"/></svg>',
name: "Community",
link: "https://astro.build/chat"
}
];
const windowComponent = createWindowElement(
`<style>
#buttons-container {
display: flex;
gap: 16px;
justify-content: center;
}
#buttons-container astro-dev-toolbar-card {
flex: 1;
}
footer {
display: flex;
justify-content: center;
gap: 24px;
}
footer a {
color: rgba(145, 152, 173, 1);
}
footer a:hover {
color: rgba(204, 206, 216, 1);
}
#main-container {
display: flex;
flex-direction: column;
height: 100%;
gap: 24px;
}
p {
margin-top: 0;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
}
header section {
display: flex;
gap: 0.8em;
}
h2 {
color: white;
margin: 0;
font-size: 18px;
}
a {
color: rgba(224, 204, 250, 1);
}
a:hover {
color: #f4ecfd;
}
#integration-list-wrapper {
position: relative;
--offset: 24px;
overflow-x: auto;
overflow-y: hidden;
margin-left: calc(var(--offset) * -1);
margin-right: calc(var(--offset) * -1);
padding-left: var(--offset);
padding-right: var(--offset);
height: 210px;
}
/* Pseudo-elements to fade cards as they scroll out of viewport */
#integration-list-wrapper::before,
#integration-list-wrapper::after {
content: '';
height: 192px;
display: block;
position: fixed;
width: var(--offset);
top: 106px;
background: red;
}
#integration-list-wrapper::before {
left: -1px;
border-left: 1px solid rgba(52, 56, 65, 1);
background: linear-gradient(to right, rgba(19, 21, 26, 1), rgba(19, 21, 26, 0));
}
#integration-list-wrapper::after {
right: -1px;
border-right: 1px solid rgba(52, 56, 65, 1);
background: linear-gradient(to left, rgba(19, 21, 26, 1), rgba(19, 21, 26, 0));
}
#integration-list-wrapper::-webkit-scrollbar {
width: 5px;
height: 8px;
background-color: rgba(255, 255, 255, 0.08); /* or add it to the track */
border-radius: 4px;
}
/* This is wild but gives us a gap on either side of the container */
#integration-list-wrapper::-webkit-scrollbar-button:start:decrement,
#integration-list-wrapper::-webkit-scrollbar-button:end:increment {
display: block;
width: 24px;
background-color: #13151A;
}
/* Removes arrows on both sides */
#integration-list-wrapper::-webkit-scrollbar-button:horizontal:start:increment,
#integration-list-wrapper::-webkit-scrollbar-button:horizontal:end:decrement {
display: none;
}
#integration-list-wrapper::-webkit-scrollbar-track-piece {
border-radius: 4px;
}
#integration-list-wrapper::-webkit-scrollbar-thumb {
background-color: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
#integration-list {
margin-top: 1em;
display: flex;
gap: 16px;
padding-bottom: 1em;
}
#integration-list::after {
content: " ";
display: inline-block;
white-space: pre;
width: 1px;
height: 1px;
}
#integration-list astro-dev-toolbar-card, .integration-skeleton {
min-width: 240px;
height: 160px;
}
.integration-skeleton {
animation: pulse 2s calc(var(--i, 0) * 250ms) cubic-bezier(0.4, 0, 0.6, 1) infinite;
background-color: rgba(35, 38, 45, 1);
border-radius: 8px;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: .5;
}
}
#integration-list astro-dev-toolbar-card .integration-image {
width: 40px;
height: 40px;
background-color: var(--integration-image-background, white);
border-radius: 9999px;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 8px;
}
#integration-list astro-dev-toolbar-card img {
width: 24px;
height: 24px;
}
#integration-list astro-dev-toolbar-card astro-dev-toolbar-icon {
width: 24px;
height: 24px;
color: #fff;
}
#links {
margin: auto 0;
display: flex;
justify-content: center;
gap: 24px;
}
#links a {
text-decoration: none;
align-items: center;
display: flex;
flex-direction: column;
gap: 0.7em;
flex: 1;
white-space: nowrap;
font-weight: 600;
color: white;
}
#links a:hover {
color: rgba(145, 152, 173, 1);
}
#links astro-dev-toolbar-icon {
width: 1.5em;
height: 1.5em;
display: block;
}
#integration-list astro-dev-toolbar-card svg {
width: 24px;
height: 24px;
vertical-align: bottom;
}
#integration-list astro-dev-toolbar-card h3 {
margin: 0;
margin-bottom: 8px;
color: white;
white-space: nowrap;
}
#integration-list astro-dev-toolbar-card p {
font-size: 14px;
}
@media (forced-colors: active) {
svg path[fill="#fff"] {
fill: black;
}
}
</style>
<header>
<section>
${astroLogo}
<astro-dev-toolbar-badge badge-style="gray" size="large">${window.__astro_dev_toolbar__.version}</astro-dev-toolbar-badge>
</section>
<astro-dev-toolbar-button id="copy-debug-button">Copy debug info <astro-dev-toolbar-icon icon="copy" /></astro-dev-toolbar-button>
</header>
<hr />
<div id="main-container">
<div>
<header><h2>Featured integrations</h2><a href="https://astro.build/integrations/" target="_blank">View all</a></header>
<div id="integration-list-wrapper">
<section id="integration-list">
<div class="integration-skeleton" style="--i:0;"></div>
<div class="integration-skeleton" style="--i:1;"></div>
<div class="integration-skeleton" style="--i:2;"></div>
<div class="integration-skeleton" style="--i:3;"></div>
<div class="integration-skeleton" style="--i:4;"></div>
</section>
</div>
</div>
<section id="links">
${links.map(
(link) => `<a href="${link.link}" target="_blank"><astro-dev-toolbar-icon ${isDefinedIcon(link.icon) ? `icon="${link.icon}">` : `>${link.icon}`}</astro-dev-toolbar-icon>${link.name}</a>`
).join("")}
</section>
</div>
`
);
const copyDebugButton = windowComponent.querySelector("#copy-debug-button");
copyDebugButton?.addEventListener("click", () => {
navigator.clipboard.writeText(
"```\n" + window.__astro_dev_toolbar__.debugInfo + "\n```"
);
copyDebugButton.textContent = "Copied to clipboard!";
setTimeout(() => {
resetDebugButton();
}, 3500);
});
canvas.append(windowComponent);
}
function resetDebugButton() {
const copyDebugButton = canvas.querySelector("#copy-debug-button");
if (!copyDebugButton)
return;
copyDebugButton.innerHTML = 'Copy debug info <astro-dev-toolbar-icon icon="copy" />';
}
function refreshIntegrationList() {
const integrationList = canvas.querySelector("#integration-list");
if (!integrationList)
return;
integrationList.innerHTML = "";
const fragment = document.createDocumentFragment();
for (const integration of integrationData.data) {
const integrationComponent = document.createElement("astro-dev-toolbar-card");
integrationComponent.link = integration.homepageUrl;
const integrationContainer = document.createElement("div");
integrationContainer.className = "integration-container";
const integrationImage = document.createElement("div");
integrationImage.className = "integration-image";
if (integration.image) {
const img = document.createElement("img");
img.src = integration.image;
img.alt = integration.title;
integrationImage.append(img);
} else {
const icon = document.createElement("astro-dev-toolbar-icon");
icon.icon = iconForIntegration(integration);
integrationImage.append(icon);
integrationImage.style.setProperty(
"--integration-image-background",
colorForIntegration()
);
}
integrationContainer.append(integrationImage);
let integrationTitle = document.createElement("h3");
integrationTitle.textContent = integration.title;
if (integration.official || integration.categories.includes("official")) {
integrationTitle.innerHTML += ' <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 21 20"><rect width="19" height="19" x="1.16602" y=".5" fill="url(#paint0_linear_917_1096)" fill-opacity=".33" rx="9.5"/><path fill="#fff" d="M15.139 6.80657c-.062-.06248-.1357-.11208-.217-.14592-.0812-.03385-.1683-.05127-.2563-.05127-.0881 0-.1752.01742-.2564.05127-.0813.03384-.155.08344-.217.14592L9.22566 11.7799 7.13899 9.68657c-.06435-.06216-.14031-.11103-.22355-.14383-.08323-.03281-.17211-.04889-.26157-.04735-.08945.00155-.17773.0207-.25978.05637a.68120694.68120694 0 0 0-.21843.15148c-.06216.06435-.11104.14031-.14384.22355-.0328.08321-.04889.17211-.04734.26161.00154.0894.0207.1777.05636.2597.03566.0821.08714.1563.15148.2185l2.56 2.56c.06198.0625.13571.1121.21695.1459s.16838.0513.25639.0513c.088 0 .17514-.0175.25638-.0513s.15497-.0834.21695-.1459L15.139 7.78657c.0677-.06242.1217-.13819.1586-.22253.0369-.08433.056-.1754.056-.26747 0-.09206-.0191-.18313-.056-.26747-.0369-.08433-.0909-.1601-.1586-.22253Z"/><rect width="19" height="19" x="1.16602" y=".5" stroke="url(#paint1_linear_917_1096)" rx="9.5"/><defs><linearGradient id="paint0_linear_917_1096" x1="20.666" x2="-3.47548" y1=".00000136" y2="10.1345" gradientUnits="userSpaceOnUse"><stop stop-color="#4AF2C8"/><stop offset="1" stop-color="#2F4CB3"/></linearGradient><linearGradient id="paint1_linear_917_1096" x1="20.666" x2="-3.47548" y1=".00000136" y2="10.1345" gradientUnits="userSpaceOnUse"><stop stop-color="#4AF2C8"/><stop offset="1" stop-color="#2F4CB3"/></linearGradient></defs></svg>';
}
integrationContainer.append(integrationTitle);
const integrationDescription = document.createElement("p");
integrationDescription.textContent = integration.description.length > 90 ? integration.description.slice(0, 90) + "\u2026" : integration.description;
integrationContainer.append(integrationDescription);
integrationComponent.append(integrationContainer);
fragment.append(integrationComponent);
}
integrationList.append(fragment);
}
}
};
export {
astro_default as default
};

View File

@ -0,0 +1,105 @@
import '@vitest/utils';
function collectOwnProperties(obj, collector) {
const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
Object.getOwnPropertyNames(obj).forEach(collect);
Object.getOwnPropertySymbols(obj).forEach(collect);
}
function groupBy(collection, iteratee) {
return collection.reduce((acc, item) => {
const key = iteratee(item);
acc[key] || (acc[key] = []);
acc[key].push(item);
return acc;
}, {});
}
function isPrimitive(value) {
return value === null || typeof value !== "function" && typeof value !== "object";
}
function getAllMockableProperties(obj, isModule, constructors) {
const {
Map,
Object: Object2,
Function,
RegExp,
Array: Array2
} = constructors;
const allProps = new Map();
let curr = obj;
do {
if (curr === Object2.prototype || curr === Function.prototype || curr === RegExp.prototype)
break;
collectOwnProperties(curr, (key) => {
const descriptor = Object2.getOwnPropertyDescriptor(curr, key);
if (descriptor)
allProps.set(key, { key, descriptor });
});
} while (curr = Object2.getPrototypeOf(curr));
if (isModule && !allProps.has("default") && "default" in obj) {
const descriptor = Object2.getOwnPropertyDescriptor(obj, "default");
if (descriptor)
allProps.set("default", { key: "default", descriptor });
}
return Array2.from(allProps.values());
}
function slash(str) {
return str.replace(/\\/g, "/");
}
function noop() {
}
function toArray(array) {
if (array === null || array === void 0)
array = [];
if (Array.isArray(array))
return array;
return [array];
}
function toString(v) {
return Object.prototype.toString.call(v);
}
function isPlainObject(val) {
return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
}
function deepMerge(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (isMergeableObject(target) && isMergeableObject(source)) {
Object.keys(source).forEach((key) => {
if (isMergeableObject(source[key])) {
if (!target[key])
target[key] = {};
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
});
}
return deepMerge(target, ...sources);
}
function isMergeableObject(item) {
return isPlainObject(item) && !Array.isArray(item);
}
function stdout() {
return console._stdout || process.stdout;
}
class AggregateErrorPonyfill extends Error {
errors;
constructor(errors, message = "") {
super(message);
this.errors = [...errors];
}
}
function isChildProcess() {
return typeof process !== "undefined" && !!process.send;
}
function setProcessTitle(title) {
try {
process.title = `node (${title})`;
} catch {
}
}
export { AggregateErrorPonyfill as A, isPrimitive as a, slash as b, groupBy as c, deepMerge as d, stdout as e, getAllMockableProperties as g, isChildProcess as i, noop as n, setProcessTitle as s, toArray as t };

View File

@ -0,0 +1,110 @@
const EXTERNAL_URL_REGEX = /^(?:[a-z+]+:)?\/\//i;
const perf = [
{
code: "perf-use-image-component",
title: "Use the Image component",
message: "This image could be replaced with the Image component to improve performance.",
selector: "img:not([data-image-component])",
async match(element) {
const src = element.getAttribute("src");
if (!src)
return false;
if (src.startsWith("data:"))
return false;
if (!EXTERNAL_URL_REGEX.test(src)) {
const imageData = await fetch(src).then((response) => response.blob());
if (imageData.size < 20480)
return false;
}
return true;
}
},
{
code: "perf-use-loading-lazy",
title: 'Use the loading="lazy" attribute',
message: (element) => `This ${element.nodeName} tag is below the fold and could be lazy-loaded to improve performance.`,
selector: 'img:not([loading]), img[loading="eager"], iframe:not([loading]), iframe[loading="eager"]',
match(element) {
const htmlElement = element;
if (htmlElement.offsetTop < window.innerHeight)
return false;
return true;
}
},
{
code: "perf-use-loading-eager",
title: 'Use the loading="eager" attribute',
message: (element) => `This ${element.nodeName} tag is above the fold and could be eagerly-loaded to improve performance.`,
selector: 'img[loading="lazy"], iframe[loading="lazy"]',
match(element) {
const htmlElement = element;
if (htmlElement.offsetTop > window.innerHeight)
return false;
return true;
}
},
{
code: "perf-use-videos",
title: "Use videos instead of GIFs for large animations",
message: "This GIF could be replaced with a video to reduce its file size and improve performance.",
selector: 'img[src$=".gif"]',
async match(element) {
const src = element.getAttribute("src");
if (!src)
return false;
if (EXTERNAL_URL_REGEX.test(src))
return false;
if (!EXTERNAL_URL_REGEX.test(src)) {
const imageData = await fetch(src).then((response) => response.blob());
if (imageData.size < 102400)
return false;
}
return true;
}
},
{
code: "perf-slow-component-server-render",
title: "Server-rendered component took a long time to render",
message: (element) => `This component took an unusually long time to render on the server (${getCleanRenderingTime(
element.getAttribute("server-render-time")
)}). This might be a sign that it's doing too much work on the server, or something is blocking rendering.`,
selector: "astro-island[server-render-time]",
match(element) {
const serverRenderTime = element.getAttribute("server-render-time");
if (!serverRenderTime)
return false;
const renderingTime = parseFloat(serverRenderTime);
if (Number.isNaN(renderingTime))
return false;
return renderingTime > 500;
}
},
{
code: "perf-slow-component-client-hydration",
title: "Client-rendered component took a long time to hydrate",
message: (element) => `This component took an unusually long time to render on the server (${getCleanRenderingTime(
element.getAttribute("client-render-time")
)}). This could be a sign that something is blocking the main thread and preventing the component from hydrating quickly.`,
selector: "astro-island[client-render-time]",
match(element) {
const clientRenderTime = element.getAttribute("client-render-time");
if (!clientRenderTime)
return false;
const renderingTime = parseFloat(clientRenderTime);
if (Number.isNaN(renderingTime))
return false;
return renderingTime > 500;
}
}
];
function getCleanRenderingTime(time) {
if (!time)
return "unknown";
const renderingTime = parseFloat(time);
if (Number.isNaN(renderingTime))
return "unknown";
return renderingTime.toFixed(2) + "s";
}
export {
perf
};

View File

@ -0,0 +1,12 @@
export type Options = {
root: Element;
idName: (name: string) => boolean;
className: (name: string) => boolean;
tagName: (name: string) => boolean;
attr: (name: string, value: string) => boolean;
seedMinLength: number;
optimizedMinLength: number;
threshold: number;
maxNumberOfTries: number;
};
export declare function finder(input: Element, options?: Partial<Options>): string;

View File

@ -0,0 +1,6 @@
import type { JSDOM } from 'jsdom'
declare global {
const jsdom: JSDOM
}
export {}

View File

@ -0,0 +1,2 @@
import type { IImage } from './interface.ts';
export declare const PNM: IImage;

View File

@ -0,0 +1,79 @@
# @vitest/snapshot
Lightweight implementation of Jest's snapshots.
## Usage
```js
import { SnapshotClient } from '@vitest/snapshot'
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment'
import { SnapshotManager } from '@vitest/snapshot/manager'
const client = new SnapshotClient({
// you need to provide your own equality check implementation if you use it
// this function is called when `.toMatchSnapshot({ property: 1 })` is called
isEqual: (received, expected) => equals(received, expected, [iterableEquality, subsetEquality]),
})
// class that implements snapshot saving and reading
// by default uses fs module, but you can provide your own implementation depending on the environment
const environment = new NodeSnapshotEnvironment()
// you need to implement this yourselves,
// this depends on your runner
function getCurrentFilepath() {
return '/file.spec.js'
}
function getCurrentTestName() {
return 'test1'
}
// example for inline snapshots, nothing is required to support regular snapshots,
// just call `assert` with `isInline: false`
function wrapper(received) {
function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
client.assert({
received,
message,
isInline: true,
inlineSnapshot,
filepath: getCurrentFilepath(),
name: getCurrentTestName(),
})
}
return {
// the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2)
// you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor
toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args),
}
}
const options = {
updateSnapshot: 'new',
snapshotEnvironment: environment,
}
await client.startCurrentRun(getCurrentFilepath(), getCurrentTestName(), options)
// this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath"
client.assert({
received: 'some text',
isInline: false,
})
// uses "pretty-format", so it requires quotes
// also naming is hard-coded when parsing test files
wrapper('text 1').toMatchInlineSnapshot()
wrapper('text 2').toMatchInlineSnapshot('"text 2"')
const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult
// you can use manager to manage several clients
const manager = new SnapshotManager(options)
manager.add(result)
// do something
// and then read the summary
console.log(manager.summary)
```

View File

@ -0,0 +1,11 @@
import { toUTF8String, readUInt32BE } from "./utils.js";
const PSD = {
validate: (input) => toUTF8String(input, 0, 4) === "8BPS",
calculate: (input) => ({
height: readUInt32BE(input, 14),
width: readUInt32BE(input, 18)
})
};
export {
PSD
};

Some files were not shown because too many files have changed in this diff Show More