chore: update versions

This commit is contained in:
github-actions[bot] 2024-02-14 19:45:06 +00:00
parent 8d9fc6c775
commit 4c0db299ca
1442 changed files with 319212 additions and 37 deletions

View File

@ -1,2 +0,0 @@
---
---

View File

@ -1,10 +0,0 @@
---
"@matthiesenxyz/create-astro-ghostcms": patch
---
Bump dependencies:
- @astrojs/rss from to
- vite from to
- unocss from to
- astro-font from to

View File

@ -1,10 +0,0 @@
---
"@matthiesenxyz/astro-ghostcms-brutalbyelian": patch
---
Bump dependencies:
- @astrojs/rss from to
- vite from to
- unocss from to
- astro-font from to

View File

@ -1,10 +0,0 @@
---
"@matthiesenxyz/astro-ghostcms": patch
---
Bump dependencies:
- @astrojs/rss from to
- vite from to
- unocss from to
- astro-font from to

View File

@ -0,0 +1,326 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleKindModifiers = exports.register = void 0;
const semver = require("semver");
const getUserPreferences_1 = require("../../configs/getUserPreferences");
const PConst = require("../../protocol.const");
const shared_1 = require("../../shared");
const modifiers_1 = require("../../utils/modifiers");
function register(ctx) {
const { ts } = ctx;
const lt_320 = semver.lt(ts.version, '3.2.0');
const gte_300 = semver.gte(ts.version, '3.0.0');
return async (uri, position, options) => {
const document = ctx.getTextDocument(uri);
if (!document)
return;
const preferences = await (0, getUserPreferences_1.getUserPreferences)(ctx, document);
const fileName = ctx.uriToFileName(document.uri);
const offset = document.offsetAt(position);
const completionContext = (0, shared_1.safeCall)(() => ctx.languageService.getCompletionsAtPosition(fileName, offset, {
...preferences,
...options,
}));
if (completionContext === undefined)
return;
const wordRange = completionContext.optionalReplacementSpan ? {
start: document.positionAt(completionContext.optionalReplacementSpan.start),
end: document.positionAt(completionContext.optionalReplacementSpan.start + completionContext.optionalReplacementSpan.length),
} : undefined;
let line = document.getText({
start: { line: position.line, character: 0 },
end: { line: position.line + 1, character: 0 },
});
if (line.endsWith('\n')) {
line = line.substring(0, line.length - 1);
}
const dotAccessorContext = getDotAccessorContext(document);
const entries = completionContext.entries
.map(tsEntry => toVScodeItem(tsEntry, document));
return {
isIncomplete: !!completionContext.isIncomplete,
items: entries,
};
function toVScodeItem(tsEntry, document) {
const item = { label: tsEntry.name };
item.kind = convertKind(tsEntry.kind);
if (tsEntry.source && tsEntry.hasAction) {
// De-prioritize auto-imports
// https://github.com/microsoft/vscode/issues/40311
item.sortText = '\uffff' + tsEntry.sortText;
}
else {
item.sortText = tsEntry.sortText;
}
const { sourceDisplay, isSnippet, labelDetails } = tsEntry;
if (sourceDisplay) {
item.labelDetails ??= {};
item.labelDetails.description = ts.displayPartsToString(sourceDisplay);
}
if (labelDetails) {
item.labelDetails ??= {};
Object.assign(item.labelDetails, labelDetails);
}
item.preselect = tsEntry.isRecommended;
let range = getRangeFromReplacementSpan(tsEntry, document);
item.commitCharacters = getCommitCharacters(tsEntry, {
isNewIdentifierLocation: completionContext.isNewIdentifierLocation,
isInValidCommitCharacterContext: isInValidCommitCharacterContext(document, position),
enableCallCompletions: true, // TODO: suggest.completeFunctionCalls
});
item.insertText = tsEntry.insertText;
item.insertTextFormat = isSnippet ? 2 : 1;
item.filterText = getFilterText(tsEntry, wordRange, line, tsEntry.insertText);
if (completionContext?.isMemberCompletion && dotAccessorContext && !isSnippet) {
item.filterText = dotAccessorContext.text + (item.insertText || item.label);
if (!range) {
const replacementRange = wordRange;
if (replacementRange) {
range = {
inserting: dotAccessorContext.range,
replacing: rangeUnion(dotAccessorContext.range, replacementRange),
};
}
else {
range = dotAccessorContext.range;
}
item.insertText = item.filterText;
}
}
handleKindModifiers(item, tsEntry);
if (!range && wordRange) {
range = {
inserting: { start: wordRange.start, end: position },
replacing: wordRange,
};
}
if (range) {
if ('start' in range) {
item.textEdit = {
range,
newText: item.insertText || item.label,
};
}
else {
item.textEdit = {
insert: range.inserting,
replace: range.replacing,
newText: item.insertText || item.label,
};
}
}
return {
...item,
data: {
uri,
fileName,
offset,
originalItem: {
name: tsEntry.name,
source: tsEntry.source,
data: tsEntry.data,
labelDetails: tsEntry.labelDetails,
},
},
};
}
function getDotAccessorContext(document) {
let dotAccessorContext;
if (gte_300) {
if (!completionContext)
return;
const isMemberCompletion = completionContext.isMemberCompletion;
if (isMemberCompletion) {
const dotMatch = line.slice(0, position.character).match(/\??\.\s*$/) || undefined;
if (dotMatch) {
const range = {
start: { line: position.line, character: position.character - dotMatch[0].length },
end: position,
};
const text = document.getText(range);
dotAccessorContext = { range, text };
}
}
}
return dotAccessorContext;
}
// from vscode typescript
function getRangeFromReplacementSpan(tsEntry, document) {
if (!tsEntry.replacementSpan) {
return;
}
let replaceRange = {
start: document.positionAt(tsEntry.replacementSpan.start),
end: document.positionAt(tsEntry.replacementSpan.start + tsEntry.replacementSpan.length),
};
// Make sure we only replace a single line at most
if (replaceRange.start.line !== replaceRange.end.line) {
replaceRange = {
start: {
line: replaceRange.start.line,
character: replaceRange.start.character,
},
end: {
line: replaceRange.start.line,
character: document.positionAt(document.offsetAt({ line: replaceRange.start.line + 1, character: 0 }) - 1).character,
},
};
}
// If TS returns an explicit replacement range, we should use it for both types of completion
return {
inserting: replaceRange,
replacing: replaceRange,
};
}
function getFilterText(tsEntry, wordRange, line, insertText) {
// Handle private field completions
if (tsEntry.name.startsWith('#')) {
const wordStart = wordRange ? line.charAt(wordRange.start.character) : undefined;
if (insertText) {
if (insertText.startsWith('this.#')) {
return wordStart === '#' ? insertText : insertText.replace(/^this\.#/, '');
}
else {
return insertText;
}
}
else {
return wordStart === '#' ? undefined : tsEntry.name.replace(/^#/, '');
}
}
// For `this.` completions, generally don't set the filter text since we don't want them to be overly prioritized. #74164
if (insertText?.startsWith('this.')) {
return undefined;
}
// Handle the case:
// ```
// const xyz = { 'ab c': 1 };
// xyz.ab|
// ```
// In which case we want to insert a bracket accessor but should use `.abc` as the filter text instead of
// the bracketed insert text.
else if (insertText?.startsWith('[')) {
return insertText.replace(/^\[['"](.+)[['"]\]$/, '.$1');
}
// In all other cases, fallback to using the insertText
return insertText;
}
function convertKind(kind) {
switch (kind) {
case PConst.Kind.primitiveType:
case PConst.Kind.keyword:
return 14;
case PConst.Kind.const:
case PConst.Kind.let:
case PConst.Kind.variable:
case PConst.Kind.localVariable:
case PConst.Kind.alias:
case PConst.Kind.parameter:
return 6;
case PConst.Kind.memberVariable:
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
return 5;
case PConst.Kind.function:
case PConst.Kind.localFunction:
return 3;
case PConst.Kind.method:
case PConst.Kind.constructSignature:
case PConst.Kind.callSignature:
case PConst.Kind.indexSignature:
return 2;
case PConst.Kind.enum:
return 13;
case PConst.Kind.enumMember:
return 20;
case PConst.Kind.module:
case PConst.Kind.externalModuleName:
return 9;
case PConst.Kind.class:
case PConst.Kind.type:
return 7;
case PConst.Kind.interface:
return 8;
case PConst.Kind.warning:
return 1;
case PConst.Kind.script:
return 17;
case PConst.Kind.directory:
return 19;
case PConst.Kind.string:
return 21;
default:
return 10;
}
}
function getCommitCharacters(entry, context) {
if (entry.kind === PConst.Kind.warning) { // Ambient JS word based suggestion
return undefined;
}
if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
return undefined;
}
const commitCharacters = ['.', ',', ';'];
if (context.enableCallCompletions) {
commitCharacters.push('(');
}
return commitCharacters;
}
function isInValidCommitCharacterContext(document, position) {
if (lt_320) {
// Workaround for https://github.com/microsoft/TypeScript/issues/27742
// Only enable dot completions when the previous character is not a dot preceded by whitespace.
// Prevents incorrectly completing while typing spread operators.
if (position.character > 1) {
const preText = document.getText({
start: { line: position.line, character: 0 },
end: position,
});
return preText.match(/(\s|^)\.$/ig) === null;
}
}
return true;
}
};
}
exports.register = register;
function handleKindModifiers(item, tsEntry) {
if (tsEntry.kindModifiers) {
const kindModifiers = (0, modifiers_1.parseKindModifier)(tsEntry.kindModifiers);
if (kindModifiers.has(PConst.KindModifiers.optional)) {
if (!item.insertText) {
item.insertText = item.label;
}
if (!item.filterText) {
item.filterText = item.label;
}
item.label += '?';
}
if (kindModifiers.has(PConst.KindModifiers.deprecated)) {
item.tags = [1];
}
if (kindModifiers.has(PConst.KindModifiers.color)) {
item.kind = 16;
}
if (tsEntry.kind === PConst.Kind.script) {
for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
if (kindModifiers.has(extModifier)) {
if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
item.detail = tsEntry.name;
}
else {
item.detail = tsEntry.name + extModifier;
}
break;
}
}
}
}
}
exports.handleKindModifiers = handleKindModifiers;
function rangeUnion(a, b) {
const start = (a.start.line < b.start.line || (a.start.line === b.start.line && a.start.character < b.start.character)) ? a.start : b.start;
const end = (a.end.line > b.end.line || (a.end.line === b.end.line && a.end.character > b.end.character)) ? a.end : b.end;
return { start, end };
}
//# sourceMappingURL=basic.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"prefer-ts-expect-error.js","sourceRoot":"","sources":["../../src/rules/prefer-ts-expect-error.ts"],"names":[],"mappings":";;AACA,oDAA2D;AAG3D,kCAAqC;AAIrC,kBAAe,IAAA,iBAAU,EAAiB;IACxC,IAAI,EAAE,wBAAwB;IAC9B,IAAI,EAAE;QACJ,IAAI,EAAE,SAAS;QACf,IAAI,EAAE;YACJ,WAAW,EAAE,oDAAoD;YACjE,WAAW,EAAE,QAAQ;SACtB;QACD,OAAO,EAAE,MAAM;QACf,QAAQ,EAAE;YACR,wBAAwB,EACtB,yEAAyE;SAC5E;QACD,MAAM,EAAE,EAAE;KACX;IACD,cAAc,EAAE,EAAE;IAClB,MAAM,CAAC,OAAO;QACZ,MAAM,wBAAwB,GAAG,sBAAsB,CAAC;QACxD,MAAM,uBAAuB,GAAG,6BAA6B,CAAC;QAE9D,SAAS,aAAa,CAAC,OAAyB;YAC9C,OAAO,OAAO,CAAC,IAAI,KAAK,uBAAe,CAAC,IAAI,CAAC;QAC/C,CAAC;QAED,SAAS,kBAAkB,CAAC,OAAyB;YACnD,IAAI,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC;gBAC3B,OAAO,OAAO,CAAC,KAAK,CAAC;YACvB,CAAC;YAED,0DAA0D;YAC1D,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC/C,OAAO,YAAY,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC/C,CAAC;QAED,SAAS,sBAAsB,CAAC,OAAyB;YACvD,MAAM,IAAI,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC;YACzC,OAAO,aAAa,CAAC,OAAO,CAAC;gBAC3B,CAAC,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC;gBACrC,CAAC,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzC,CAAC;QAED,OAAO;YACL,OAAO;gBACL,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,cAAc,EAAE,CAAC;gBACrD,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;oBACzB,IAAI,sBAAsB,CAAC,OAAO,CAAC,EAAE,CAAC;wBACpC,MAAM,oBAAoB,GAAG,CAAC,KAAgB,EAAW,EAAE,CACzD,KAAK,CAAC,WAAW,CACf,OAAO,EACP,KAAK,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,kBAAkB,CAAC,EAAE,CAC/D,CAAC;wBAEJ,MAAM,qBAAqB,GAAG,CAAC,KAAgB,EAAW,EAAE,CAC1D,KAAK,CAAC,WAAW,CACf,OAAO,EACP,KAAK,OAAO,CAAC,KAAK,CAAC,OAAO,CACxB,YAAY,EACZ,kBAAkB,CACnB,IAAI,CACN,CAAC;wBAEJ,OAAO,CAAC,MAAM,CAAC;4BACb,IAAI,EAAE,OAAO;4BACb,SAAS,EAAE,0BAA0B;4BACrC,GAAG,EAAE,aAAa,CAAC,OAAO,CAAC;gCACzB,CAAC,CAAC,oBAAoB;gCACtB,CAAC,CAAC,qBAAqB;yBAC1B,CAAC,CAAC;oBACL,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}

View File

@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWorkspaceFolderManager = void 0;
function createWorkspaceFolderManager() {
let folders = [];
const onDidAddCallbacks = new Set();
const onDidRemoveCallbacks = new Set();
return {
add(folder) {
if (!folders.some(uri => uri.toString() === folder.toString())) {
folders.push(folder);
}
},
remove(folder) {
folders = folders.filter(uri => uri.toString() !== folder.toString());
},
getAll() {
return folders;
},
onDidAdd(cb) {
onDidAddCallbacks.add(cb);
return {
dispose() {
onDidAddCallbacks.delete(cb);
},
};
},
onDidRemove(cb) {
onDidRemoveCallbacks.add(cb);
return {
dispose() {
onDidRemoveCallbacks.delete(cb);
},
};
},
};
}
exports.createWorkspaceFolderManager = createWorkspaceFolderManager;
//# sourceMappingURL=workspaceFolderManager.js.map

View File

@ -0,0 +1,21 @@
'use strict';
var $TypeError = require('es-errors/type');
var ToInt32 = require('../ToInt32');
var ToUint32 = require('../ToUint32');
// https://262.ecma-international.org/11.0/#sec-numeric-types-number-leftShift
module.exports = function NumberLeftShift(x, y) {
if (typeof x !== 'number' || typeof y !== 'number') {
throw new $TypeError('Assertion failed: `x` and `y` arguments must be Numbers');
}
var lnum = ToInt32(x);
var rnum = ToUint32(y);
var shiftCount = rnum & 0x1F;
return lnum << shiftCount;
};

View File

@ -0,0 +1,143 @@
'use strict';
var hasOwn = require('hasown');
var inspect = require('object-inspect');
var supportsDescriptors = require('define-properties').supportsDescriptors;
var v = require('es-value-fixtures');
var forEach = require('for-each');
var availableFlags = require('available-regexp-flags');
var regexProperties = require('available-regexp-flags/properties');
var sortedFlags = availableFlags.slice().sort(function (a, b) { return a.localeCompare(b); }).join('');
var getRegexLiteral = function (stringRegex) {
try {
// eslint-disable-next-line no-new-func
return Function('return ' + stringRegex + ';')();
} catch (e) { /**/ }
return null;
};
module.exports = function runTests(flags, t) {
forEach(v.primitives, function (nonObject) {
t['throws'](
function () { flags(nonObject); },
TypeError,
'throws when called with a non-object receiver: ' + inspect(nonObject)
);
});
t.equal(flags(/a/g), 'g', 'flags(/a/g) !== "g"');
t.equal(flags(/a/gmi), 'gim', 'flags(/a/gmi) !== "gim"');
t.equal(flags(new RegExp('a', 'gmi')), 'gim', 'flags(new RegExp("a", "gmi")) !== "gim"');
t.equal(flags(/a/), '', 'flags(/a/) !== ""');
t.equal(flags(new RegExp('a')), '', 'flags(new RegExp("a")) !== ""');
forEach(availableFlags, function (flag) {
var property = regexProperties[flag];
t.test(property + ' flag', function (st) {
st.equal(flags(getRegexLiteral('/a/' + flag)), flag, 'flags(/a/' + flag + ') !== ' + inspect(flag));
st.equal(flags(new RegExp('a', flag)), flag, 'flags(new RegExp("a", ' + inspect(flag) + ')) !== ' + inspect(flag));
st.end();
});
});
t.test('sorting', function (st) {
st.equal(flags(/a/gim), 'gim', 'flags(/a/gim) !== "gim"');
st.equal(flags(/a/mig), 'gim', 'flags(/a/mig) !== "gim"');
st.equal(flags(/a/mgi), 'gim', 'flags(/a/mgi) !== "gim"');
if (hasOwn(RegExp.prototype, 'sticky')) {
st.equal(flags(getRegexLiteral('/a/gyim')), 'gimy', 'flags(/a/gyim) !== "gimy"');
}
if (hasOwn(RegExp.prototype, 'unicode')) {
st.equal(flags(getRegexLiteral('/a/ugmi')), 'gimu', 'flags(/a/ugmi) !== "gimu"');
}
if (hasOwn(RegExp.prototype, 'dotAll')) {
st.equal(flags(getRegexLiteral('/a/sgmi')), 'gims', 'flags(/a/sgmi) !== "gims"');
}
var randomFlags = availableFlags.slice().sort(function () { return Math.random() > 0.5 ? 1 : -1; }).join('').replace('v', '');
st.equal(
flags(getRegexLiteral('/a/' + randomFlags)),
sortedFlags.replace('v', ''),
'random: flags(/a/' + randomFlags + ') === ' + inspect(sortedFlags)
);
st.end();
});
t.test('basic examples', function (st) {
st.equal(flags(/a/g), 'g', '(/a/g).flags !== "g"');
st.equal(flags(/a/gmi), 'gim', '(/a/gmi).flags !== "gim"');
st.equal(flags(new RegExp('a', 'gmi')), 'gim', 'new RegExp("a", "gmi").flags !== "gim"');
st.equal(flags(/a/), '', '(/a/).flags !== ""');
st.equal(flags(new RegExp('a')), '', 'new RegExp("a").flags !== ""');
st.end();
});
t.test('generic flags', function (st) {
st.equal(flags({}), '');
st.equal(flags({ ignoreCase: true }), 'i');
st.equal(flags({ dotAll: 1, global: 0, sticky: 1, unicode: 1 }), 'suy');
st.equal(flags({ __proto__: { multiline: true } }), 'm');
var obj = {};
forEach(availableFlags, function (flag) {
if (flag !== 'v') {
obj[regexProperties[flag]] = true;
}
});
st.equal(flags(obj), sortedFlags.replace('v', ''), 'an object with every available flag: ' + sortedFlags);
st.end();
});
t.test('getters', { skip: !supportsDescriptors }, function (st) {
/* eslint getter-return: 0 */
var calls = '';
var re = {};
Object.defineProperty(re, 'hasIndices', {
get: function () {
calls += 'd';
}
});
Object.defineProperty(re, 'global', {
get: function () {
calls += 'g';
}
});
Object.defineProperty(re, 'ignoreCase', {
get: function () {
calls += 'i';
}
});
Object.defineProperty(re, 'multiline', {
get: function () {
calls += 'm';
}
});
Object.defineProperty(re, 'dotAll', {
get: function () {
calls += 's';
}
});
Object.defineProperty(re, 'unicode', {
get: function () {
calls += 'u';
}
});
Object.defineProperty(re, 'sticky', {
get: function () {
calls += 'y';
}
});
flags(re);
st.equal(calls, 'dgimsuy', 'getters are called in expected order');
st.end();
});
};

View File

@ -0,0 +1 @@
{"version":3,"file":"disable-type-checked.js","sourceRoot":"","sources":["../../src/configs/disable-type-checked.ts"],"names":[],"mappings":";AAAA,wCAAwC;AACxC,gCAAgC;AAChC,mDAAmD;AACnD,EAAE;AACF,4DAA4D;AAC5D,sDAAsD;AAItD,iBAAS;IACP,aAAa,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE;IAChD,KAAK,EAAE;QACL,mCAAmC,EAAE,KAAK;QAC1C,4CAA4C,EAAE,KAAK;QACnD,iCAAiC,EAAE,KAAK;QACxC,sCAAsC,EAAE,KAAK;QAC7C,oCAAoC,EAAE,KAAK;QAC3C,sCAAsC,EAAE,KAAK;QAC7C,iDAAiD,EAAE,KAAK;QACxD,mDAAmD,EAAE,KAAK;QAC1D,yCAAyC,EAAE,KAAK;QAChD,oCAAoC,EAAE,KAAK;QAC3C,oCAAoC,EAAE,KAAK;QAC3C,iDAAiD,EAAE,KAAK;QACxD,wCAAwC,EAAE,KAAK;QAC/C,mCAAmC,EAAE,KAAK;QAC1C,mDAAmD,EAAE,KAAK;QAC1D,qCAAqC,EAAE,KAAK;QAC5C,2DAA2D,EAAE,KAAK;QAClE,6CAA6C,EAAE,KAAK;QACpD,6CAA6C,EAAE,KAAK;QACpD,kDAAkD,EAAE,KAAK;QACzD,kDAAkD,EAAE,KAAK;QACzD,uCAAuC,EAAE,KAAK;QAC9C,yCAAyC,EAAE,KAAK;QAChD,mCAAmC,EAAE,KAAK;QAC1C,8CAA8C,EAAE,KAAK;QACrD,4CAA4C,EAAE,KAAK;QACnD,qCAAqC,EAAE,KAAK;QAC5C,0CAA0C,EAAE,KAAK;QACjD,iDAAiD,EAAE,KAAK;QACxD,sDAAsD,EAAE,KAAK;QAC7D,yCAAyC,EAAE,KAAK;QAChD,gCAAgC,EAAE,KAAK;QACvC,oCAAoC,EAAE,KAAK;QAC3C,8CAA8C,EAAE,KAAK;QACrD,0CAA0C,EAAE,KAAK;QACjD,iDAAiD,EAAE,KAAK;QACxD,oCAAoC,EAAE,KAAK;QAC3C,oDAAoD,EAAE,KAAK;QAC3D,iDAAiD,EAAE,KAAK;QACxD,uCAAuC,EAAE,KAAK;QAC9C,4CAA4C,EAAE,KAAK;QACnD,mDAAmD,EAAE,KAAK;QAC1D,2CAA2C,EAAE,KAAK;QAClD,+CAA+C,EAAE,KAAK;QACtD,kCAAkC,EAAE,KAAK;QACzC,2CAA2C,EAAE,KAAK;QAClD,kDAAkD,EAAE,KAAK;QACzD,iCAAiC,EAAE,KAAK;QACxC,+CAA+C,EAAE,KAAK;QACtD,gDAAgD,EAAE,KAAK;QACvD,mCAAmC,EAAE,KAAK;KAC3C;CAC6B,CAAC"}

View File

@ -0,0 +1,18 @@
'use strict';
var $TypeError = require('es-errors/type');
var isNaN = require('../../helpers/isNaN');
// https://262.ecma-international.org/11.0/#sec-numeric-types-number-equal
module.exports = function NumberEqual(x, y) {
if (typeof x !== 'number' || typeof y !== 'number') {
throw new $TypeError('Assertion failed: `x` and `y` arguments must be Numbers');
}
if (isNaN(x) || isNaN(y)) {
return false;
}
// shortcut for the actual spec mechanics
return x === y;
};

View File

@ -0,0 +1,43 @@
import v8 from 'node:v8';
import { c as createForksRpcOptions, u as unwrapForksConfig } from '../vendor/utils.GbToHGHI.js';
import { r as runVmTests } from '../vendor/vm.jVxKtN5R.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.TxmaEFIQ.js';
import 'vite-node/client';
import 'vite-node/utils';
import '@vitest/utils/error';
import '../path.js';
import 'node:fs';
import '../vendor/base.QYERqzkH.js';
import 'node:module';
import 'vite-node/constants';
import '../vendor/index.rJjbcrrp.js';
import 'std-env';
import '@vitest/runner/utils';
import '../vendor/global.CkGT_TMy.js';
class ForksVmWorker {
getRpcOptions() {
return createForksRpcOptions(v8);
}
async runTests(state) {
const exit = process.exit;
state.ctx.config = unwrapForksConfig(state.ctx.config);
try {
await runVmTests(state);
} finally {
process.exit = exit;
}
}
}
var vmForks = new ForksVmWorker();
export { vmForks as default };

View File

@ -0,0 +1,26 @@
'use strict';
var $TypeError = require('es-errors/type');
var IsAccessorDescriptor = require('./IsAccessorDescriptor');
var IsDataDescriptor = require('./IsDataDescriptor');
var isPropertyDescriptor = require('../helpers/records/property-descriptor');
// https://262.ecma-international.org/6.0/#sec-isgenericdescriptor
module.exports = function IsGenericDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return false;
}
if (!isPropertyDescriptor(Desc)) {
throw new $TypeError('Assertion failed: `Desc` must be a Property Descriptor');
}
if (!IsAccessorDescriptor(Desc) && !IsDataDescriptor(Desc)) {
return true;
}
return false;
};

View File

@ -0,0 +1 @@
{"files":{"LICENSE":{"checkedAt":1707939899662,"integrity":"sha512-GInyRqrY/WcEsmb+HJQ6uhNRw81tNJpZtUPo00y+TQLmY602jHr1AwX75EcW4kAQyXFP76hxIJTSHQ07r1bEGw==","mode":420,"size":1087},"examples/CodeSlot.astro":{"checkedAt":1707939899662,"integrity":"sha512-mFFAwvk/8zP5Hh1CcbsYpD7fEc82WSAwamYjBFnvw0D3RIz/9sVdNOM4BmGh4r+9FPNU6p8fcx90hTPLIa9fiw==","mode":420,"size":364},"lib/GhostRender.astro":{"checkedAt":1707939899662,"integrity":"sha512-5H4jzpNZ2ILkzmf07MJCHtwApW/PJ0zQ6Mp7fKIQ/I7fCpQ7+uVQ+Qij2cMpnV9B7ahAkuS2IV1Grx5G1yzQVg==","mode":420,"size":497},"examples/H1.astro":{"checkedAt":1707939899662,"integrity":"sha512-jKPDDoCmUbN/+YIkcoUlt8f71rWWL9VxCWTif9ti0R1QNYlEncUn9S+6wWM0g4E1bwKmEWHnCp+9dGdhV7Jotw==","mode":420,"size":49},"examples/H2.astro":{"checkedAt":1707939899662,"integrity":"sha512-HF+dUUo61+1ag1g5bcnjE2jpWOQuXOu0xHElhejHJadn1lbuS+4jinhf0qjaK88IA8KLkdseRar4RytqJEPmtg==","mode":420,"size":49},"examples/H3.astro":{"checkedAt":1707939899662,"integrity":"sha512-0eR80lOMPXZbikaPPPXhjZSxrG9pdm6UBXR18SbrgksL5FfXw7+8iJ9HuCT38F1E3MYyvthCTJBPiYSAVLdA+Q==","mode":420,"size":49},"examples/H4.astro":{"checkedAt":1707939899662,"integrity":"sha512-PaK4UIeHR5Ts5CE9o48EvPSj/wYkFyxhQIlnMmJt5vGH+CXJbfXqt8j8ovt+y9qZpxBI+DWQWV20kMeIxC9yTA==","mode":420,"size":49},"examples/H5.astro":{"checkedAt":1707939899663,"integrity":"sha512-fmbCFzobBy86M2gjuuh/Xj134r0T8MOyk/zm9cUl9laTIgi0RUD2eb+gL9F0gHWMEbje25PZ50u95tiWuH4qGw==","mode":420,"size":49},"examples/H6.astro":{"checkedAt":1707939899663,"integrity":"sha512-6JJ/nSxeLhzD7EQirqCXjphgK206nWBT8cg9cwUyaEf9q4Y86KmqDHSCdyqOr9W4sDAUZMk9bDUeJWiRbhb0Gg==","mode":420,"size":49},"examples/Paragraph.astro":{"checkedAt":1707939899663,"integrity":"sha512-2ahTCmMr3AERzFTnKvlMgHP1qBwos+zctWhxWv/ZsJFA8q/TmCyD69vEneG//WUTKwOjKj8QDhskjg751897vQ==","mode":420,"size":366},"package.json":{"checkedAt":1707939899663,"integrity":"sha512-vfKVLmuQexiWlHoMhrjZBWDrJONabtdrPeMPglyNAuSWJAGZ67XNclWVfRzsogDUKAcjigAvvwG0HHgLPt28iA==","mode":420,"size":1031},"CHANGELOG.md":{"checkedAt":1707939899663,"integrity":"sha512-ozriQHiqHVPlTK5y7Uy7xUGZCnSVCGMhwuNYzIjCyQvqdN87ss8St2I4nYF5lYWf42MGS4r/IG057ESjXoD3fw==","mode":420,"size":159},"README.md":{"checkedAt":1707939899663,"integrity":"sha512-nA2Lo9F3nEo02w6nAmKfg3EzsWigpqh0xJ/RyiNdQhxWKG8wblFxz+HUbjLQ3Lz2u+ba/B3So0pavudovZp8Ig==","mode":420,"size":1008},"lib/env.d.ts":{"checkedAt":1707939899663,"integrity":"sha512-8Oak+OsQcW+0dU26weIgLtqUdFcycChdJNo4dZQ3AwUicaR3BijguysCOAO04CEBOssYIk7woPsHoTrao2cUKg==","mode":420,"size":39},"examples/index.ts":{"checkedAt":1707939899663,"integrity":"sha512-998vQt+NOtEpOi0qIyFjv3uxWiOOy7LiYq2lomp0JNyrD2CIaA1swQNR1hI9LN0UMqDxvpU5XWiHS9+Wd7UWgQ==","mode":420,"size":369},"index.ts":{"checkedAt":1707939899664,"integrity":"sha512-95bU6HJzZnB9QDH8IQfOnksHI0CGszESpJ9lIl+fN19Sep2OB6ZvjVft+DQVdRTkPrOccbU4DHeXhNRrvOuWag==","mode":420,"size":66},"lib/utils.ts":{"checkedAt":1707939899664,"integrity":"sha512-rJ06lktTaJshTMeyGxO6m+kSUR5m/Iw7ozaZ84CIooIouFpR5tXbJmmeCSnGiWpa5os5Iyoa1F19NVRCjajPyQ==","mode":420,"size":1782}}}

View File

@ -0,0 +1,49 @@
'use strict';
var $TypeError = require('es-errors/type');
var Call = require('./Call');
var CompletionRecord = require('./CompletionRecord');
var GetMethod = require('./GetMethod');
var IsCallable = require('./IsCallable');
var Type = require('./Type');
// https://262.ecma-international.org/6.0/#sec-iteratorclose
module.exports = function IteratorClose(iterator, completion) {
if (Type(iterator) !== 'Object') {
throw new $TypeError('Assertion failed: Type(iterator) is not Object');
}
if (!IsCallable(completion) && !(completion instanceof CompletionRecord)) {
throw new $TypeError('Assertion failed: completion is not a thunk representing a Completion Record, nor a Completion Record instance');
}
var completionThunk = completion instanceof CompletionRecord ? function () { return completion['?'](); } : completion;
var iteratorReturn = GetMethod(iterator, 'return');
if (typeof iteratorReturn === 'undefined') {
return completionThunk();
}
var completionRecord;
try {
var innerResult = Call(iteratorReturn, iterator, []);
} catch (e) {
// if we hit here, then "e" is the innerResult completion that needs re-throwing
// if the completion is of type "throw", this will throw.
completionThunk();
completionThunk = null; // ensure it's not called twice.
// if not, then return the innerResult completion
throw e;
}
completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does
completionThunk = null; // ensure it's not called twice.
if (Type(innerResult) !== 'Object') {
throw new $TypeError('iterator .return must return an object');
}
return completionRecord;
};

View File

@ -0,0 +1,93 @@
{
"name": "array-buffer-byte-length",
"version": "1.0.1",
"description": "Get the byte length of an ArrayBuffer, even in engines without a `.byteLength` method.",
"main": "index.js",
"exports": {
".": "./index.js",
"./package.json": "./package.json"
},
"sideEffects": false,
"types": "./index.d.ts",
"scripts": {
"prepack": "npmignore --auto --commentLines=autogenerated",
"prepublishOnly": "safe-publish-latest",
"prepublish": "not-in-publish || npm run prepublishOnly",
"pretest": "npm run lint",
"prelint": "evalmd README.md",
"lint": "eslint --ext=js,mjs .",
"postlint": "tsc -p .",
"tests-only": "nyc tape 'test/**/*.js'",
"test": "npm run tests-only",
"posttest": "aud --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"keywords": [
"shim",
"polyfill",
"ArrayBuffer",
"byteLength",
"byte",
"length",
"es-shim API",
"es-shims"
],
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/inspect-js/array-buffer-byte-length.git"
},
"bugs": {
"url": "https://github.com/inspect-js/array-buffer-byte-length/issues"
},
"homepage": "https://github.com/inspect-js/array-buffer-byte-length#readme",
"dependencies": {
"call-bind": "^1.0.5",
"is-array-buffer": "^3.0.4"
},
"devDependencies": {
"@ljharb/eslint-config": "^21.1.0",
"@types/call-bind": "^1.0.5",
"@types/es-value-fixtures": "^1.4.4",
"@types/for-each": "^0.3.3",
"@types/object-inspect": "^1.8.4",
"@types/tape": "^5.6.4",
"aud": "^2.0.4",
"auto-changelog": "^2.4.0",
"es-value-fixtures": "^1.4.2",
"eslint": "=8.8.0",
"evalmd": "^0.0.19",
"for-each": "^0.3.3",
"in-publish": "^2.0.1",
"npmignore": "^0.3.1",
"nyc": "^10.3.2",
"object-inspect": "^1.13.1",
"safe-publish-latest": "^2.0.0",
"tape": "^5.7.4",
"typescript": "^5.4.0-dev.20240202"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"testling": {
"files": "test/index.js"
},
"publishConfig": {
"ignore": [
".github/workflows"
]
},
"engines": {
"node": ">= 0.4"
}
}

View File

@ -0,0 +1,247 @@
import type { ClassicConfig, FlatConfig, SharedConfig } from './Config';
import type { Parser } from './Parser';
import type { Processor as ProcessorType } from './Processor';
import type { AnyRuleCreateFunction, AnyRuleModule, RuleCreateFunction, RuleFix, RuleModule } from './Rule';
import type { SourceCode } from './SourceCode';
export type MinimalRuleModule<TMessageIds extends string = string, TOptions extends readonly unknown[] = []> = Partial<Omit<RuleModule<TMessageIds, TOptions>, 'create'>> & Pick<RuleModule<TMessageIds, TOptions>, 'create'>;
declare class LinterBase {
/**
* Initialize the Linter.
* @param config the config object
*/
constructor(config?: Linter.LinterOptions);
/**
* Define a new parser module
* @param parserId Name of the parser
* @param parserModule The parser object
*/
defineParser(parserId: string, parserModule: Parser.LooseParserModule): void;
/**
* Defines a new linting rule.
* @param ruleId A unique rule identifier
* @param ruleModule Function from context to object mapping AST node types to event handlers
*/
defineRule<TMessageIds extends string, TOptions extends readonly unknown[]>(ruleId: string, ruleModule: MinimalRuleModule<TMessageIds, TOptions> | RuleCreateFunction): void;
/**
* Defines many new linting rules.
* @param rulesToDefine map from unique rule identifier to rule
*/
defineRules<TMessageIds extends string, TOptions extends readonly unknown[]>(rulesToDefine: Record<string, MinimalRuleModule<TMessageIds, TOptions> | RuleCreateFunction<TMessageIds, TOptions>>): void;
/**
* Gets an object with all loaded rules.
* @returns All loaded rules
*/
getRules(): Map<string, MinimalRuleModule<string, unknown[]>>;
/**
* Gets the `SourceCode` object representing the parsed source.
* @returns The `SourceCode` object.
*/
getSourceCode(): SourceCode;
/**
* Verifies the text against the rules specified by the second argument.
* @param textOrSourceCode The text to parse or a SourceCode object.
* @param config An ESLintConfig instance to configure everything.
* @param filenameOrOptions The optional filename of the file being checked.
* If this is not set, the filename will default to '<input>' in the rule context.
* If this is an object, then it has "filename", "allowInlineConfig", and some properties.
* @returns The results as an array of messages or an empty array if no messages.
*/
verify(textOrSourceCode: SourceCode | string, config: Linter.ConfigType, filenameOrOptions?: Linter.VerifyOptions | string): Linter.LintMessage[];
/**
* Performs multiple autofix passes over the text until as many fixes as possible have been applied.
* @param code The source text to apply fixes to.
* @param config The ESLint config object to use.
* @param options The ESLint options object to use.
* @returns The result of the fix operation as returned from the SourceCodeFixer.
*/
verifyAndFix(code: string, config: Linter.ConfigType, options: Linter.FixOptions): Linter.FixReport;
/**
* The version from package.json.
*/
readonly version: string;
/**
* The version from package.json.
*/
static readonly version: string;
}
declare namespace Linter {
interface LinterOptions {
/**
* path to a directory that should be considered as the current working directory.
*/
cwd?: string;
}
type EnvironmentConfig = SharedConfig.EnvironmentConfig;
type GlobalsConfig = SharedConfig.GlobalsConfig;
type GlobalVariableOption = SharedConfig.GlobalVariableOption;
type GlobalVariableOptionBase = SharedConfig.GlobalVariableOptionBase;
type ParserOptions = SharedConfig.ParserOptions;
type PluginMeta = SharedConfig.PluginMeta;
type RuleEntry = SharedConfig.RuleEntry;
type RuleLevel = SharedConfig.RuleLevel;
type RuleLevelAndOptions = SharedConfig.RuleLevelAndOptions;
type RulesRecord = SharedConfig.RulesRecord;
type Severity = SharedConfig.Severity;
type SeverityString = SharedConfig.SeverityString;
/** @deprecated use Linter.ConfigType instead */
type Config = ClassicConfig.Config;
type ConfigType = ClassicConfig.Config | FlatConfig.ConfigArray;
/** @deprecated use ClassicConfig.ConfigOverride instead */
type ConfigOverride = ClassicConfig.ConfigOverride;
interface VerifyOptions {
/**
* Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied.
* Useful if you want to validate JS without comments overriding rules.
*/
allowInlineConfig?: boolean;
/**
* if `true` then the linter doesn't make `fix` properties into the lint result.
*/
disableFixes?: boolean;
/**
* the filename of the source code.
*/
filename?: string;
/**
* the predicate function that selects adopt code blocks.
*/
filterCodeBlock?: (filename: string, text: string) => boolean;
/**
* postprocessor for report messages.
* If provided, this should accept an array of the message lists
* for each code block returned from the preprocessor, apply a mapping to
* the messages as appropriate, and return a one-dimensional array of
* messages.
*/
postprocess?: ProcessorType.PostProcess;
/**
* preprocessor for source text.
* If provided, this should accept a string of source text, and return an array of code blocks to lint.
*/
preprocess?: ProcessorType.PreProcess;
/**
* Adds reported errors for unused `eslint-disable` directives.
*/
reportUnusedDisableDirectives?: SeverityString | boolean;
}
interface FixOptions extends VerifyOptions {
/**
* Determines whether fixes should be applied.
*/
fix?: boolean;
}
interface LintSuggestion {
desc: string;
fix: RuleFix;
messageId?: string;
}
interface LintMessage {
/**
* The 1-based column number.
*/
column: number;
/**
* The 1-based column number of the end location.
*/
endColumn?: number;
/**
* The 1-based line number of the end location.
*/
endLine?: number;
/**
* If `true` then this is a fatal error.
*/
fatal?: true;
/**
* Information for autofix.
*/
fix?: RuleFix;
/**
* The 1-based line number.
*/
line: number;
/**
* The error message.
*/
message: string;
messageId?: string;
nodeType: string;
/**
* The ID of the rule which makes this message.
*/
ruleId: string | null;
/**
* The severity of this message.
*/
severity: Severity;
source: string | null;
/**
* Information for suggestions
*/
suggestions?: LintSuggestion[];
}
interface FixReport {
/**
* True, if the code was fixed
*/
fixed: boolean;
/**
* Fixed code text (might be the same as input if no fixes were applied).
*/
output: string;
/**
* Collection of all messages for the given code
*/
messages: LintMessage[];
}
/** @deprecated use Parser.ParserModule */
type ParserModule = Parser.LooseParserModule;
/** @deprecated use Parser.ParseResult */
type ESLintParseResult = Parser.ParseResult;
/** @deprecated use Processor.ProcessorModule */
type Processor = ProcessorType.ProcessorModule;
interface Environment {
/**
* The definition of global variables.
*/
globals?: GlobalsConfig;
/**
* The parser options that will be enabled under this environment.
*/
parserOptions?: ParserOptions;
}
type LegacyPluginRules = Record<string, AnyRuleCreateFunction | AnyRuleModule>;
type PluginRules = Record<string, AnyRuleModule>;
interface Plugin {
/**
* The definition of plugin configs.
*/
configs?: Record<string, ClassicConfig.Config>;
/**
* The definition of plugin environments.
*/
environments?: Record<string, Environment>;
/**
* Metadata about your plugin for easier debugging and more effective caching of plugins.
*/
meta?: PluginMeta;
/**
* The definition of plugin processors.
*/
processors?: Record<string, ProcessorType.ProcessorModule>;
/**
* The definition of plugin rules.
*/
rules?: LegacyPluginRules;
}
}
declare const Linter_base: typeof LinterBase;
/**
* The Linter object does the actual evaluation of the JavaScript code. It doesn't do any filesystem operations, it
* simply parses and reports on the code. In particular, the Linter object does not process configuration objects
* or files.
*/
declare class Linter extends Linter_base {
}
export { Linter };
//# sourceMappingURL=Linter.d.ts.map

View File

@ -0,0 +1,4 @@
import type * as vscode from '@volar/language-service';
import type { SharedContext } from '../types';
export declare function register(ctx: SharedContext): (uri: string, position: vscode.Position) => vscode.DocumentHighlight[];
//# sourceMappingURL=documentHighlight.d.ts.map

View File

@ -0,0 +1,3 @@
declare function hasOwn<T extends {} = {}>(o: T, p: PropertyKey): p is keyof T;
export = hasOwn;

View File

@ -0,0 +1 @@
{"version":3,"file":"no-base-to-string.js","sourceRoot":"","sources":["../../src/rules/no-base-to-string.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,oDAA0D;AAC1D,+CAAiC;AAEjC,kCAAqE;AAErE,IAAK,UAIJ;AAJD,WAAK,UAAU;IACb,+BAAiB,CAAA;IACjB,4BAAc,CAAA;IACd,+BAAiB,CAAA;AACnB,CAAC,EAJI,UAAU,KAAV,UAAU,QAId;AASD,kBAAe,IAAA,iBAAU,EAAsB;IAC7C,IAAI,EAAE,mBAAmB;IACzB,IAAI,EAAE;QACJ,IAAI,EAAE;YACJ,WAAW,EACT,sGAAsG;YACxG,WAAW,EAAE,aAAa;YAC1B,oBAAoB,EAAE,IAAI;SAC3B;QACD,QAAQ,EAAE;YACR,YAAY,EACV,0EAA0E;SAC7E;QACD,MAAM,EAAE;YACN;gBACE,IAAI,EAAE,QAAQ;gBACd,UAAU,EAAE;oBACV,gBAAgB,EAAE;wBAChB,IAAI,EAAE,OAAO;wBACb,KAAK,EAAE;4BACL,IAAI,EAAE,QAAQ;yBACf;qBACF;iBACF;gBACD,oBAAoB,EAAE,KAAK;aAC5B;SACF;QACD,IAAI,EAAE,YAAY;KACnB;IACD,cAAc,EAAE;QACd;YACE,gBAAgB,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,iBAAiB,CAAC;SAChE;KACF;IACD,MAAM,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC;QACtB,MAAM,QAAQ,GAAG,IAAA,wBAAiB,EAAC,OAAO,CAAC,CAAC;QAC5C,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,cAAc,EAAE,CAAC;QAClD,MAAM,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,EAAE,CAAC;QAEvD,SAAS,eAAe,CAAC,IAAyB,EAAE,IAAc;YAChE,IAAI,IAAI,CAAC,IAAI,KAAK,sBAAc,CAAC,OAAO,EAAE,CAAC;gBACzC,OAAO;YACT,CAAC;YAED,MAAM,SAAS,GAAG,wBAAwB,CACxC,IAAI,IAAI,QAAQ,CAAC,iBAAiB,CAAC,IAAI,CAAC,CACzC,CAAC;YACF,IAAI,SAAS,KAAK,UAAU,CAAC,MAAM,EAAE,CAAC;gBACpC,OAAO;YACT,CAAC;YAED,OAAO,CAAC,MAAM,CAAC;gBACb,IAAI,EAAE;oBACJ,SAAS;oBACT,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC;iBACvC;gBACD,SAAS,EAAE,cAAc;gBACzB,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAED,SAAS,wBAAwB,CAAC,IAAa;YAC7C,MAAM,QAAQ,GAAG,OAAO,CAAC,iBAAiB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YAC7D,MAAM,YAAY,GAAG,QAAQ,EAAE,eAAe,EAAE,CAAC;YACjD,IAAI,CAAC,QAAQ,IAAI,CAAC,YAAY,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC5D,OAAO,UAAU,CAAC,MAAM,CAAC;YAC3B,CAAC;YAED,mFAAmF;YACnF,IACE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC,SAAS,CAAC,OAAO;gBACjC,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC,SAAS,CAAC,cAAc,EACxC,CAAC;gBACD,OAAO,UAAU,CAAC,MAAM,CAAC;YAC3B,CAAC;YAED,IAAI,gBAAgB,CAAC,QAAQ,CAAC,IAAA,kBAAW,EAAC,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;gBAC1D,OAAO,UAAU,CAAC,MAAM,CAAC;YAC3B,CAAC;YAED,IACE,YAAY,CAAC,KAAK,CAChB,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CACb,CAAC,EAAE,CAAC,sBAAsB,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,KAAK,QAAQ,CACtE,EACD,CAAC;gBACD,OAAO,UAAU,CAAC,MAAM,CAAC;YAC3B,CAAC;YAED,IAAI,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;gBAC1B,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;oBACjC,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAC;oBAE5D,IAAI,iBAAiB,KAAK,UAAU,CAAC,MAAM,EAAE,CAAC;wBAC5C,OAAO,UAAU,CAAC,MAAM,CAAC;oBAC3B,CAAC;gBACH,CAAC;gBAED,OAAO,UAAU,CAAC,KAAK,CAAC;YAC1B,CAAC;YAED,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;gBACpB,OAAO,UAAU,CAAC,KAAK,CAAC;YAC1B,CAAC;YAED,IAAI,iBAAiB,GAAG,IAAI,CAAC;YAC7B,IAAI,iBAAiB,GAAG,KAAK,CAAC;YAE9B,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACjC,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAC;gBAE5D,IAAI,iBAAiB,KAAK,UAAU,CAAC,MAAM,IAAI,iBAAiB,EAAE,CAAC;oBACjE,iBAAiB,GAAG,KAAK,CAAC;gBAC5B,CAAC;gBAED,IAAI,iBAAiB,KAAK,UAAU,CAAC,KAAK,IAAI,CAAC,iBAAiB,EAAE,CAAC;oBACjE,iBAAiB,GAAG,IAAI,CAAC;gBAC3B,CAAC;YACH,CAAC;YAED,IAAI,iBAAiB,IAAI,iBAAiB,EAAE,CAAC;gBAC3C,OAAO,UAAU,CAAC,MAAM,CAAC;YAC3B,CAAC;YAED,IAAI,iBAAiB,EAAE,CAAC;gBACtB,OAAO,UAAU,CAAC,SAAS,CAAC;YAC9B,CAAC;YAED,OAAO,UAAU,CAAC,KAAK,CAAC;QAC1B,CAAC;QAED,OAAO;YACL,yEAAyE,CACvE,IAA+D;gBAE/D,MAAM,QAAQ,GAAG,QAAQ,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACvD,MAAM,SAAS,GAAG,QAAQ,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBAEzD,IAAI,IAAA,kBAAW,EAAC,OAAO,EAAE,QAAQ,CAAC,KAAK,QAAQ,EAAE,CAAC;oBAChD,eAAe,CAAC,IAAI,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;gBACzC,CAAC;qBAAM,IACL,IAAA,kBAAW,EAAC,OAAO,EAAE,SAAS,CAAC,KAAK,QAAQ;oBAC5C,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,sBAAc,CAAC,iBAAiB,EACnD,CAAC;oBACD,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;gBACvC,CAAC;YACH,CAAC;YACD,mFAAmF,CACjF,IAAyB;gBAEzB,MAAM,UAAU,GAAG,IAAI,CAAC,MAAmC,CAAC;gBAC5D,eAAe,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YACrC,CAAC;YACD,eAAe,CAAC,IAA8B;gBAC5C,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,sBAAc,CAAC,wBAAwB,EAAE,CAAC;oBACjE,OAAO;gBACT,CAAC;gBACD,KAAK,MAAM,UAAU,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;oBAC1C,eAAe,CAAC,UAAU,CAAC,CAAC;gBAC9B,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}

View File

@ -0,0 +1,35 @@
'use strict';
var $SyntaxError = require('es-errors/syntax');
var $TypeError = require('es-errors/type');
var whichTypedArray = require('which-typed-array');
var availableTypedArrays = require('available-typed-arrays')();
var IsArray = require('./IsArray');
var TypedArrayCreate = require('./TypedArrayCreate');
var getConstructor = require('../helpers/typedArrayConstructors');
// https://262.ecma-international.org/14.0/#sec-typedarray-create-same-type
module.exports = function TypedArrayCreateSameType(exemplar, argumentList) {
if (availableTypedArrays.length === 0) {
throw new $SyntaxError('Assertion failed: Typed Arrays are not supported in this environment');
}
var kind = whichTypedArray(exemplar);
if (!kind) {
throw new $TypeError('Assertion failed: exemplar must be a TypedArray'); // step 1
}
if (!IsArray(argumentList)) {
throw new $TypeError('Assertion failed: `argumentList` must be a List'); // step 1
}
var constructor = getConstructor(kind); // step 2
if (typeof constructor !== 'function') {
throw new $SyntaxError('Assertion failed: `constructor` of `exemplar` (' + kind + ') must exist. Please report this!');
}
return TypedArrayCreate(constructor, argumentList); // steps 3 - 6
};

View File

@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'consistent-indexed-object-style',
meta: {
type: 'suggestion',
docs: {
description: 'Require or disallow the `Record` type',
recommended: 'stylistic',
},
messages: {
preferRecord: 'A record is preferred over an index signature.',
preferIndexSignature: 'An index signature is preferred over a record.',
},
fixable: 'code',
schema: [
{
type: 'string',
enum: ['record', 'index-signature'],
},
],
},
defaultOptions: ['record'],
create(context, [mode]) {
function checkMembers(members, node, parentId, prefix, postfix, safeFix = true) {
if (members.length !== 1) {
return;
}
const [member] = members;
if (member.type !== utils_1.AST_NODE_TYPES.TSIndexSignature) {
return;
}
const parameter = member.parameters.at(0);
if (parameter?.type !== utils_1.AST_NODE_TYPES.Identifier) {
return;
}
const keyType = parameter.typeAnnotation;
if (!keyType) {
return;
}
const valueType = member.typeAnnotation;
if (!valueType) {
return;
}
if (parentId) {
const scope = context.sourceCode.getScope(parentId);
const superVar = utils_1.ASTUtils.findVariable(scope, parentId.name);
if (superVar) {
const isCircular = superVar.references.some(item => item.isTypeReference &&
node.range[0] <= item.identifier.range[0] &&
node.range[1] >= item.identifier.range[1]);
if (isCircular) {
return;
}
}
}
context.report({
node,
messageId: 'preferRecord',
fix: safeFix
? (fixer) => {
const key = context.sourceCode.getText(keyType.typeAnnotation);
const value = context.sourceCode.getText(valueType.typeAnnotation);
const record = member.readonly
? `Readonly<Record<${key}, ${value}>>`
: `Record<${key}, ${value}>`;
return fixer.replaceText(node, `${prefix}${record}${postfix}`);
}
: null,
});
}
return {
...(mode === 'index-signature' && {
TSTypeReference(node) {
const typeName = node.typeName;
if (typeName.type !== utils_1.AST_NODE_TYPES.Identifier) {
return;
}
if (typeName.name !== 'Record') {
return;
}
const params = node.typeArguments?.params;
if (params?.length !== 2) {
return;
}
context.report({
node,
messageId: 'preferIndexSignature',
fix(fixer) {
const key = context.sourceCode.getText(params[0]);
const type = context.sourceCode.getText(params[1]);
return fixer.replaceText(node, `{ [key: ${key}]: ${type} }`);
},
});
},
}),
...(mode === 'record' && {
TSTypeLiteral(node) {
const parent = findParentDeclaration(node);
checkMembers(node.members, node, parent?.id, '', '');
},
TSInterfaceDeclaration(node) {
let genericTypes = '';
if (node.typeParameters?.params.length) {
genericTypes = `<${node.typeParameters.params
.map(p => context.sourceCode.getText(p))
.join(', ')}>`;
}
checkMembers(node.body.body, node, node.id, `type ${node.id.name}${genericTypes} = `, ';', !node.extends.length);
},
}),
};
},
});
function findParentDeclaration(node) {
if (node.parent && node.parent.type !== utils_1.AST_NODE_TYPES.TSTypeAnnotation) {
if (node.parent.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration) {
return node.parent;
}
return findParentDeclaration(node.parent);
}
return undefined;
}
//# sourceMappingURL=consistent-indexed-object-style.js.map

View File

@ -0,0 +1,12 @@
'use strict';
var $TypeError = require('es-errors/type');
// https://262.ecma-international.org/11.0/#sec-binaryand
module.exports = function BinaryAnd(x, y) {
if ((x !== 0 && x !== 1) || (y !== 0 && y !== 1)) {
throw new $TypeError('Assertion failed: `x` and `y` must be either 0 or 1');
}
return x & y;
};

View File

@ -0,0 +1 @@
{"files":{"dist/bin.js":{"checkedAt":1707939899101,"integrity":"sha512-Rd4m8UeAB44vSqNKrzBCbLmoHiOKeVM3uCvAY7FTLVrjI57NvDXhkLJF8PBCVOGmFJ3rHqjLH7W7jH3kbpG0Fg==","mode":493,"size":363},"dist/index.js":{"checkedAt":1707939899101,"integrity":"sha512-ZtAl+Iv9Y39KBM2bAVBtgLPsd73O07SLuqeV83JzZTtNk0VZQxSrdTcbJAL+5NVHclxSjxLmwUcu7pq9MuX08w==","mode":420,"size":3990},"dist/options.js":{"checkedAt":1707939899101,"integrity":"sha512-pTJro//hT/se/BU4kjU6++dK0sA6bPVf28EbuSXblPg1zCeNSqd+lt3Cy03zDinooQBjV2QfOwbKxXb34fbAZg==","mode":420,"size":1346},"dist/bin.d.ts":{"checkedAt":1707939899101,"integrity":"sha512-TuHIj4w/TkzTTLbAAzm/nW0Db/St469J6HHMiWa4THKdi3VJKsxkE8mmZKwApXlYIjrBPEIp2oxi6+alPk94Pw==","mode":420,"size":11},"dist/index.d.ts":{"checkedAt":1707939899101,"integrity":"sha512-Hdyyxbwm8kCzaAIV9bRB3qlPn4peer4x2mmYYHXknKZ1PQGa5xUXcbECJj7l+E2KtKGqDOL78vpNkageFPpatQ==","mode":420,"size":927},"dist/options.d.ts":{"checkedAt":1707939899101,"integrity":"sha512-6/P7tfaYF3O8Sw2xCjWH+Axhg3MLNfpUBjmjF3zTdeReolpkCnDxFN7oL87Bhb/LYNh7npWZ0CNPfPTXcF1vzg==","mode":420,"size":1574},"LICENSE":{"checkedAt":1707939899101,"integrity":"sha512-ZGZL3q3cqWfh6/hM1VUk2uyHxv8yb6flHo+YPGjbtIsJlROJyfk5mnVwX1/Ms0hZKIqi7PwvPZ9MaOxaFDXq3w==","mode":420,"size":1085},"package.json":{"checkedAt":1707939899101,"integrity":"sha512-C0+5Ob/YAu3iIhm944jioYvkVV5ZIoDJBVyXVOriGvezaOprHnV7lOYHljcyqDKVJVfrM8rNZ1hAuvRJ/JL8Tg==","mode":420,"size":1047}}}

View File

@ -0,0 +1,57 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $SyntaxError = require('es-errors/syntax');
var $TypeError = require('es-errors/type');
var $preventExtensions = GetIntrinsic('%Object.preventExtensions%', true);
var $gOPD = require('gopd');
var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%', true);
var forEach = require('../helpers/forEach');
var DefinePropertyOrThrow = require('./DefinePropertyOrThrow');
var IsAccessorDescriptor = require('./IsAccessorDescriptor');
var ToPropertyDescriptor = require('./ToPropertyDescriptor');
var Type = require('./Type');
// https://262.ecma-international.org/6.0/#sec-setintegritylevel
module.exports = function SetIntegrityLevel(O, level) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
if (level !== 'sealed' && level !== 'frozen') {
throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`');
}
if (!$preventExtensions) {
throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support');
}
var status = $preventExtensions(O);
if (!status) {
return false;
}
if (!$gOPN) {
throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support');
}
var theKeys = $gOPN(O);
if (level === 'sealed') {
forEach(theKeys, function (k) {
DefinePropertyOrThrow(O, k, { configurable: false });
});
} else if (level === 'frozen') {
forEach(theKeys, function (k) {
var currentDesc = $gOPD(O, k);
if (typeof currentDesc !== 'undefined') {
var desc;
if (IsAccessorDescriptor(ToPropertyDescriptor(currentDesc))) {
desc = { configurable: false };
} else {
desc = { configurable: false, writable: false };
}
DefinePropertyOrThrow(O, k, desc);
}
});
}
return true;
};

View File

@ -0,0 +1,36 @@
import { defaultSplitRE, isValidSelector } from '@unocss/core';
const sourceMapRE = /\/\/#\s*sourceMappingURL=.*\n?/g;
function removeSourceMap(code) {
if (code.includes("sourceMappingURL="))
return code.replace(sourceMapRE, "");
return code;
}
const quotedArbitraryValuesRE = /(?:[\w&:[\]-]|\[\S{1,64}=\S{1,64}\]){1,64}\[\\?['"]?\S{1,64}?['"]\]\]?[\w:-]{0,64}/g;
const arbitraryPropertyRE = /\[(\\\W|[\w-]){1,64}:[^\s:]{0,64}?("\S{1,64}?"|'\S{1,64}?'|`\S{1,64}?`|[^\s:]{1,64}?)[^\s:]{0,64}?\)?\]/g;
const arbitraryPropertyCandidateRE = /^\[(\\\W|[\w-]){1,64}:['"]?\S{1,64}?['"]?\]$/;
function splitCodeWithArbitraryVariants(code) {
const result = [];
for (const match of code.matchAll(arbitraryPropertyRE)) {
if (match.index !== 0 && !/^[\s'"`]/.test(code[match.index - 1] ?? ""))
continue;
result.push(match[0]);
}
for (const match of code.matchAll(quotedArbitraryValuesRE))
result.push(match[0]);
code.split(defaultSplitRE).forEach((match) => {
if (isValidSelector(match) && !arbitraryPropertyCandidateRE.test(match))
result.push(match);
});
return result;
}
const extractorArbitraryVariants = {
name: "@unocss/extractor-arbitrary-variants",
order: 0,
extract({ code }) {
return splitCodeWithArbitraryVariants(removeSourceMap(code));
}
};
export { arbitraryPropertyRE, extractorArbitraryVariants as default, extractorArbitraryVariants, quotedArbitraryValuesRE, splitCodeWithArbitraryVariants };

View File

@ -0,0 +1,354 @@
import { C as Colors } from './shared/preset-mini.hpPpX7ws.mjs';
import '@unocss/core';
declare const colors: {
inherit: string;
current: string;
transparent: string;
black: string;
white: string;
rose: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
pink: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
fuchsia: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
purple: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
violet: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
indigo: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
blue: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
sky: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
cyan: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
teal: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
emerald: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
green: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
lime: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
yellow: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
amber: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
orange: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
red: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
gray: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
slate: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
zinc: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
neutral: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
stone: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
light: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
dark: {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
950: string;
};
readonly lightblue: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly lightBlue: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly warmgray: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly warmGray: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly truegray: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly trueGray: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly coolgray: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly coolGray: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly bluegray: string | (Colors & {
DEFAULT?: string | undefined;
});
readonly blueGray: string | (Colors & {
DEFAULT?: string | undefined;
});
};
export { colors };

View File

@ -0,0 +1,885 @@
import limit from 'p-limit';
import { getSafeTimers, createDefer, format, isObject, objDisplay, objectAttr, noop, toArray, shuffle } from '@vitest/utils';
import { processError } from '@vitest/utils/error';
export { processError } from '@vitest/utils/error';
import { createChainable, generateHash, calculateSuiteHash, someTasksAreOnly, interpretTaskModes, partitionSuiteChildren, hasTests, hasFailed } from './utils.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);
};
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 fixtureArray = Object.entries(fixtures).map(([prop, value], index) => {
const isFn = typeof value === "function";
return {
prop,
value,
index,
isFn
};
});
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);
if (!usedProps.length)
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 }) => 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, fn, options) {
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), fn, options);
}
);
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 createSuiteCollector(name, factory = () => {
}, mode, concurrent, sequential, 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, fn = noop, options = {}) {
if (typeof options === "number")
options = { timeout: options };
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: fn }
);
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, factory, options = {}) {
const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
const currentSuite = getCurrentSuite();
if (typeof options === "number")
options = { timeout: options };
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.concurrent, this.sequential, 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, fn, options) => {
const _name = formatName(name);
const arrayOnlyCases = cases.every(Array.isArray);
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i];
arrayOnlyCases ? suite2(formatTitle(_name, items, idx), () => fn(...items), options) : suite2(formatTitle(_name, items, idx), () => fn(i), options);
});
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, fn2, options) => {
const _name = formatName(name);
const arrayOnlyCases = cases.every(Array.isArray);
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i];
arrayOnlyCases ? test2(formatTitle(_name, items, idx), () => fn2(...items), options) : test2(formatTitle(_name, items, idx), () => fn2(i), options);
});
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, fn2, options) {
getCurrentSuite().test.fn.call(this, formatName(name), fn2, options);
}, _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;
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);
}
}
if (test.result.state === "fail")
await Promise.all(((_f = test.onFailed) == null ? void 0 : _f.map((fn) => fn(test.result))) || []);
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 ((_g = runner.onAfterRunTask) == null ? void 0 : _g.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);
});
function createTestHook(name, handler) {
return (fn) => {
const current = getCurrentTest();
if (!current)
throw new Error(`Hook ${name}() can only be called inside a test`);
handler(current, fn);
};
}
export { afterAll, afterEach, beforeAll, beforeEach, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, setFn, setHooks, startTests, suite, test, updateTask };

View File

@ -0,0 +1,55 @@
'use strict';
var $TypeError = require('es-errors/type');
var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
var Call = require('./Call');
var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow');
var Get = require('./Get');
var HasProperty = require('./HasProperty');
var IsArray = require('./IsArray');
var ToLength = require('./ToLength');
var ToString = require('./ToString');
// https://262.ecma-international.org/10.0/#sec-flattenintoarray
module.exports = function FlattenIntoArray(target, source, sourceLen, start, depth) {
var mapperFunction;
if (arguments.length > 5) {
mapperFunction = arguments[5];
}
var targetIndex = start;
var sourceIndex = 0;
while (sourceIndex < sourceLen) {
var P = ToString(sourceIndex);
var exists = HasProperty(source, P);
if (exists === true) {
var element = Get(source, P);
if (typeof mapperFunction !== 'undefined') {
if (arguments.length <= 6) {
throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided');
}
element = Call(mapperFunction, arguments[6], [element, sourceIndex, source]);
}
var shouldFlatten = false;
if (depth > 0) {
shouldFlatten = IsArray(element);
}
if (shouldFlatten) {
var elementLen = ToLength(Get(element, 'length'));
targetIndex = FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1);
} else {
if (targetIndex >= MAX_SAFE_INTEGER) {
throw new $TypeError('index too large');
}
CreateDataPropertyOrThrow(target, ToString(targetIndex), element);
targetIndex += 1;
}
}
sourceIndex += 1;
}
return targetIndex;
};

View File

@ -0,0 +1 @@
{"files":{"LICENSE":{"checkedAt":1707939899407,"integrity":"sha512-o7HEIFnimZVIAv9KTD/PP6FfDvz7SNoM2Tyqrp7XIlPMtKl8zX2zLmOOIbS4YIvXl2tcZX7YPsvHpuGTYVMULQ==","mode":420,"size":1076},"lib/binarySearch.js":{"checkedAt":1707939899407,"integrity":"sha512-0ns4SJYmKiHuJy/p8c8m5IF0Zc8hWmVubRNeMr3T3Ocaa5tO7xoKWD1o6GQkQjZt2gM7uwyj3+6ZBMM9znWL/A==","mode":420,"size":893},"lib/buildMappings.js":{"checkedAt":1707939899407,"integrity":"sha512-8tHJyUZfabyQhb39+1VYATtCwJGEPx/htVqXMRoqTXzZbqcpdWdVXf4aA3zwF3CdKV67ZxFTx074ml7/S6jXBw==","mode":420,"size":738},"lib/buildStacks.js":{"checkedAt":1707939899408,"integrity":"sha512-VzOlGQ0vBRJeRUwMnTl4PCcTiW+E56Y7P0mvzy80ppr1/+FAiXcbrWngg/KwN9C1GgRhCILD+o97ANyEViVN/g==","mode":420,"size":794},"index.js":{"checkedAt":1707939899408,"integrity":"sha512-lLgRF7j/PoLvi3iD6k7H7CgXdqFlJyoj3mr/800V9noIBuWu90pMG7VOJrg9mB2coezA6+Lf+ylbzRY/gWrdEA==","mode":420,"size":1055},"lib/sourceMap.js":{"checkedAt":1707939899408,"integrity":"sha512-T50lF7tWh3w/nTzRgo1t9/ajBd9p+KQczQAsb72zAlfMgXp3EPrxEq1kT+nJ4/qxHd3Fz6hSj9SSFWRAEtuedg==","mode":420,"size":3004},"lib/translateOffset.js":{"checkedAt":1707939899408,"integrity":"sha512-uB1DBHFEgWynur0DJzajM5PY9t2IlyIICGcKE7+cpci8d/5JA9ienc82NjUWFnylhpKgRm1D/q3ZhS0BC5aAWQ==","mode":420,"size":567},"package.json":{"checkedAt":1707939899408,"integrity":"sha512-tCj9IKxyvYyqM8SP+LEB1zNoYjHD2groCZGSZ0N2h/czwgW5VbK0SpGvrH4nvbRmhdX9iagKEwo1jFj50wriYQ==","mode":420,"size":350},"README.md":{"checkedAt":1707939899409,"integrity":"sha512-/RNgy8NNHSpBsNeaV13zvE2C042IGCZEMn1tnp/gfPcrJfj98wHYLcyyo4PMs8Huf8zwV/7FZUvaCnjImkCzvg==","mode":420,"size":1560},"lib/binarySearch.d.ts":{"checkedAt":1707939899409,"integrity":"sha512-2uu6bR7ML/m6ittqNAm6EpsbwVNCtb6Amu91Eo2jyDHtef13YDyP6yr44PNvf3FRCJ5vLILtobXPPmrL/lZSzw==","mode":420,"size":148},"lib/buildMappings.d.ts":{"checkedAt":1707939899409,"integrity":"sha512-U7bPec6LJdy2jVxW1L9FRZUZaUXdaQwDRbODvbGlEfHZZJFRxLNbDm8uk7fQAGPg7du5bRHnMr0uhPzv3xiUuw==","mode":420,"size":168},"lib/buildStacks.d.ts":{"checkedAt":1707939899409,"integrity":"sha512-708XCmunK0Eq6THAF9c30UmbGqA0MK+hk/9xUJsME7RUisO5pkOR1MaDeD9FtLIy6Sp1lKswYOOxdi1Ws55uzA==","mode":420,"size":225},"index.d.ts":{"checkedAt":1707939899409,"integrity":"sha512-e8ALSCgrBJeNpOd81IiYJfdfJIDmnysnvxjhoxBmqo7gPUTwnQyyvO4kpjmgu+qAZbrhmGj7Ty9JdPuwksaIwg==","mode":420,"size":175},"lib/sourceMap.d.ts":{"checkedAt":1707939899409,"integrity":"sha512-1FQXyTm1eU6wctJ6kOiA3lNhVCXIYTWuOBoh6S2tePh/DZkVXTMi2O9P9+Yy+TiNPBkQhRZwonQr3Ysw88YrfQ==","mode":420,"size":1022},"lib/translateOffset.d.ts":{"checkedAt":1707939899410,"integrity":"sha512-pAKimjAoTG8A5xvNb64uJxp5cvYZ06YRPj99ydkOBuX8Jjf69EuZInyd4BWMg9OPrweXoGeoPenwNTl6EJessA==","mode":420,"size":139}}}

View File

@ -0,0 +1,450 @@
import { createRequire } from 'node:module';
import { dirname } from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
import vm from 'node:vm';
import { resolve } from 'pathe';
import createDebug from 'debug';
import { createImportMetaEnvProxy, normalizeModuleId, slash, isInternalRequest, isNodeBuiltin, normalizeRequestId, toFilePath, cleanUrl, isPrimitive } from './utils.mjs';
import { extractSourceMap } from './source-map.mjs';
import 'node:fs';
const { setTimeout, clearTimeout } = globalThis;
const debugExecute = createDebug("vite-node:client:execute");
const debugNative = createDebug("vite-node:client:native");
const clientStub = {
injectQuery: (id) => id,
createHotContext: () => {
return {
accept: () => {
},
prune: () => {
},
dispose: () => {
},
decline: () => {
},
invalidate: () => {
},
on: () => {
},
send: () => {
}
};
},
updateStyle: () => {
},
removeStyle: () => {
}
};
const env = createImportMetaEnvProxy();
const DEFAULT_REQUEST_STUBS = {
"/@vite/client": clientStub,
"@vite/client": clientStub
};
class ModuleCacheMap extends Map {
normalizePath(fsPath) {
return normalizeModuleId(fsPath);
}
/**
* Assign partial data to the map
*/
update(fsPath, mod) {
fsPath = this.normalizePath(fsPath);
if (!super.has(fsPath))
this.setByModuleId(fsPath, mod);
else
Object.assign(super.get(fsPath), mod);
return this;
}
setByModuleId(modulePath, mod) {
return super.set(modulePath, mod);
}
set(fsPath, mod) {
return this.setByModuleId(this.normalizePath(fsPath), mod);
}
getByModuleId(modulePath) {
if (!super.has(modulePath))
this.setByModuleId(modulePath, {});
const mod = super.get(modulePath);
if (!mod.imports) {
Object.assign(mod, {
imports: /* @__PURE__ */ new Set(),
importers: /* @__PURE__ */ new Set()
});
}
return mod;
}
get(fsPath) {
return this.getByModuleId(this.normalizePath(fsPath));
}
deleteByModuleId(modulePath) {
return super.delete(modulePath);
}
delete(fsPath) {
return this.deleteByModuleId(this.normalizePath(fsPath));
}
invalidateModule(mod) {
var _a, _b;
delete mod.evaluated;
delete mod.resolving;
delete mod.promise;
delete mod.exports;
(_a = mod.importers) == null ? void 0 : _a.clear();
(_b = mod.imports) == null ? void 0 : _b.clear();
return true;
}
/**
* Invalidate modules that dependent on the given modules, up to the main entry
*/
invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id))
continue;
invalidated.add(id);
const mod = super.get(id);
if (mod == null ? void 0 : mod.importers)
this.invalidateDepTree(mod.importers, invalidated);
super.delete(id);
}
return invalidated;
}
/**
* Invalidate dependency modules of the given modules, down to the bottom-level dependencies
*/
invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id))
continue;
invalidated.add(id);
const subIds = Array.from(super.entries()).filter(([, mod]) => {
var _a;
return (_a = mod.importers) == null ? void 0 : _a.has(id);
}).map(([key]) => key);
subIds.length && this.invalidateSubDepTree(subIds, invalidated);
super.delete(id);
}
return invalidated;
}
/**
* Return parsed source map based on inlined source map of the module
*/
getSourceMap(id) {
const cache = this.get(id);
if (cache.map)
return cache.map;
const map = cache.code && extractSourceMap(cache.code);
if (map) {
cache.map = map;
return map;
}
return null;
}
}
class ViteNodeRunner {
constructor(options) {
this.options = options;
this.root = options.root ?? process.cwd();
this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
}
root;
debug;
/**
* Holds the cache of modules
* Keys of the map are filepaths, or plain package names
*/
moduleCache;
async executeFile(file) {
const url = `/@fs/${slash(resolve(file))}`;
return await this.cachedRequest(url, url, []);
}
async executeId(rawId) {
const [id, url] = await this.resolveUrl(rawId);
return await this.cachedRequest(id, url, []);
}
/** @internal */
async cachedRequest(id, fsPath, callstack) {
const importee = callstack[callstack.length - 1];
const mod = this.moduleCache.get(fsPath);
const { imports, importers } = mod;
if (importee)
importers.add(importee);
const getStack = () => `stack:
${[...callstack, fsPath].reverse().map((p) => ` - ${p}`).join("\n")}`;
if (callstack.includes(fsPath) || Array.from(imports.values()).some((i) => importers.has(i))) {
if (mod.exports)
return mod.exports;
}
let debugTimer;
if (this.debug)
debugTimer = setTimeout(() => console.warn(`[vite-node] module ${fsPath} takes over 2s to load.
${getStack()}`), 2e3);
try {
if (mod.promise)
return await mod.promise;
const promise = this.directRequest(id, fsPath, callstack);
Object.assign(mod, { promise, evaluated: false });
return await promise;
} finally {
mod.evaluated = true;
if (debugTimer)
clearTimeout(debugTimer);
}
}
shouldResolveId(id, _importee) {
return !isInternalRequest(id) && !isNodeBuiltin(id) && !id.startsWith("data:");
}
async _resolveUrl(id, importer) {
var _a, _b;
const dep = normalizeRequestId(id, this.options.base);
if (!this.shouldResolveId(dep))
return [dep, dep];
const { path, exists } = toFilePath(dep, this.root);
if (!this.options.resolveId || exists)
return [dep, path];
const resolved = await this.options.resolveId(dep, importer);
if ((_b = (_a = resolved == null ? void 0 : resolved.meta) == null ? void 0 : _a["vite:alias"]) == null ? void 0 : _b.noResolved) {
const error = new Error(
`Cannot find module '${id}'${importer ? ` imported from '${importer}'` : ""}.
- If you rely on tsconfig.json's "paths" to resolve modules, please install "vite-tsconfig-paths" plugin to handle module resolution.
- Make sure you don't have relative aliases in your Vitest config. Use absolute paths instead. Read more: https://vitest.dev/guide/common-errors`
);
Object.defineProperty(error, "code", { value: "ERR_MODULE_NOT_FOUND", enumerable: true });
Object.defineProperty(error, Symbol.for("vitest.error.not_found.data"), { value: { id: dep, importer }, enumerable: false });
throw error;
}
const resolvedId = resolved ? normalizeRequestId(resolved.id, this.options.base) : dep;
return [resolvedId, resolvedId];
}
async resolveUrl(id, importee) {
const resolveKey = `resolve:${id}`;
this.moduleCache.setByModuleId(resolveKey, { resolving: true });
try {
return await this._resolveUrl(id, importee);
} finally {
this.moduleCache.deleteByModuleId(resolveKey);
}
}
/** @internal */
async dependencyRequest(id, fsPath, callstack) {
return await this.cachedRequest(id, fsPath, callstack);
}
/** @internal */
async directRequest(id, fsPath, _callstack) {
const moduleId = normalizeModuleId(fsPath);
const callstack = [..._callstack, moduleId];
const mod = this.moduleCache.getByModuleId(moduleId);
const request = async (dep) => {
const [id2, depFsPath] = await this.resolveUrl(String(dep), fsPath);
const depMod = this.moduleCache.getByModuleId(depFsPath);
depMod.importers.add(moduleId);
mod.imports.add(depFsPath);
return this.dependencyRequest(id2, depFsPath, callstack);
};
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
if (id in requestStubs)
return requestStubs[id];
let { code: transformed, externalize } = await this.options.fetchModule(id);
if (externalize) {
debugNative(externalize);
const exports2 = await this.interopedImport(externalize);
mod.exports = exports2;
return exports2;
}
if (transformed == null)
throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
const { Object: Object2, Reflect: Reflect2, Symbol: Symbol2 } = this.getContextPrimitives();
const modulePath = cleanUrl(moduleId);
const href = pathToFileURL(modulePath).href;
const __filename = fileURLToPath(href);
const __dirname = dirname(__filename);
const meta = {
url: href,
env,
filename: __filename,
dirname: __dirname
};
const exports = Object2.create(null);
Object2.defineProperty(exports, Symbol2.toStringTag, {
value: "Module",
enumerable: false,
configurable: false
});
const SYMBOL_NOT_DEFINED = Symbol2("not defined");
let moduleExports = SYMBOL_NOT_DEFINED;
const cjsExports = new Proxy(exports, {
get: (target, p, receiver) => {
if (Reflect2.has(target, p))
return Reflect2.get(target, p, receiver);
return Reflect2.get(Object2.prototype, p, receiver);
},
getPrototypeOf: () => Object2.prototype,
set: (_, p, value) => {
if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) {
exportAll(cjsExports, value);
exports.default = value;
return true;
}
if (!Reflect2.has(exports, "default"))
exports.default = {};
if (moduleExports !== SYMBOL_NOT_DEFINED && isPrimitive(moduleExports)) {
defineExport(exports, p, () => void 0);
return true;
}
if (!isPrimitive(exports.default))
exports.default[p] = value;
if (p !== "default")
defineExport(exports, p, () => value);
return true;
}
});
Object2.assign(mod, { code: transformed, exports });
const moduleProxy = {
set exports(value) {
exportAll(cjsExports, value);
exports.default = value;
moduleExports = value;
},
get exports() {
return cjsExports;
}
};
let hotContext;
if (this.options.createHotContext) {
Object2.defineProperty(meta, "hot", {
enumerable: true,
get: () => {
var _a, _b;
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, moduleId));
return hotContext;
},
set: (value) => {
hotContext = value;
}
});
}
const context = this.prepareContext({
// esm transformed by Vite
__vite_ssr_import__: request,
__vite_ssr_dynamic_import__: request,
__vite_ssr_exports__: exports,
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
__vite_ssr_import_meta__: meta,
// cjs compact
require: createRequire(href),
exports: cjsExports,
module: moduleProxy,
__filename,
__dirname
});
debugExecute(__filename);
if (transformed[0] === "#")
transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
await this.runModule(context, transformed);
return exports;
}
getContextPrimitives() {
return { Object, Reflect, Symbol };
}
async 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.runInThisContext(code, options);
await fn(...Object.values(context));
}
prepareContext(context) {
return context;
}
/**
* Define if a module should be interop-ed
* This function mostly for the ability to override by subclass
*/
shouldInterop(path, mod) {
if (this.options.interopDefault === false)
return false;
return !path.endsWith(".mjs") && "default" in mod;
}
importExternalModule(path) {
return import(path);
}
/**
* Import a module and interop it
*/
async interopedImport(path) {
const importedModule = await this.importExternalModule(path);
if (!this.shouldInterop(path, importedModule))
return importedModule;
const { mod, defaultExport } = interopModule(importedModule);
return new Proxy(mod, {
get(mod2, prop) {
if (prop === "default")
return defaultExport;
return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]);
},
has(mod2, prop) {
if (prop === "default")
return defaultExport !== void 0;
return prop in mod2 || defaultExport && prop in defaultExport;
},
getOwnPropertyDescriptor(mod2, prop) {
const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop);
if (descriptor)
return descriptor;
if (prop === "default" && defaultExport !== void 0) {
return {
value: defaultExport,
enumerable: true,
configurable: true
};
}
}
});
}
}
function interopModule(mod) {
if (isPrimitive(mod)) {
return {
mod: { default: mod },
defaultExport: mod
};
}
let defaultExport = "default" in mod ? mod.default : mod;
if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
mod = defaultExport;
if ("default" in defaultExport)
defaultExport = defaultExport.default;
}
return { mod, defaultExport };
}
function defineExport(exports, key, value) {
Object.defineProperty(exports, key, {
enumerable: true,
configurable: true,
get: value
});
}
function exportAll(exports, sourceModule) {
if (exports === sourceModule)
return;
if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)
return;
for (const key in sourceModule) {
if (key !== "default") {
try {
defineExport(exports, key, () => sourceModule[key]);
} catch (_err) {
}
}
}
}
export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner };

View File

@ -0,0 +1,57 @@
export { B as BaseSequencer, b as VitestPackageInstaller, V as VitestPlugin, a as createMethodsRPC, c as createVitest, r as registerConsoleShortcuts, s as startVitest } from './vendor/node.Zme77R4t.js';
import 'pathe';
import 'vite';
import 'node:path';
import 'node:url';
import 'node:process';
import 'node:fs';
import './vendor/constants.i1PoEnhr.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import 'os';
import 'path';
import './vendor/index.xL8XjTLv.js';
import 'util';
import 'stream';
import 'events';
import 'fs';
import 'picocolors';
import 'vite-node/client';
import '@vitest/snapshot/manager';
import 'vite-node/server';
import './vendor/index.rJjbcrrp.js';
import 'std-env';
import '@vitest/runner/utils';
import '@vitest/utils';
import './vendor/global.CkGT_TMy.js';
import './vendor/coverage.E7sG1b3r.js';
import './path.js';
import 'node:v8';
import 'node:os';
import 'node:events';
import 'tinypool';
import './vendor/index.cAUulNDf.js';
import './vendor/base.QYERqzkH.js';
import 'node:worker_threads';
import 'node:fs/promises';
import 'node:perf_hooks';
import 'execa';
import '@vitest/utils/source-map';
import 'module';
import 'acorn-walk';
import './vendor/reporters.cA9x-5v-.js';
import './chunks/runtime-console.Iloo9fIt.js';
import 'node:stream';
import 'node:console';
import './vendor/date.Ns1pGd_X.js';
import './vendor/tasks.IknbGB2n.js';
import 'node:module';
import 'local-pkg';
import 'node:crypto';
import 'vite-node/utils';
import 'assert';
import 'magic-string';
import '@vitest/utils/ast';
import 'strip-literal';
import './vendor/environments.sU0TD7wX.js';
import 'node:readline';
import 'readline';

View File

@ -0,0 +1,83 @@
import { Comparer, Comparison, SortedReadonlyArray } from "./corePublic";
/**
* Iterates through `array` by index and performs the callback on each element of array until the callback
* returns a falsey value, then returns false.
* If no such value is found, the callback is applied to each element of array and `true` is returned.
*/
export declare function every<T>(array: readonly T[] | undefined, callback: (element: T, index: number) => boolean): boolean;
/** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
export declare function findIndex<T>(array: readonly T[] | undefined, predicate: (element: T, index: number) => boolean, startIndex?: number): number;
export declare function indexOfAnyCharCode(text: string, charCodes: readonly number[], start?: number): number;
export declare function map<T, U>(array: readonly T[], f: (x: T, i: number) => U): U[];
export declare function map<T, U>(array: readonly T[] | undefined, f: (x: T, i: number) => U): U[] | undefined;
/**
* Flattens an array containing a mix of array or non-array elements.
*
* @param array The array to flatten.
*/
export declare function flatten<T>(array: T[][] | readonly (T | readonly T[] | undefined)[]): T[];
/**
* Maps an array. If the mapped value is an array, it is spread into the result.
*
* @param array The array to map.
* @param mapfn The callback used to map the result into one or more values.
*/
export declare function flatMap<T, U>(array: readonly T[] | undefined, mapfn: (x: T, i: number) => U | readonly U[] | undefined): readonly U[];
export declare function some<T>(array: readonly T[] | undefined): array is readonly T[];
export declare function some<T>(array: readonly T[] | undefined, predicate: (value: T) => boolean): boolean;
/**
* Returns a new sorted array.
*/
export declare function sort<T>(array: readonly T[], comparer?: Comparer<T>): SortedReadonlyArray<T>;
/**
* Returns the last element of an array if non-empty, `undefined` otherwise.
*/
export declare function lastOrUndefined<T>(array: readonly T[] | undefined): T | undefined;
export declare function last<T>(array: readonly T[]): T;
/**
* Compare the equality of two strings using a case-sensitive ordinal comparison.
*
* Case-sensitive comparisons compare both strings one code-point at a time using the integer
* value of each code-point after applying `toUpperCase` to each string. We always map both
* strings to their upper-case form as some unicode characters do not properly round-trip to
* lowercase (such as `ẞ` (German sharp capital s)).
*/
export declare function equateStringsCaseInsensitive(a: string, b: string): boolean;
/**
* Compare the equality of two strings using a case-sensitive ordinal comparison.
*
* Case-sensitive comparisons compare both strings one code-point at a time using the
* integer value of each code-point.
*/
export declare function equateStringsCaseSensitive(a: string, b: string): boolean;
/**
* Compare two strings using a case-insensitive ordinal comparison.
*
* Ordinal comparisons are based on the difference between the unicode code points of both
* strings. Characters with multiple unicode representations are considered unequal. Ordinal
* comparisons provide predictable ordering, but place "a" after "B".
*
* Case-insensitive comparisons compare both strings one code-point at a time using the integer
* value of each code-point after applying `toUpperCase` to each string. We always map both
* strings to their upper-case form as some unicode characters do not properly round-trip to
* lowercase (such as `ẞ` (German sharp capital s)).
*/
declare function compareStringsCaseInsensitive(a: string, b: string): Comparison;
/**
* Compare two strings using a case-sensitive ordinal comparison.
*
* Ordinal comparisons are based on the difference between the unicode code points of both
* strings. Characters with multiple unicode representations are considered unequal. Ordinal
* comparisons provide predictable ordering, but place "a" after "B".
*
* Case-sensitive comparisons compare both strings one code-point at a time using the integer
* value of each code-point.
*/
export declare function compareStringsCaseSensitive(a: string | undefined, b: string | undefined): Comparison;
export declare function getStringComparer(ignoreCase?: boolean): typeof compareStringsCaseInsensitive;
export declare function endsWith(str: string, suffix: string): boolean;
export declare function stringContains(str: string, substring: string): boolean;
type GetCanonicalFileName = (fileName: string) => string;
export declare function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): GetCanonicalFileName;
export declare function startsWith(str: string, prefix: string): boolean;
export {};

View File

@ -0,0 +1 @@
{"version":3,"file":"ban-tslint-comment.js","sourceRoot":"","sources":["../../src/rules/ban-tslint-comment.ts"],"names":[],"mappings":";;AAAA,oDAA2D;AAE3D,kCAAqC;AAErC,eAAe;AACf,iHAAiH;AACjH,MAAM,oBAAoB,GACxB,2DAA2D,CAAC;AAE9D,MAAM,MAAM,GAAG,CACb,IAAY,EACZ,IAAkD,EAC1C,EAAE,CACV,IAAI,KAAK,uBAAe,CAAC,IAAI;IAC3B,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;IAC/B,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAE1C,kBAAe,IAAA,iBAAU,EAAC;IACxB,IAAI,EAAE,oBAAoB;IAC1B,IAAI,EAAE;QACJ,IAAI,EAAE,YAAY;QAClB,IAAI,EAAE;YACJ,WAAW,EAAE,2CAA2C;YACxD,WAAW,EAAE,WAAW;SACzB;QACD,QAAQ,EAAE;YACR,eAAe,EAAE,uCAAuC;SACzD;QACD,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,MAAM;KAChB;IACD,cAAc,EAAE,EAAE;IAClB,MAAM,EAAE,OAAO,CAAC,EAAE;QAChB,OAAO;YACL,OAAO;gBACL,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,cAAc,EAAE,CAAC;gBACrD,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;oBACnB,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;wBACvC,OAAO,CAAC,MAAM,CAAC;4BACb,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE;4BACvC,IAAI,EAAE,CAAC;4BACP,SAAS,EAAE,iBAAiB;4BAC5B,GAAG,CAAC,KAAK;gCACP,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC;oCACpD,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;oCAC3D,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI;iCACvB,CAAC,CAAC;gCACH,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC;oCAClD,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM;oCACxB,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI;iCACrB,CAAC,CAAC;gCACH,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,UAAU,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC;4BACvD,CAAC;yBACF,CAAC,CAAC;oBACL,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}

View File

@ -0,0 +1,15 @@
'use strict';
var $TypeError = require('es-errors/type');
var BigIntLeftShift = require('./leftShift');
// https://262.ecma-international.org/11.0/#sec-numeric-types-bigint-signedRightShift
module.exports = function BigIntSignedRightShift(x, y) {
if (typeof x !== 'bigint' || typeof y !== 'bigint') {
throw new $TypeError('Assertion failed: `x` and `y` arguments must be BigInts');
}
return BigIntLeftShift(x, -y);
};

View File

@ -0,0 +1,776 @@
'use strict';
const utilities = require('./preset-mini.UhMMbd34.cjs');
const ruleUtils = require('@unocss/rule-utils');
const core = require('@unocss/core');
const variantAria = {
name: "aria",
match(matcher, ctx) {
const variant = ruleUtils.variantGetParameter("aria-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
const aria = utilities.h.bracket(match) ?? ctx.theme.aria?.[match] ?? "";
if (aria) {
return {
matcher: rest,
selector: (s) => `${s}[aria-${aria}]`
};
}
}
}
};
function calcMaxWidthBySize(size) {
const value = size.match(/^-?[0-9]+\.?[0-9]*/)?.[0] || "";
const unit = size.slice(value.length);
if (unit === "px") {
const maxWidth = Number.parseFloat(value) - 0.1;
return Number.isNaN(maxWidth) ? size : `${maxWidth}${unit}`;
}
return `calc(${size} - 0.1px)`;
}
function variantBreakpoints() {
const regexCache = {};
return {
name: "breakpoints",
match(matcher, context) {
const variantEntries = (utilities.resolveBreakpoints(context) ?? []).map(({ point, size }, idx) => [point, size, idx]);
for (const [point, size, idx] of variantEntries) {
if (!regexCache[point])
regexCache[point] = new RegExp(`^((?:([al]t-|[<~]|max-))?${point}(?:${context.generator.config.separators.join("|")}))`);
const match = matcher.match(regexCache[point]);
if (!match)
continue;
const [, pre] = match;
const m = matcher.slice(pre.length);
if (m === "container")
continue;
const isLtPrefix = pre.startsWith("lt-") || pre.startsWith("<") || pre.startsWith("max-");
const isAtPrefix = pre.startsWith("at-") || pre.startsWith("~");
let order = 3e3;
if (isLtPrefix) {
order -= idx + 1;
return {
matcher: m,
handle: (input, next) => next({
...input,
parent: `${input.parent ? `${input.parent} $$ ` : ""}@media (max-width: ${calcMaxWidthBySize(size)})`,
parentOrder: order
})
};
}
order += idx + 1;
if (isAtPrefix && idx < variantEntries.length - 1) {
return {
matcher: m,
handle: (input, next) => next({
...input,
parent: `${input.parent ? `${input.parent} $$ ` : ""}@media (min-width: ${size}) and (max-width: ${calcMaxWidthBySize(variantEntries[idx + 1][1])})`,
parentOrder: order
})
};
}
return {
matcher: m,
handle: (input, next) => next({
...input,
parent: `${input.parent ? `${input.parent} $$ ` : ""}@media (min-width: ${size})`,
parentOrder: order
})
};
}
},
multiPass: true,
autocomplete: "(at-|lt-|max-|)$breakpoints:"
};
}
function scopeMatcher(name, combinator) {
return {
name: `combinator:${name}`,
match(matcher, ctx) {
if (!matcher.startsWith(name))
return;
const separators = ctx.generator.config.separators;
let body = ruleUtils.variantGetBracket(`${name}-`, matcher, separators);
if (!body) {
for (const separator of separators) {
if (matcher.startsWith(`${name}${separator}`)) {
body = ["", matcher.slice(name.length + separator.length)];
break;
}
}
if (!body)
return;
}
let bracketValue = utilities.h.bracket(body[0]) ?? "";
if (bracketValue === "")
bracketValue = "*";
return {
matcher: body[1],
selector: (s) => `${s}${combinator}${bracketValue}`
};
},
multiPass: true
};
}
const variantCombinators = [
scopeMatcher("all", " "),
scopeMatcher("children", ">"),
scopeMatcher("next", "+"),
scopeMatcher("sibling", "+"),
scopeMatcher("siblings", "~")
];
const variantContainerQuery = {
name: "@",
match(matcher, ctx) {
if (matcher.startsWith("@container"))
return;
const variant = ruleUtils.variantGetParameter("@", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest, label] = variant;
const unbracket = utilities.h.bracket(match);
let container;
if (unbracket) {
const minWidth = utilities.h.numberWithUnit(unbracket);
if (minWidth)
container = `(min-width: ${minWidth})`;
} else {
container = ctx.theme.containers?.[match] ?? "";
}
if (container) {
core.warnOnce("The container query variant is experimental and may not follow semver.");
let order = 1e3 + Object.keys(ctx.theme.containers ?? {}).indexOf(match);
if (label)
order += 1e3;
return {
matcher: rest,
handle: (input, next) => next({
...input,
parent: `${input.parent ? `${input.parent} $$ ` : ""}@container${label ? ` ${label} ` : " "}${container}`,
parentOrder: order
})
};
}
}
},
multiPass: true
};
function variantColorsMediaOrClass(options = {}) {
if (options?.dark === "class" || typeof options.dark === "object") {
const { dark = ".dark", light = ".light" } = typeof options.dark === "string" ? {} : options.dark;
return [
ruleUtils.variantMatcher("dark", (input) => ({ prefix: `${dark} $$ ${input.prefix}` })),
ruleUtils.variantMatcher("light", (input) => ({ prefix: `${light} $$ ${input.prefix}` }))
];
}
return [
ruleUtils.variantParentMatcher("dark", "@media (prefers-color-scheme: dark)"),
ruleUtils.variantParentMatcher("light", "@media (prefers-color-scheme: light)")
];
}
const variantDataAttribute = {
name: "data",
match(matcher, ctx) {
const variant = ruleUtils.variantGetParameter("data-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
const dataAttribute = utilities.h.bracket(match) ?? ctx.theme.data?.[match] ?? "";
if (dataAttribute) {
return {
matcher: rest,
selector: (s) => `${s}[data-${dataAttribute}]`
};
}
}
}
};
function taggedData(tagName) {
return {
name: `${tagName}-data`,
match(matcher, ctx) {
const variant = ruleUtils.variantGetParameter(`${tagName}-data-`, matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
const dataAttribute = utilities.h.bracket(match) ?? ctx.theme.data?.[match] ?? "";
if (dataAttribute) {
return {
matcher: `${tagName}-[[data-${dataAttribute}]]:${rest}`
};
}
}
}
};
}
const variantTaggedDataAttributes = [
taggedData("group"),
taggedData("peer"),
taggedData("parent"),
taggedData("previous")
];
const variantLanguageDirections = [
ruleUtils.variantMatcher("rtl", (input) => ({ prefix: `[dir="rtl"] $$ ${input.prefix}` })),
ruleUtils.variantMatcher("ltr", (input) => ({ prefix: `[dir="ltr"] $$ ${input.prefix}` }))
];
const variantSelector = {
name: "selector",
match(matcher, ctx) {
const variant = ruleUtils.variantGetBracket("selector-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
const selector = utilities.h.bracket(match);
if (selector) {
return {
matcher: rest,
selector: () => selector
};
}
}
}
};
const variantCssLayer = {
name: "layer",
match(matcher, ctx) {
const variant = ruleUtils.variantGetParameter("layer-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
const layer = utilities.h.bracket(match) ?? match;
if (layer) {
return {
matcher: rest,
handle: (input, next) => next({
...input,
parent: `${input.parent ? `${input.parent} $$ ` : ""}@layer ${layer}`
})
};
}
}
}
};
const variantInternalLayer = {
name: "uno-layer",
match(matcher, ctx) {
const variant = ruleUtils.variantGetParameter("uno-layer-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
const layer = utilities.h.bracket(match) ?? match;
if (layer) {
return {
matcher: rest,
layer
};
}
}
}
};
const variantScope = {
name: "scope",
match(matcher, ctx) {
const variant = ruleUtils.variantGetBracket("scope-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
const scope = utilities.h.bracket(match);
if (scope) {
return {
matcher: rest,
selector: (s) => `${scope} $$ ${s}`
};
}
}
}
};
const variantVariables = {
name: "variables",
match(matcher, ctx) {
if (!matcher.startsWith("["))
return;
const [match, rest] = ruleUtils.getBracket(matcher, "[", "]") ?? [];
if (!(match && rest))
return;
let newMatcher;
for (const separator of ctx.generator.config.separators) {
if (rest.startsWith(separator)) {
newMatcher = rest.slice(separator.length);
break;
}
}
if (newMatcher == null)
return;
const variant = utilities.h.bracket(match) ?? "";
const useParent = variant.startsWith("@");
if (!(useParent || variant.includes("&")))
return;
return {
matcher: newMatcher,
handle(input, next) {
const updates = useParent ? {
parent: `${input.parent ? `${input.parent} $$ ` : ""}${variant}`
} : {
selector: variant.replace(/&/g, input.selector)
};
return next({
...input,
...updates
});
}
};
},
multiPass: true
};
const anchoredNumberRE = /^-?[0-9.]+(?:[a-z]+|%)?$/;
const numberRE = /-?[0-9.]+(?:[a-z]+|%)?/;
const ignoreProps = [
/\b(opacity|color|flex|backdrop-filter|^filter|transform)\b/
];
function negateMathFunction(value) {
const match = value.match(utilities.cssMathFnRE);
if (match) {
const [fnBody, rest] = ruleUtils.getStringComponent(`(${match[2]})${match[3]}`, "(", ")", " ") ?? [];
if (fnBody)
return `calc(${match[1]}${fnBody} * -1)${rest ? ` ${rest}` : ""}`;
}
}
const negateFunctionBodyRE = /\b(hue-rotate)\s*(\(.*)/;
function negateFunctionBody(value) {
const match = value.match(negateFunctionBodyRE);
if (match) {
const [fnBody, rest] = ruleUtils.getStringComponent(match[2], "(", ")", " ") ?? [];
if (fnBody) {
const body = anchoredNumberRE.test(fnBody.slice(1, -1)) ? fnBody.replace(numberRE, (i) => i.startsWith("-") ? i.slice(1) : `-${i}`) : `(calc(${fnBody} * -1))`;
return `${match[1]}${body}${rest ? ` ${rest}` : ""}`;
}
}
}
const variantNegative = {
name: "negative",
match(matcher) {
if (!matcher.startsWith("-"))
return;
return {
matcher: matcher.slice(1),
body: (body) => {
if (body.find((v) => v[0] === utilities.CONTROL_MINI_NO_NEGATIVE))
return;
let changed = false;
body.forEach((v) => {
const value = v[1]?.toString();
if (!value || value === "0")
return;
if (ignoreProps.some((i) => i.test(v[0])))
return;
const negatedFn = negateMathFunction(value);
if (negatedFn) {
v[1] = negatedFn;
changed = true;
return;
}
const negatedBody = negateFunctionBody(value);
if (negatedBody) {
v[1] = negatedBody;
changed = true;
return;
}
if (anchoredNumberRE.test(value)) {
v[1] = value.replace(numberRE, (i) => i.startsWith("-") ? i.slice(1) : `-${i}`);
changed = true;
}
});
if (changed)
return body;
return [];
}
};
}
};
function variantImportant() {
let re;
return {
name: "important",
match(matcher, ctx) {
if (!re)
re = new RegExp(`^(important(?:${ctx.generator.config.separators.join("|")})|!)`);
let base;
const match = matcher.match(re);
if (match)
base = matcher.slice(match[0].length);
else if (matcher.endsWith("!"))
base = matcher.slice(0, -1);
if (base) {
return {
matcher: base,
body: (body) => {
body.forEach((v) => {
if (v[1])
v[1] += " !important";
});
return body;
}
};
}
}
};
}
const variantPrint = ruleUtils.variantParentMatcher("print", "@media print");
const variantCustomMedia = {
name: "media",
match(matcher, ctx) {
const variant = ruleUtils.variantGetParameter("media-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
let media = utilities.h.bracket(match) ?? "";
if (media === "")
media = ctx.theme.media?.[match] ?? "";
if (media) {
return {
matcher: rest,
handle: (input, next) => next({
...input,
parent: `${input.parent ? `${input.parent} $$ ` : ""}@media ${media}`
})
};
}
}
},
multiPass: true
};
const variantSupports = {
name: "supports",
match(matcher, ctx) {
const variant = ruleUtils.variantGetParameter("supports-", matcher, ctx.generator.config.separators);
if (variant) {
const [match, rest] = variant;
let supports = utilities.h.bracket(match) ?? "";
if (supports === "")
supports = ctx.theme.supports?.[match] ?? "";
if (supports) {
return {
matcher: rest,
handle: (input, next) => next({
...input,
parent: `${input.parent ? `${input.parent} $$ ` : ""}@supports ${supports}`
})
};
}
}
},
multiPass: true
};
const PseudoClasses = Object.fromEntries([
// pseudo elements part 1
["first-letter", "::first-letter"],
["first-line", "::first-line"],
// location
"any-link",
"link",
"visited",
"target",
["open", "[open]"],
// forms
"default",
"checked",
"indeterminate",
"placeholder-shown",
"autofill",
"optional",
"required",
"valid",
"invalid",
"user-valid",
"user-invalid",
"in-range",
"out-of-range",
"read-only",
"read-write",
// content
"empty",
// interactions
"focus-within",
"hover",
"focus",
"focus-visible",
"active",
"enabled",
"disabled",
// tree-structural
"root",
"empty",
["even-of-type", ":nth-of-type(even)"],
["even", ":nth-child(even)"],
["odd-of-type", ":nth-of-type(odd)"],
["odd", ":nth-child(odd)"],
"first-of-type",
["first", ":first-child"],
"last-of-type",
["last", ":last-child"],
"only-child",
"only-of-type",
// pseudo elements part 2
["backdrop-element", "::backdrop"],
["placeholder", "::placeholder"],
["before", "::before"],
["after", "::after"],
["selection", "::selection"],
["marker", "::marker"],
["file", "::file-selector-button"]
].map((key) => Array.isArray(key) ? key : [key, `:${key}`]));
const PseudoClassesKeys = Object.keys(PseudoClasses);
const PseudoClassesColon = Object.fromEntries([
["backdrop", "::backdrop"]
].map((key) => Array.isArray(key) ? key : [key, `:${key}`]));
const PseudoClassesColonKeys = Object.keys(PseudoClassesColon);
const PseudoClassFunctions = [
"not",
"is",
"where",
"has"
];
const PseudoClassesStr = Object.entries(PseudoClasses).filter(([, pseudo]) => !pseudo.startsWith("::")).map(([key]) => key).sort((a, b) => b.length - a.length).join("|");
const PseudoClassesColonStr = Object.entries(PseudoClassesColon).filter(([, pseudo]) => !pseudo.startsWith("::")).map(([key]) => key).sort((a, b) => b.length - a.length).join("|");
const PseudoClassFunctionsStr = PseudoClassFunctions.join("|");
function taggedPseudoClassMatcher(tag, parent, combinator) {
const rawRE = new RegExp(`^(${core.escapeRegExp(parent)}:)(\\S+)${core.escapeRegExp(combinator)}\\1`);
let splitRE;
let pseudoRE;
let pseudoColonRE;
let pseudoVarRE;
const matchBracket = (input) => {
const body = ruleUtils.variantGetBracket(`${tag}-`, input, []);
if (!body)
return;
const [match, rest] = body;
const bracketValue = utilities.h.bracket(match);
if (bracketValue == null)
return;
const label = rest.split(splitRE, 1)?.[0] ?? "";
const prefix = `${parent}${core.escapeSelector(label)}`;
return [
label,
input.slice(input.length - (rest.length - label.length - 1)),
bracketValue.includes("&") ? bracketValue.replace(/&/g, prefix) : `${prefix}${bracketValue}`
];
};
const matchPseudo = (input) => {
const match = input.match(pseudoRE) || input.match(pseudoColonRE);
if (!match)
return;
const [original, fn, pseudoKey] = match;
const label = match[3] ?? "";
let pseudo = PseudoClasses[pseudoKey] || PseudoClassesColon[pseudoKey] || `:${pseudoKey}`;
if (fn)
pseudo = `:${fn}(${pseudo})`;
return [
label,
input.slice(original.length),
`${parent}${core.escapeSelector(label)}${pseudo}`,
pseudoKey
];
};
const matchPseudoVar = (input) => {
const match = input.match(pseudoVarRE);
if (!match)
return;
const [original, fn, pseudoValue] = match;
const label = match[3] ?? "";
const pseudo = `:${fn}(${pseudoValue})`;
return [
label,
input.slice(original.length),
`${parent}${core.escapeSelector(label)}${pseudo}`
];
};
return {
name: `pseudo:${tag}`,
match(input, ctx) {
if (!(splitRE && pseudoRE && pseudoColonRE)) {
splitRE = new RegExp(`(?:${ctx.generator.config.separators.join("|")})`);
pseudoRE = new RegExp(`^${tag}-(?:(?:(${PseudoClassFunctionsStr})-)?(${PseudoClassesStr}))(?:(/\\w+))?(?:${ctx.generator.config.separators.join("|")})`);
pseudoColonRE = new RegExp(`^${tag}-(?:(?:(${PseudoClassFunctionsStr})-)?(${PseudoClassesColonStr}))(?:(/\\w+))?(?:${ctx.generator.config.separators.filter((x) => x !== "-").join("|")})`);
pseudoVarRE = new RegExp(`^${tag}-(?:(${PseudoClassFunctionsStr})-)?\\[(.+)\\](?:(/\\w+))?(?:${ctx.generator.config.separators.filter((x) => x !== "-").join("|")})`);
}
if (!input.startsWith(tag))
return;
const result = matchBracket(input) || matchPseudo(input) || matchPseudoVar(input);
if (!result)
return;
const [label, matcher, prefix, pseudoName = ""] = result;
if (label !== "")
core.warnOnce("The labeled variant is experimental and may not follow semver.");
return {
matcher,
handle: (input2, next) => next({
...input2,
prefix: `${prefix}${combinator}${input2.prefix}`.replace(rawRE, "$1$2:"),
sort: PseudoClassesKeys.indexOf(pseudoName) ?? PseudoClassesColonKeys.indexOf(pseudoName)
})
};
},
multiPass: true
};
}
const excludedPseudo = [
"::-webkit-resizer",
"::-webkit-scrollbar",
"::-webkit-scrollbar-button",
"::-webkit-scrollbar-corner",
"::-webkit-scrollbar-thumb",
"::-webkit-scrollbar-track",
"::-webkit-scrollbar-track-piece",
"::file-selector-button"
];
const PseudoClassesAndElementsStr = Object.entries(PseudoClasses).map(([key]) => key).sort((a, b) => b.length - a.length).join("|");
const PseudoClassesAndElementsColonStr = Object.entries(PseudoClassesColon).map(([key]) => key).sort((a, b) => b.length - a.length).join("|");
function variantPseudoClassesAndElements() {
let PseudoClassesAndElementsRE;
let PseudoClassesAndElementsColonRE;
return {
name: "pseudo",
match(input, ctx) {
if (!(PseudoClassesAndElementsRE && PseudoClassesAndElementsRE)) {
PseudoClassesAndElementsRE = new RegExp(`^(${PseudoClassesAndElementsStr})(?:${ctx.generator.config.separators.join("|")})`);
PseudoClassesAndElementsColonRE = new RegExp(`^(${PseudoClassesAndElementsColonStr})(?:${ctx.generator.config.separators.filter((x) => x !== "-").join("|")})`);
}
const match = input.match(PseudoClassesAndElementsRE) || input.match(PseudoClassesAndElementsColonRE);
if (match) {
const pseudo = PseudoClasses[match[1]] || PseudoClassesColon[match[1]] || `:${match[1]}`;
let index = PseudoClassesKeys.indexOf(match[1]);
if (index === -1)
index = PseudoClassesColonKeys.indexOf(match[1]);
if (index === -1)
index = void 0;
return {
matcher: input.slice(match[0].length),
handle: (input2, next) => {
const selectors = pseudo.startsWith("::") && !excludedPseudo.includes(pseudo) ? {
pseudo: `${input2.pseudo}${pseudo}`
} : {
selector: `${input2.selector}${pseudo}`
};
return next({
...input2,
...selectors,
sort: index,
noMerge: true
});
}
};
}
},
multiPass: true,
autocomplete: `(${PseudoClassesAndElementsStr}|${PseudoClassesAndElementsColonStr}):`
};
}
function variantPseudoClassFunctions() {
let PseudoClassFunctionsRE;
let PseudoClassColonFunctionsRE;
let PseudoClassVarFunctionRE;
return {
match(input, ctx) {
if (!(PseudoClassFunctionsRE && PseudoClassColonFunctionsRE)) {
PseudoClassFunctionsRE = new RegExp(`^(${PseudoClassFunctionsStr})-(${PseudoClassesStr})(?:${ctx.generator.config.separators.join("|")})`);
PseudoClassColonFunctionsRE = new RegExp(`^(${PseudoClassFunctionsStr})-(${PseudoClassesColonStr})(?:${ctx.generator.config.separators.filter((x) => x !== "-").join("|")})`);
PseudoClassVarFunctionRE = new RegExp(`^(${PseudoClassFunctionsStr})-(\\[.+\\])(?:${ctx.generator.config.separators.filter((x) => x !== "-").join("|")})`);
}
const match = input.match(PseudoClassFunctionsRE) || input.match(PseudoClassColonFunctionsRE) || input.match(PseudoClassVarFunctionRE);
if (match) {
const fn = match[1];
const fnVal = ruleUtils.getBracket(match[2], "[", "]");
const pseudo = fnVal ? utilities.h.bracket(match[2]) : PseudoClasses[match[2]] || PseudoClassesColon[match[2]] || `:${match[2]}`;
return {
matcher: input.slice(match[0].length),
selector: (s) => `${s}:${fn}(${pseudo})`
};
}
},
multiPass: true,
autocomplete: `(${PseudoClassFunctionsStr})-(${PseudoClassesStr}|${PseudoClassesColonStr}):`
};
}
function variantTaggedPseudoClasses(options = {}) {
const attributify = !!options?.attributifyPseudo;
let firstPrefix = options?.prefix ?? "";
firstPrefix = (Array.isArray(firstPrefix) ? firstPrefix : [firstPrefix]).filter(Boolean)[0] ?? "";
const tagWithPrefix = (tag, combinator) => taggedPseudoClassMatcher(tag, attributify ? `[${firstPrefix}${tag}=""]` : `.${firstPrefix}${tag}`, combinator);
return [
tagWithPrefix("group", " "),
tagWithPrefix("peer", "~"),
tagWithPrefix("parent", ">"),
tagWithPrefix("previous", "+")
];
}
const PartClassesRE = /(part-\[(.+)]:)(.+)/;
const variantPartClasses = {
match(input) {
const match = input.match(PartClassesRE);
if (match) {
const part = `part(${match[2]})`;
return {
matcher: input.slice(match[1].length),
selector: (s) => `${s}::${part}`
};
}
},
multiPass: true
};
function variants(options) {
return [
variantAria,
variantDataAttribute,
variantCssLayer,
variantSelector,
variantInternalLayer,
variantNegative,
variantImportant(),
variantSupports,
variantPrint,
variantCustomMedia,
variantBreakpoints(),
...variantCombinators,
variantPseudoClassesAndElements(),
variantPseudoClassFunctions(),
...variantTaggedPseudoClasses(options),
variantPartClasses,
...variantColorsMediaOrClass(options),
...variantLanguageDirections,
variantScope,
variantContainerQuery,
variantVariables,
...variantTaggedDataAttributes
];
}
exports.calcMaxWidthBySize = calcMaxWidthBySize;
exports.variantAria = variantAria;
exports.variantBreakpoints = variantBreakpoints;
exports.variantColorsMediaOrClass = variantColorsMediaOrClass;
exports.variantCombinators = variantCombinators;
exports.variantContainerQuery = variantContainerQuery;
exports.variantCssLayer = variantCssLayer;
exports.variantCustomMedia = variantCustomMedia;
exports.variantDataAttribute = variantDataAttribute;
exports.variantImportant = variantImportant;
exports.variantInternalLayer = variantInternalLayer;
exports.variantLanguageDirections = variantLanguageDirections;
exports.variantNegative = variantNegative;
exports.variantPartClasses = variantPartClasses;
exports.variantPrint = variantPrint;
exports.variantPseudoClassFunctions = variantPseudoClassFunctions;
exports.variantPseudoClassesAndElements = variantPseudoClassesAndElements;
exports.variantScope = variantScope;
exports.variantSelector = variantSelector;
exports.variantSupports = variantSupports;
exports.variantTaggedDataAttributes = variantTaggedDataAttributes;
exports.variantTaggedPseudoClasses = variantTaggedPseudoClasses;
exports.variantVariables = variantVariables;
exports.variants = variants;

View File

@ -0,0 +1,70 @@
{
"name": "@typescript-eslint/scope-manager",
"version": "7.0.1",
"description": "TypeScript scope analyser for ESLint",
"files": [
"dist",
"package.json",
"README.md",
"LICENSE"
],
"type": "commonjs",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"engines": {
"node": "^16.0.0 || >=18.0.0"
},
"repository": {
"type": "git",
"url": "https://github.com/typescript-eslint/typescript-eslint.git",
"directory": "packages/scope-manager"
},
"bugs": {
"url": "https://github.com/typescript-eslint/typescript-eslint/issues"
},
"license": "MIT",
"keywords": [
"eslint",
"typescript",
"estree"
],
"scripts": {
"build": "npx nx build",
"clean": "npx nx clean",
"clean-fixtures": "npx nx clean-fixtures",
"format": "prettier --write \"./**/*.{ts,mts,cts,tsx,js,mjs,cjs,jsx,json,md,css}\" --ignore-path ../../.prettierignore",
"generate-lib": "npx nx generate-lib",
"lint": "npx nx lint",
"test": "npx nx test --code-coverage",
"typecheck": "npx nx typecheck"
},
"dependencies": {
"@typescript-eslint/types": "7.0.1",
"@typescript-eslint/visitor-keys": "7.0.1"
},
"devDependencies": {
"@types/glob": "*",
"@typescript-eslint/typescript-estree": "7.0.1",
"glob": "*",
"jest-specific-snapshot": "*",
"make-dir": "*",
"pretty-format": "*",
"typescript": "*"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"typesVersions": {
"<4.7": {
"*": [
"_ts4.3/*"
]
}
}
}

View File

@ -0,0 +1,6 @@
import type * as vscode from '@volar/language-service';
import type * as ts from 'typescript';
import type { SharedContext } from '../types';
export declare function register(ctx: SharedContext): (uri: string, position: vscode.Position, newName: string) => Promise<vscode.WorkspaceEdit | undefined>;
export declare function fileTextChangesToWorkspaceEdit(changes: readonly ts.FileTextChanges[], ctx: SharedContext): vscode.WorkspaceEdit;
//# sourceMappingURL=rename.d.ts.map

View File

@ -0,0 +1,6 @@
import type { FormattingOptions } from '@volar/language-service';
import type * as ts from 'typescript';
import type { TextDocument } from 'vscode-languageserver-textdocument';
import type { SharedContext } from '../types';
export declare function getFormatCodeSettings(ctx: SharedContext, document: TextDocument, options?: FormattingOptions): Promise<ts.FormatCodeSettings>;
//# sourceMappingURL=getFormatCodeSettings.d.ts.map

View File

@ -0,0 +1,139 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.searchExternalFiles = exports.decorateLanguageServiceHost = void 0;
const language_core_1 = require("@volar/language-core");
const resolveModuleName_1 = require("../resolveModuleName");
function decorateLanguageServiceHost(virtualFiles, languageServiceHost, ts) {
let extraProjectVersion = 0;
const { languagePlugins } = virtualFiles;
const exts = languagePlugins
.map(plugin => plugin.typescript?.extraFileExtensions.map(ext => '.' + ext.extension) ?? [])
.flat();
const scripts = new Map();
const readDirectory = languageServiceHost.readDirectory?.bind(languageServiceHost);
const resolveModuleNameLiterals = languageServiceHost.resolveModuleNameLiterals?.bind(languageServiceHost);
const resolveModuleNames = languageServiceHost.resolveModuleNames?.bind(languageServiceHost);
const getProjectVersion = languageServiceHost.getProjectVersion?.bind(languageServiceHost);
const getScriptSnapshot = languageServiceHost.getScriptSnapshot.bind(languageServiceHost);
const getScriptKind = languageServiceHost.getScriptKind?.bind(languageServiceHost);
// path completion
if (readDirectory) {
languageServiceHost.readDirectory = (path, extensions, exclude, include, depth) => {
if (extensions) {
for (const ext of exts) {
if (!extensions.includes(ext)) {
extensions = [...extensions, ...ext];
}
}
}
return readDirectory(path, extensions, exclude, include, depth);
};
}
if (languagePlugins.some(language => language.typescript?.extraFileExtensions.length)) {
const resolveModuleName = (0, resolveModuleName_1.createResolveModuleName)(ts, languageServiceHost, languagePlugins, fileName => virtualFiles.get(fileName));
if (resolveModuleNameLiterals) {
languageServiceHost.resolveModuleNameLiterals = (moduleLiterals, containingFile, redirectedReference, options, ...rest) => {
return [
...resolveModuleNameLiterals(moduleLiterals.filter(name => !exts.some(ext => name.text.endsWith(ext))), containingFile, redirectedReference, options, ...rest),
...moduleLiterals
.filter(name => exts.some(ext => name.text.endsWith(ext)))
.map(name => resolveModuleName(name.text, containingFile, options, undefined, redirectedReference)),
];
};
}
if (resolveModuleNames) {
languageServiceHost.resolveModuleNames = (moduleNames, containingFile, reusedNames, redirectedReference, options, containingSourceFile) => {
return [
...resolveModuleNames(moduleNames.filter(name => !exts.some(ext => name.endsWith(ext))), containingFile, reusedNames, redirectedReference, options, containingSourceFile),
...moduleNames
.filter(name => exts.some(ext => name.endsWith(ext)))
.map(moduleName => resolveModuleName(moduleName, containingFile, options, undefined, redirectedReference).resolvedModule),
];
};
}
}
if (getProjectVersion) {
languageServiceHost.getProjectVersion = () => {
return getProjectVersion() + ':' + extraProjectVersion;
};
}
languageServiceHost.getScriptSnapshot = fileName => {
if (exts.some(ext => fileName.endsWith(ext))) {
updateScript(fileName);
return scripts.get(fileName)?.snapshot;
}
return getScriptSnapshot(fileName);
};
if (getScriptKind) {
languageServiceHost.getScriptKind = fileName => {
if (exts.some(ext => fileName.endsWith(ext))) {
updateScript(fileName);
const script = scripts.get(fileName);
if (script) {
return script.kind;
}
return ts.ScriptKind.Deferred;
}
return getScriptKind(fileName);
};
}
function updateScript(fileName) {
const version = languageServiceHost.getScriptVersion(fileName);
if (version !== scripts.get(fileName)?.version) {
let extension = '.ts';
let snapshotSnapshot;
let scriptKind = ts.ScriptKind.TS;
const snapshot = getScriptSnapshot(fileName);
if (snapshot) {
extraProjectVersion++;
const sourceFile = virtualFiles.set(fileName, (0, language_core_1.resolveCommonLanguageId)(fileName), snapshot);
if (sourceFile.generated) {
const text = snapshot.getText(0, snapshot.getLength());
let patchedText = text.split('\n').map(line => ' '.repeat(line.length)).join('\n');
const script = sourceFile.generated.languagePlugin.typescript?.getScript(sourceFile.generated.code);
if (script) {
extension = script.extension;
scriptKind = script.scriptKind;
patchedText += script.code.snapshot.getText(0, script.code.snapshot.getLength());
}
snapshotSnapshot = ts.ScriptSnapshot.fromString(patchedText);
if (sourceFile.generated.languagePlugin.typescript?.getExtraScripts) {
console.warn('getExtraScripts() is not available in this use case.');
}
}
}
else if (virtualFiles.get(fileName)) {
extraProjectVersion++;
virtualFiles.delete(fileName);
}
scripts.set(fileName, {
version,
extension,
snapshot: snapshotSnapshot,
kind: scriptKind,
});
}
return scripts.get(fileName);
}
}
exports.decorateLanguageServiceHost = decorateLanguageServiceHost;
function searchExternalFiles(ts, project, exts) {
if (project.projectKind !== ts.server.ProjectKind.Configured) {
return [];
}
const configFile = project.getProjectName();
const config = ts.readJsonConfigFile(configFile, project.readFile.bind(project));
const parseHost = {
useCaseSensitiveFileNames: project.useCaseSensitiveFileNames(),
fileExists: project.fileExists.bind(project),
readFile: project.readFile.bind(project),
readDirectory: (...args) => {
args[1] = exts;
return project.readDirectory(...args);
},
};
const parsed = ts.parseJsonSourceFileConfigFileContent(config, parseHost, project.getCurrentDirectory());
return parsed.fileNames;
}
exports.searchExternalFiles = searchExternalFiles;
//# sourceMappingURL=decorateLanguageServiceHost.js.map

View File

@ -0,0 +1 @@
{"files":{"LICENSE":{"checkedAt":1707939899490,"integrity":"sha512-e6Azp98T3IIh9uy4NT357Iu8c0dWTrVyQAKq389D3dnKyCEDwFK6e48wfzxsS4H7m3M2HK9BEAXSnmzdHmCNWQ==","mode":420,"size":1067},"lib/index.js":{"checkedAt":1707939899490,"integrity":"sha512-dO9pDeUw/xQGz3cbtYfyvE/L2pVvA4fupgmEcjRsnJ7RhBHZCp2TO7iMyGgLzNH6HMqjkl+VjjvzPLMYYqRcGg==","mode":420,"size":85190},"package.json":{"checkedAt":1707939899490,"integrity":"sha512-W/pjKMT5/6v0CoHDIHsQyilu5FvuqEA/HT/NNwpEA7IuwPkBzU45hJcdcieYNHwC7UDwhbNVefUBr0N6Dmt+eg==","mode":420,"size":3966},"README.md":{"checkedAt":1707939899490,"integrity":"sha512-fJaIr5hWbni+kiq3HKquSIT4KkoIuANjI2D/k3WPM925vn65Ktx1uJTN4HHcM36pvusDOdckwbCU8FWuDlJZfg==","mode":420,"size":7897},"lib/index.mjs":{"checkedAt":1707939899491,"integrity":"sha512-tqMQQHfri4vtPETzibwOvh9AZwZrcOfz/VKNmQD+gnI3WiV6Y8AwKRLXMNNDPMKAJsDWAm4gEKjr54XKCMQD6g==","mode":420,"size":83020},"lib/index.d.mts":{"checkedAt":1707939899491,"integrity":"sha512-7VZvh1gfLeHRkn9wGszdIuZlXf/od+uSolg4tzJUhYIpVH3oefiEj2i0i1LP891f8OBJqusahKrcoulUuXoLhA==","mode":420,"size":12610},"lib/index.d.ts":{"checkedAt":1707939899491,"integrity":"sha512-7VZvh1gfLeHRkn9wGszdIuZlXf/od+uSolg4tzJUhYIpVH3oefiEj2i0i1LP891f8OBJqusahKrcoulUuXoLhA==","mode":420,"size":12610}}}

View File

@ -0,0 +1,140 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'space-before-function-paren',
meta: {
deprecated: true,
replacedBy: ['@stylistic/ts/space-before-function-paren'],
type: 'layout',
docs: {
description: 'Enforce consistent spacing before function parenthesis',
extendsBaseRule: true,
},
fixable: 'whitespace',
schema: [
{
oneOf: [
{
type: 'string',
enum: ['always', 'never'],
},
{
type: 'object',
properties: {
anonymous: {
type: 'string',
enum: ['always', 'never', 'ignore'],
},
named: {
type: 'string',
enum: ['always', 'never', 'ignore'],
},
asyncArrow: {
type: 'string',
enum: ['always', 'never', 'ignore'],
},
},
additionalProperties: false,
},
],
},
],
messages: {
unexpected: 'Unexpected space before function parentheses.',
missing: 'Missing space before function parentheses.',
},
},
defaultOptions: ['always'],
create(context, [firstOption]) {
const baseConfig = typeof firstOption === 'string' ? firstOption : 'always';
const overrideConfig = typeof firstOption === 'object' ? firstOption : {};
/**
* Determines whether a function has a name.
* @param node The function node.
* @returns Whether the function has a name.
*/
function isNamedFunction(node) {
if (node.id != null) {
return true;
}
const parent = node.parent;
return (parent.type === utils_1.AST_NODE_TYPES.MethodDefinition ||
parent.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition ||
(parent.type === utils_1.AST_NODE_TYPES.Property &&
(parent.kind === 'get' || parent.kind === 'set' || parent.method)));
}
/**
* Gets the config for a given function
* @param node The function node
*/
function getConfigForFunction(node) {
if (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
// Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar
if (node.async &&
(0, util_1.isOpeningParenToken)(context.sourceCode.getFirstToken(node, { skip: 1 }))) {
return overrideConfig.asyncArrow ?? baseConfig;
}
}
else if (isNamedFunction(node)) {
return overrideConfig.named ?? baseConfig;
// `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}`
}
else if (!node.generator) {
return overrideConfig.anonymous ?? baseConfig;
}
return 'ignore';
}
/**
* Checks the parens of a function node
* @param node A function node
*/
function checkFunction(node) {
const functionConfig = getConfigForFunction(node);
if (functionConfig === 'ignore') {
return;
}
let leftToken;
let rightToken;
if (node.typeParameters) {
leftToken = context.sourceCode.getLastToken(node.typeParameters);
rightToken = context.sourceCode.getTokenAfter(leftToken);
}
else {
rightToken = context.sourceCode.getFirstToken(node, util_1.isOpeningParenToken);
leftToken = context.sourceCode.getTokenBefore(rightToken);
}
const hasSpacing = context.sourceCode.isSpaceBetween(leftToken, rightToken);
if (hasSpacing && functionConfig === 'never') {
context.report({
node,
loc: {
start: leftToken.loc.end,
end: rightToken.loc.start,
},
messageId: 'unexpected',
fix: fixer => fixer.removeRange([leftToken.range[1], rightToken.range[0]]),
});
}
else if (!hasSpacing &&
functionConfig === 'always' &&
(!node.typeParameters || node.id)) {
context.report({
node,
loc: rightToken.loc,
messageId: 'missing',
fix: fixer => fixer.insertTextAfter(leftToken, ' '),
});
}
}
return {
ArrowFunctionExpression: checkFunction,
FunctionDeclaration: checkFunction,
FunctionExpression: checkFunction,
TSEmptyBodyFunctionExpression: checkFunction,
TSDeclareFunction: checkFunction,
};
},
});
//# sourceMappingURL=space-before-function-paren.js.map

View File

@ -0,0 +1,16 @@
type TypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| BigInt64Array
| BigUint64Array;
declare function isTypedArray(value: unknown): value is TypedArray;
export = isTypedArray;

View File

@ -0,0 +1,42 @@
{
"name": "@unocss/extractor-arbitrary-variants",
"version": "0.58.5",
"description": "Extractor arbitrary variants for utilities",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/unocss/unocss/tree/main/packages/extractor-arbitrary-variants#readme",
"repository": {
"type": "git",
"url": "https://github.com/unocss/unocss",
"directory": "packages/extractor-arbitrary-variants"
},
"bugs": {
"url": "https://github.com/unocss/unocss/issues"
},
"keywords": [
"unocss",
"unocss-extractor"
],
"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"
],
"dependencies": {
"@unocss/core": "0.58.5"
},
"scripts": {
"build": "unbuild",
"stub": "unbuild --stub"
}
}

View File

@ -0,0 +1,179 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'method-signature-style',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce using a particular method signature syntax',
},
fixable: 'code',
messages: {
errorMethod: 'Shorthand method signature is forbidden. Use a function property instead.',
errorProperty: 'Function property signature is forbidden. Use a method shorthand instead.',
},
schema: [
{
type: 'string',
enum: ['property', 'method'],
},
],
},
defaultOptions: ['property'],
create(context, [mode]) {
function getMethodKey(node) {
let key = context.sourceCode.getText(node.key);
if (node.computed) {
key = `[${key}]`;
}
if (node.optional) {
key = `${key}?`;
}
if (node.readonly) {
key = `readonly ${key}`;
}
return key;
}
function getMethodParams(node) {
let params = '()';
if (node.params.length > 0) {
const openingParen = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(node.params[0], util_1.isOpeningParenToken), 'Missing opening paren before first parameter');
const closingParen = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.params[node.params.length - 1], util_1.isClosingParenToken), 'Missing closing paren after last parameter');
params = context.sourceCode.text.substring(openingParen.range[0], closingParen.range[1]);
}
if (node.typeParameters != null) {
const typeParams = context.sourceCode.getText(node.typeParameters);
params = `${typeParams}${params}`;
}
return params;
}
function getMethodReturnType(node) {
return node.returnType == null
? // if the method has no return type, it implicitly has an `any` return type
// we just make it explicit here so we can do the fix
'any'
: context.sourceCode.getText(node.returnType.typeAnnotation);
}
function getDelimiter(node) {
const lastToken = context.sourceCode.getLastToken(node);
if (lastToken &&
((0, util_1.isSemicolonToken)(lastToken) || (0, util_1.isCommaToken)(lastToken))) {
return lastToken.value;
}
return '';
}
function isNodeParentModuleDeclaration(node) {
if (!node.parent) {
return false;
}
if (node.parent.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration) {
return true;
}
if (node.parent.type === utils_1.AST_NODE_TYPES.Program) {
return false;
}
return isNodeParentModuleDeclaration(node.parent);
}
return {
...(mode === 'property' && {
TSMethodSignature(methodNode) {
if (methodNode.kind !== 'method') {
return;
}
const parent = methodNode.parent;
const members = parent.type === utils_1.AST_NODE_TYPES.TSInterfaceBody
? parent.body
: parent.type === utils_1.AST_NODE_TYPES.TSTypeLiteral
? parent.members
: [];
const duplicatedKeyMethodNodes = members.filter((element) => element.type === utils_1.AST_NODE_TYPES.TSMethodSignature &&
element !== methodNode &&
getMethodKey(element) === getMethodKey(methodNode));
const isParentModule = isNodeParentModuleDeclaration(methodNode);
if (duplicatedKeyMethodNodes.length > 0) {
if (isParentModule) {
context.report({
node: methodNode,
messageId: 'errorMethod',
});
}
else {
context.report({
node: methodNode,
messageId: 'errorMethod',
*fix(fixer) {
const methodNodes = [
methodNode,
...duplicatedKeyMethodNodes,
].sort((a, b) => (a.range[0] < b.range[0] ? -1 : 1));
const typeString = methodNodes
.map(node => {
const params = getMethodParams(node);
const returnType = getMethodReturnType(node);
return `(${params} => ${returnType})`;
})
.join(' & ');
const key = getMethodKey(methodNode);
const delimiter = getDelimiter(methodNode);
yield fixer.replaceText(methodNode, `${key}: ${typeString}${delimiter}`);
for (const node of duplicatedKeyMethodNodes) {
const lastToken = context.sourceCode.getLastToken(node);
if (lastToken) {
const nextToken = context.sourceCode.getTokenAfter(lastToken);
if (nextToken) {
yield fixer.remove(node);
yield fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], '');
}
}
}
},
});
}
return;
}
if (isParentModule) {
context.report({
node: methodNode,
messageId: 'errorMethod',
});
}
else {
context.report({
node: methodNode,
messageId: 'errorMethod',
fix: fixer => {
const key = getMethodKey(methodNode);
const params = getMethodParams(methodNode);
const returnType = getMethodReturnType(methodNode);
const delimiter = getDelimiter(methodNode);
return fixer.replaceText(methodNode, `${key}: ${params} => ${returnType}${delimiter}`);
},
});
}
},
}),
...(mode === 'method' && {
TSPropertySignature(propertyNode) {
const typeNode = propertyNode.typeAnnotation?.typeAnnotation;
if (typeNode?.type !== utils_1.AST_NODE_TYPES.TSFunctionType) {
return;
}
context.report({
node: propertyNode,
messageId: 'errorProperty',
fix: fixer => {
const key = getMethodKey(propertyNode);
const params = getMethodParams(typeNode);
const returnType = getMethodReturnType(typeNode);
const delimiter = getDelimiter(propertyNode);
return fixer.replaceText(propertyNode, `${key}${params}: ${returnType}${delimiter}`);
},
});
},
}),
};
},
});
//# sourceMappingURL=method-signature-style.js.map

View File

@ -0,0 +1,112 @@
import { Path } from "./types";
/**
* Internally, we represent paths as strings with '/' as the directory separator.
* When we make system calls (eg: LanguageServiceHost.getDirectory()),
* we expect the host to correctly handle paths in our specified format.
*/
export declare const directorySeparator = "/";
/**
* Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
* like `c:`, `c:\` or `c:/`).
*/
export declare function isRootedDiskPath(path: string): boolean;
export declare function hasExtension(fileName: string): boolean;
export declare function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean;
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* // POSIX
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* // DOS
* getDirectoryPath("c:/path/to/file.ext") === "c:/path/to"
* getDirectoryPath("c:/path/to/") === "c:/path"
* getDirectoryPath("c:/") === "c:/"
* getDirectoryPath("c:") === "c:"
* // URL
* getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to"
* getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path"
* getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/"
* getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org"
* ```
*/
export declare function getDirectoryPath(path: Path): Path;
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* // POSIX
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* // DOS
* getDirectoryPath("c:/path/to/file.ext") === "c:/path/to"
* getDirectoryPath("c:/path/to/") === "c:/path"
* getDirectoryPath("c:/") === "c:/"
* getDirectoryPath("c:") === "c:"
* // URL
* getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to"
* getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path"
* getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/"
* getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org"
* getDirectoryPath("file://server/path/to/file.ext") === "file://server/path/to"
* getDirectoryPath("file://server/path/to") === "file://server/path"
* getDirectoryPath("file://server/") === "file://server/"
* getDirectoryPath("file://server") === "file://server"
* getDirectoryPath("file:///path/to/file.ext") === "file:///path/to"
* getDirectoryPath("file:///path/to") === "file:///path"
* getDirectoryPath("file:///") === "file:///"
* getDirectoryPath("file://") === "file://"
* ```
*/
export declare function getDirectoryPath(path: string): string;
/**
* Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
*
* ```ts
* // Non-rooted
* combinePaths("path", "to", "file.ext") === "path/to/file.ext"
* combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
* // POSIX
* combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
* combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
* // DOS
* combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
* combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
* // URL
* combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
* combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
* ```
*/
export declare function combinePaths(path: string, ...paths: (string | undefined)[]): string;
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*
* ```ts
* getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
* ```
*/
export declare function getNormalizedPathComponents(path: string, currentDirectory: string | undefined): string[];
export declare function normalizePath(path: string): string;
/**
* Removes a trailing directory separator from a path, if it does not already have one.
*
* ```ts
* removeTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext"
* removeTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext"
* ```
*/
export declare function removeTrailingDirectorySeparator(path: Path): Path;
export declare function removeTrailingDirectorySeparator(path: string): string;
/**
* Determines whether a `parent` path contains a `child` path using the provide case sensitivity.
*/
export declare function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean;
export declare function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;

View File

@ -0,0 +1 @@
{"files":{".eslintrc":{"checkedAt":1707939899760,"integrity":"sha512-EBDRW6cKPexAflK5TvXZbx9EvGejXIyoPbyjoNOLl5Echn8KK7Z7Gs0WknJhkWSuAIaaX8pLKKihPo6R+hPg1Q==","mode":420,"size":122},".nycrc":{"checkedAt":1707939899760,"integrity":"sha512-42sgwWzusJB1Dzhl78jX/Zg65Oi0HDDMOGXS/Uklv1kCYn4fHtRsD/JFPwdu+d40vome9XdUspzRWEQAcTGEeQ==","mode":420,"size":216},"LICENSE":{"checkedAt":1707939899760,"integrity":"sha512-zSWZlPMHqdrYcu0iKn0DZJ7EU8PHWsyOsYC+m2L4TRgwzvU+9Xsi8DCgqVoMt3xcoyvGCZp05dGObt+3xshLBw==","mode":420,"size":1071},"index.js":{"checkedAt":1707939899760,"integrity":"sha512-epWlABre69fe9LO6vIcr1IPTF+SLwaDfJEkuM4T6GR93pEVD1P4Rlc0dzUilfoKCDHNm1Xa+iD3fgIUW1kc4Mg==","mode":420,"size":387},"test/index.js":{"checkedAt":1707939899760,"integrity":"sha512-/ZDSNI7rWFZiwI0Qtfj+ZAliLzTdqkXYwc2Y+t5U3lxKMaHVucArl4ViQ2qLRZFJk23xAoFwM20UUt8iLP7NEQ==","mode":420,"size":878},"package.json":{"checkedAt":1707939899760,"integrity":"sha512-njmG3001EmKn2systC4vtgbF5ln7WsyDn+l1D1sFWQISqcTs+auln1IneE5/ptsf3PQzqTsnquR4uhsl/940dw==","mode":420,"size":2031},"CHANGELOG.md":{"checkedAt":1707939899760,"integrity":"sha512-famfo8cQuuZ3sW3hOGIkUi3hGmV7DnCYA7np24THJCJZc1sTynhV3KvYaf1ZP1I8CH3Y5pVjRbVaATkjx1pQog==","mode":420,"size":3108},"README.md":{"checkedAt":1707939899760,"integrity":"sha512-Tm2RKyZJrD1cQ1Kd3R97BY83jb/QCldnnVNO/enG1YfOiGGi+ua/g7nZ1rJG40aUH0jy8Bq0jNssYHfGFe4GWg==","mode":420,"size":1828},".github/FUNDING.yml":{"checkedAt":1707939899760,"integrity":"sha512-TGZqAhBMHbhTCfCT8T6ONDQvaV9qM11rdJSG7+4xFjQ8oF35q7fORDZJiS+OkzzLOXVEkImW4oQIf6WTo1He0w==","mode":420,"size":586}}}

View File

@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateMap = exports.clone = void 0;
const sourcemap_codec_1 = require("@jridgewell/sourcemap-codec");
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const base_1 = require("./base");
function clone(segments) {
const cloned = [];
for (const s of segments) {
if (typeof s === 'string') {
cloned.push(s);
}
else {
cloned.push([...s]);
}
}
return cloned;
}
exports.clone = clone;
function generateMap(segments, readSource) {
const cloned = clone(segments);
const mappings = [];
const sourceCode = new Map();
let newLineIndex = (0, base_1.toString)(cloned).indexOf('\n');
while (newLineIndex >= 0) {
onLine((0, base_1.overwrite)(cloned, [0, newLineIndex + 1]));
newLineIndex = (0, base_1.toString)(cloned).indexOf('\n');
}
onLine((0, base_1.overwrite)(cloned, [0, (0, base_1.getLength)(cloned)]));
return (0, sourcemap_codec_1.encode)(mappings);
function onLine(lineSegments) {
const lineMapping = [];
let currentColumn = 0;
let hasCodeMapping = false;
for (const s of lineSegments) {
if (typeof s === 'string') {
if (hasCodeMapping) {
hasCodeMapping = false;
// we don't break off last mapping for now
}
currentColumn += s.length;
}
else {
hasCodeMapping = true;
const source = s[1];
const sourceOffset = s[2][0];
if (!sourceCode.has(source)) {
const readed = readSource(source);
sourceCode.set(source, [readed[0], vscode_languageserver_textdocument_1.TextDocument.create('', '', 0, readed[1])]);
}
const [sourceIndex, document] = sourceCode.get(source);
const position = document.positionAt(sourceOffset);
lineMapping.push([
currentColumn,
sourceIndex,
position.line,
position.character,
]);
currentColumn += s[0].length;
}
}
mappings.push(lineMapping);
}
}
exports.generateMap = generateMap;
//# sourceMappingURL=map.js.map

View File

@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.register = void 0;
const featureWorkers_1 = require("../utils/featureWorkers");
const cancellation_1 = require("../utils/cancellation");
const language_core_1 = require("@volar/language-core");
function register(context) {
return (uri, position, lastChange, token = cancellation_1.NoneCancellationToken) => {
return (0, featureWorkers_1.languageFeatureWorker)(context, uri, () => ({ position, lastChange }), function* (map) {
for (const mappedPosition of map.getGeneratedPositions(position, language_core_1.isAutoInsertEnabled)) {
const range = map.getGeneratedRange(lastChange.range);
if (range) {
yield {
position: mappedPosition,
lastChange: {
text: lastChange.text,
range,
},
};
}
}
}, (service, document, args) => {
if (token.isCancellationRequested) {
return;
}
return service[1].provideAutoInsertionEdit?.(document, args.position, args.lastChange, token);
}, (item, map) => {
if (!map || typeof item === 'string') {
return item;
}
const range = map.getSourceRange(item.range, language_core_1.isAutoInsertEnabled);
if (range) {
item.range = range;
return item;
}
});
};
}
exports.register = register;
//# sourceMappingURL=provideAutoInsertionEdit.js.map

View File

@ -0,0 +1,249 @@
---
description: "Require explicit return and argument types on exported functions' and classes' public class methods."
---
> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/explicit-module-boundary-types** for documentation.
Explicit types for function return values and arguments makes it clear to any calling code what is the module boundary's input and output.
Adding explicit type annotations for those types can help improve code readability.
It can also improve TypeScript type checking performance on larger codebases.
## Examples
<!--tabs-->
### ❌ Incorrect
```ts
// Should indicate that no value is returned (void)
export function test() {
return;
}
// Should indicate that a string is returned
export var arrowFn = () => 'test';
// All arguments should be typed
export var arrowFn = (arg): string => `test ${arg}`;
export var arrowFn = (arg: any): string => `test ${arg}`;
export class Test {
// Should indicate that no value is returned (void)
method() {
return;
}
}
```
### ✅ Correct
```ts
// A function with no return value (void)
export function test(): void {
return;
}
// A return value of type string
export var arrowFn = (): string => 'test';
// All arguments should be typed
export var arrowFn = (arg: string): string => `test ${arg}`;
export var arrowFn = (arg: unknown): string => `test ${arg}`;
export class Test {
// A class method with no return value (void)
method(): void {
return;
}
}
// The function does not apply because it is not an exported function.
function test() {
return;
}
```
## Options
### Configuring in a mixed JS/TS codebase
If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.mjs`/`.cjs`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.mts`/`.cts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.mjs`/`.cjs`/`.jsx` files.
```jsonc
{
"rules": {
// disable the rule for all files
"@typescript-eslint/explicit-module-boundary-types": "off",
},
"overrides": [
{
// enable the rule specifically for TypeScript files
"files": ["*.ts", "*.mts", "*.cts", "*.tsx"],
"rules": {
"@typescript-eslint/explicit-module-boundary-types": "error",
},
},
],
}
```
### `allowArgumentsExplicitlyTypedAsAny`
Examples of code for this rule with `{ allowArgumentsExplicitlyTypedAsAny: false }`:
<!--tabs-->
#### ❌ Incorrect
```ts option='{ "allowArgumentsExplicitlyTypedAsAny": false }'
export const func = (value: any): number => value + 1;
```
#### ✅ Correct
```ts option='{ "allowArgumentsExplicitlyTypedAsAny": false }'
export const func = (value: number): number => value + 1;
```
### `allowDirectConstAssertionInArrowFunctions`
Examples of code for this rule with `{ allowDirectConstAssertionInArrowFunctions: false }`:
<!--tabs-->
#### ❌ Incorrect
```ts option='{ "allowArgumentsExplicitlyTypedAsAny": false }'
export const func = (value: number) => ({ type: 'X', value });
export const foo = () => ({
bar: true,
});
export const bar = () => 1;
```
#### ✅ Correct
```ts option='{ "allowArgumentsExplicitlyTypedAsAny": false }'
export const func = (value: number) => ({ type: 'X', value }) as const;
export const foo = () =>
({
bar: true,
}) as const;
export const bar = () => 1 as const;
```
### `allowedNames`
You may pass function/method names you would like this rule to ignore, like so:
```json
{
"@typescript-eslint/explicit-module-boundary-types": [
"error",
{
"allowedNames": ["ignoredFunctionName", "ignoredMethodName"]
}
]
}
```
### `allowHigherOrderFunctions`
Examples of code for this rule with `{ allowHigherOrderFunctions: false }`:
<!--tabs-->
#### ❌ Incorrect
```ts option='{ "allowHigherOrderFunctions": false }'
export const arrowFn = () => () => {};
export function fn() {
return function () {};
}
export function foo(outer: string) {
return function (inner: string) {};
}
```
#### ✅ Correct
```ts option='{ "allowHigherOrderFunctions": false }'
export const arrowFn = () => (): void => {};
export function fn() {
return function (): void {};
}
export function foo(outer: string) {
return function (inner: string): void {};
}
```
### `allowTypedFunctionExpressions`
Examples of code for this rule with `{ allowTypedFunctionExpressions: false }`:
<!--tabs-->
#### ❌ Incorrect
```ts option='{ "allowTypedFunctionExpressions": false }'
export let arrowFn = () => 'test';
export let funcExpr = function () {
return 'test';
};
export let objectProp = {
foo: () => 1,
};
export const foo = bar => {};
```
#### ✅ Correct
```ts option='{ "allowTypedFunctionExpressions": false }'
type FuncType = () => string;
export let arrowFn: FuncType = () => 'test';
export let funcExpr: FuncType = function () {
return 'test';
};
export let asTyped = (() => '') as () => string;
export let castTyped = <() => string>(() => '');
interface ObjectType {
foo(): number;
}
export let objectProp: ObjectType = {
foo: () => 1,
};
export let objectPropAs = {
foo: () => 1,
} as ObjectType;
export let objectPropCast = <ObjectType>{
foo: () => 1,
};
type FooType = (bar: string) => void;
export const foo: FooType = bar => {};
```
## When Not To Use It
If your project is not used by downstream consumers that are sensitive to API types, you can disable this rule.
## Further Reading
- TypeScript [Functions](https://www.typescriptlang.org/docs/handbook/functions.html#function-types)
## Related To
- [explicit-function-return-type](./explicit-function-return-type.md)

View File

@ -0,0 +1,107 @@
'use strict';
var test = require('tape');
var whichTypedArray = require('../');
var isCallable = require('is-callable');
var hasToStringTag = require('has-tostringtag/shams')();
var generators = require('make-generator-function')();
var arrows = require('make-arrow-function').list();
var forEach = require('for-each');
var typedArrayNames = [
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array',
'BigInt64Array',
'BigUint64Array'
];
test('not arrays', function (t) {
t.test('non-number/string primitives', function (st) {
// @ts-expect-error
st.equal(false, whichTypedArray(), 'undefined is not typed array');
st.equal(false, whichTypedArray(null), 'null is not typed array');
st.equal(false, whichTypedArray(false), 'false is not typed array');
st.equal(false, whichTypedArray(true), 'true is not typed array');
st.end();
});
t.equal(false, whichTypedArray({}), 'object is not typed array');
t.equal(false, whichTypedArray(/a/g), 'regex literal is not typed array');
t.equal(false, whichTypedArray(new RegExp('a', 'g')), 'regex object is not typed array');
t.equal(false, whichTypedArray(new Date()), 'new Date() is not typed array');
t.test('numbers', function (st) {
st.equal(false, whichTypedArray(42), 'number is not typed array');
st.equal(false, whichTypedArray(Object(42)), 'number object is not typed array');
st.equal(false, whichTypedArray(NaN), 'NaN is not typed array');
st.equal(false, whichTypedArray(Infinity), 'Infinity is not typed array');
st.end();
});
t.test('strings', function (st) {
st.equal(false, whichTypedArray('foo'), 'string primitive is not typed array');
st.equal(false, whichTypedArray(Object('foo')), 'string object is not typed array');
st.end();
});
t.end();
});
test('Functions', function (t) {
t.equal(false, whichTypedArray(function () {}), 'function is not typed array');
t.end();
});
test('Generators', { skip: generators.length === 0 }, function (t) {
forEach(generators, function (genFn) {
t.equal(false, whichTypedArray(genFn), 'generator function ' + genFn + ' is not typed array');
});
t.end();
});
test('Arrow functions', { skip: arrows.length === 0 }, function (t) {
forEach(arrows, function (arrowFn) {
t.equal(false, whichTypedArray(arrowFn), 'arrow function ' + arrowFn + ' is not typed array');
});
t.end();
});
test('@@toStringTag', { skip: !hasToStringTag }, function (t) {
forEach(typedArrayNames, function (typedArray) {
// @ts-expect-error TODO: fix
if (typeof global[typedArray] === 'function') {
// @ts-expect-error TODO: fix
var fakeTypedArray = [];
// @ts-expect-error TODO: fix
fakeTypedArray[Symbol.toStringTag] = typedArray;
// @ts-expect-error TODO: fix
t.equal(false, whichTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array');
} else {
t.comment('# SKIP ' + typedArray + ' is not supported');
}
});
t.end();
});
/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor | BigInt64ArrayConstructor | BigUint64ArrayConstructor} TypedArrayConstructor */
test('Typed Arrays', function (t) {
forEach(typedArrayNames, function (typedArray) {
// @ts-expect-error TODO: fix
/** @type {TypedArrayConstructor} */ var TypedArray = global[typedArray];
if (isCallable(TypedArray)) {
var arr = new TypedArray(10);
t.equal(whichTypedArray(arr), typedArray, 'new ' + typedArray + '(10) is typed array of type ' + typedArray);
} else {
t.comment('# SKIP ' + typedArray + ' is not supported');
}
});
t.end();
});

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAEA,wDAAgC;AAChC,0DAAkC;AAClC,0FAAgE;AAChE,sFAA6D;AAC7D,wEAAgD;AAChD,kGAAwE;AACxE,8DAAsC;AACtC,wFAA8D;AAC9D,oEAA4C;AAC5C,8FAAoE;AACpE,oDAA4B;AAE5B,sHAAsH;AACtH,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAGlD,CAAC;AAEF,iBAAS;IACP,OAAO,EAAE;QACP,GAAG,EAAH,aAAG;QACH,IAAI,EAAJ,cAAI;QACJ,sBAAsB,EAAE,8BAAkB;QAC1C,oBAAoB,EAAE,4BAAiB;QACvC,WAAW,EAAX,qBAAW;QACX,mEAAmE;QACnE,qCAAqC,EAAE,kCAAsB;QAC7D,0BAA0B,EAAE,kCAAsB;QAClD,MAAM,EAAN,gBAAM;QACN,qBAAqB,EAAE,6BAAiB;QACxC,SAAS,EAAT,mBAAS;QACT,wBAAwB,EAAE,gCAAoB;KAC/C;IACD,IAAI,EAAE;QACJ,IAAI;QACJ,OAAO;KACR;IACD,KAAK,EAAL,eAAK;CACkB,CAAC"}

View File

@ -0,0 +1,46 @@
import { VariantObject, Variant } from '@unocss/core';
import { PresetMiniOptions } from './index.cjs';
import { T as Theme } from './shared/preset-mini.hpPpX7ws.cjs';
import './shared/preset-mini.YxT4AwuI.cjs';
import './colors.cjs';
import './shared/preset-mini.20fUBpHS.cjs';
declare const variantAria: VariantObject;
declare function calcMaxWidthBySize(size: string): string;
declare function variantBreakpoints(): VariantObject;
declare const variantCombinators: Variant[];
declare const variantContainerQuery: VariantObject;
declare function variantColorsMediaOrClass(options?: PresetMiniOptions): Variant[];
declare const variantDataAttribute: VariantObject;
declare const variantTaggedDataAttributes: Variant[];
declare function variants(options: PresetMiniOptions): Variant<Theme>[];
declare const variantLanguageDirections: Variant[];
declare function variantImportant(): VariantObject;
declare const variantPrint: VariantObject;
declare const variantCustomMedia: VariantObject;
declare const variantSelector: Variant;
declare const variantCssLayer: Variant;
declare const variantInternalLayer: Variant;
declare const variantScope: Variant;
declare const variantVariables: Variant;
declare const variantNegative: Variant;
declare function variantPseudoClassesAndElements(): VariantObject;
declare function variantPseudoClassFunctions(): VariantObject;
declare function variantTaggedPseudoClasses(options?: PresetMiniOptions): VariantObject[];
declare const variantPartClasses: VariantObject;
declare const variantSupports: VariantObject;
export { calcMaxWidthBySize, variantAria, variantBreakpoints, variantColorsMediaOrClass, variantCombinators, variantContainerQuery, variantCssLayer, variantCustomMedia, variantDataAttribute, variantImportant, variantInternalLayer, variantLanguageDirections, variantNegative, variantPartClasses, variantPrint, variantPseudoClassFunctions, variantPseudoClassesAndElements, variantScope, variantSelector, variantSupports, variantTaggedDataAttributes, variantTaggedPseudoClasses, variantVariables, variants };

View File

@ -0,0 +1,804 @@
import '@vite/env';
class HMRContext {
constructor(hmrClient, ownerPath) {
this.hmrClient = hmrClient;
this.ownerPath = ownerPath;
if (!hmrClient.dataMap.has(ownerPath)) {
hmrClient.dataMap.set(ownerPath, {});
}
// when a file is hot updated, a new context is created
// clear its stale callbacks
const mod = hmrClient.hotModulesMap.get(ownerPath);
if (mod) {
mod.callbacks = [];
}
// clear stale custom event listeners
const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
if (staleListeners) {
for (const [event, staleFns] of staleListeners) {
const listeners = hmrClient.customListenersMap.get(event);
if (listeners) {
hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
}
}
}
this.newListeners = new Map();
hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
}
get data() {
return this.hmrClient.dataMap.get(this.ownerPath);
}
accept(deps, callback) {
if (typeof deps === 'function' || !deps) {
// self-accept: hot.accept(() => {})
this.acceptDeps([this.ownerPath], ([mod]) => deps === null || deps === void 0 ? void 0 : deps(mod));
}
else if (typeof deps === 'string') {
// explicit deps
this.acceptDeps([deps], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod));
}
else if (Array.isArray(deps)) {
this.acceptDeps(deps, callback);
}
else {
throw new Error(`invalid hot.accept() usage.`);
}
}
// export names (first arg) are irrelevant on the client side, they're
// extracted in the server for propagation
acceptExports(_, callback) {
this.acceptDeps([this.ownerPath], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod));
}
dispose(cb) {
this.hmrClient.disposeMap.set(this.ownerPath, cb);
}
prune(cb) {
this.hmrClient.pruneMap.set(this.ownerPath, cb);
}
// Kept for backward compatibility (#11036)
// eslint-disable-next-line @typescript-eslint/no-empty-function
decline() { }
invalidate(message) {
this.hmrClient.notifyListeners('vite:invalidate', {
path: this.ownerPath,
message,
});
this.send('vite:invalidate', { path: this.ownerPath, message });
this.hmrClient.logger.debug(`[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ''}`);
}
on(event, cb) {
const addToMap = (map) => {
const existing = map.get(event) || [];
existing.push(cb);
map.set(event, existing);
};
addToMap(this.hmrClient.customListenersMap);
addToMap(this.newListeners);
}
off(event, cb) {
const removeFromMap = (map) => {
const existing = map.get(event);
if (existing === undefined) {
return;
}
const pruned = existing.filter((l) => l !== cb);
if (pruned.length === 0) {
map.delete(event);
return;
}
map.set(event, pruned);
};
removeFromMap(this.hmrClient.customListenersMap);
removeFromMap(this.newListeners);
}
send(event, data) {
this.hmrClient.messenger.send(JSON.stringify({ type: 'custom', event, data }));
}
acceptDeps(deps, callback = () => { }) {
const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
id: this.ownerPath,
callbacks: [],
};
mod.callbacks.push({
deps,
fn: callback,
});
this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
}
}
class HMRMessenger {
constructor(connection) {
this.connection = connection;
this.queue = [];
}
send(message) {
this.queue.push(message);
this.flush();
}
flush() {
if (this.connection.isReady()) {
this.queue.forEach((msg) => this.connection.send(msg));
this.queue = [];
}
}
}
class HMRClient {
constructor(logger, connection,
// This allows implementing reloading via different methods depending on the environment
importUpdatedModule) {
this.logger = logger;
this.importUpdatedModule = importUpdatedModule;
this.hotModulesMap = new Map();
this.disposeMap = new Map();
this.pruneMap = new Map();
this.dataMap = new Map();
this.customListenersMap = new Map();
this.ctxToListenersMap = new Map();
this.updateQueue = [];
this.pendingUpdateQueue = false;
this.messenger = new HMRMessenger(connection);
}
async notifyListeners(event, data) {
const cbs = this.customListenersMap.get(event);
if (cbs) {
await Promise.allSettled(cbs.map((cb) => cb(data)));
}
}
clear() {
this.hotModulesMap.clear();
this.disposeMap.clear();
this.pruneMap.clear();
this.dataMap.clear();
this.customListenersMap.clear();
this.ctxToListenersMap.clear();
}
// After an HMR update, some modules are no longer imported on the page
// but they may have left behind side effects that need to be cleaned up
// (.e.g style injections)
// TODO Trigger their dispose callbacks.
prunePaths(paths) {
paths.forEach((path) => {
const fn = this.pruneMap.get(path);
if (fn) {
fn(this.dataMap.get(path));
}
});
}
warnFailedUpdate(err, path) {
if (!err.message.includes('fetch')) {
this.logger.error(err);
}
this.logger.error(`[hmr] Failed to reload ${path}. ` +
`This could be due to syntax errors or importing non-existent ` +
`modules. (see errors above)`);
}
/**
* buffer multiple hot updates triggered by the same src change
* so that they are invoked in the same order they were sent.
* (otherwise the order may be inconsistent because of the http request round trip)
*/
async queueUpdate(payload) {
this.updateQueue.push(this.fetchUpdate(payload));
if (!this.pendingUpdateQueue) {
this.pendingUpdateQueue = true;
await Promise.resolve();
this.pendingUpdateQueue = false;
const loading = [...this.updateQueue];
this.updateQueue = [];
(await Promise.all(loading)).forEach((fn) => fn && fn());
}
}
async fetchUpdate(update) {
const { path, acceptedPath } = update;
const mod = this.hotModulesMap.get(path);
if (!mod) {
// In a code-splitting project,
// it is common that the hot-updating module is not loaded yet.
// https://github.com/vitejs/vite/issues/721
return;
}
let fetchedModule;
const isSelfUpdate = path === acceptedPath;
// determine the qualified callbacks before we re-import the modules
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
if (isSelfUpdate || qualifiedCallbacks.length > 0) {
const disposer = this.disposeMap.get(acceptedPath);
if (disposer)
await disposer(this.dataMap.get(acceptedPath));
try {
fetchedModule = await this.importUpdatedModule(update);
}
catch (e) {
this.warnFailedUpdate(e, acceptedPath);
}
}
return () => {
for (const { deps, fn } of qualifiedCallbacks) {
fn(deps.map((dep) => (dep === acceptedPath ? fetchedModule : undefined)));
}
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`[vite] hot updated: ${loggedPath}`);
};
}
}
const hmrConfigName = __HMR_CONFIG_NAME__;
const base$1 = __BASE__ || '/';
// set :host styles to make playwright detect the element as visible
const template = /*html*/ `
<style>
:host {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 99999;
--monospace: 'SFMono-Regular', Consolas,
'Liberation Mono', Menlo, Courier, monospace;
--red: #ff5555;
--yellow: #e2aa53;
--purple: #cfa4ff;
--cyan: #2dd9da;
--dim: #c9c9c9;
--window-background: #181818;
--window-color: #d8d8d8;
}
.backdrop {
position: fixed;
z-index: 99999;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow-y: scroll;
margin: 0;
background: rgba(0, 0, 0, 0.66);
}
.window {
font-family: var(--monospace);
line-height: 1.5;
width: 800px;
color: var(--window-color);
margin: 30px auto;
padding: 25px 40px;
position: relative;
background: var(--window-background);
border-radius: 6px 6px 8px 8px;
box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
overflow: hidden;
border-top: 8px solid var(--red);
direction: ltr;
text-align: left;
}
pre {
font-family: var(--monospace);
font-size: 16px;
margin-top: 0;
margin-bottom: 1em;
overflow-x: scroll;
scrollbar-width: none;
}
pre::-webkit-scrollbar {
display: none;
}
pre.frame::-webkit-scrollbar {
display: block;
height: 5px;
}
pre.frame::-webkit-scrollbar-thumb {
background: #999;
border-radius: 5px;
}
pre.frame {
scrollbar-width: thin;
}
.message {
line-height: 1.3;
font-weight: 600;
white-space: pre-wrap;
}
.message-body {
color: var(--red);
}
.plugin {
color: var(--purple);
}
.file {
color: var(--cyan);
margin-bottom: 0;
white-space: pre-wrap;
word-break: break-all;
}
.frame {
color: var(--yellow);
}
.stack {
font-size: 13px;
color: var(--dim);
}
.tip {
font-size: 13px;
color: #999;
border-top: 1px dotted #999;
padding-top: 13px;
line-height: 1.8;
}
code {
font-size: 13px;
font-family: var(--monospace);
color: var(--yellow);
}
.file-link {
text-decoration: underline;
cursor: pointer;
}
kbd {
line-height: 1.5;
font-family: ui-monospace, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 0.75rem;
font-weight: 700;
background-color: rgb(38, 40, 44);
color: rgb(166, 167, 171);
padding: 0.15rem 0.3rem;
border-radius: 0.25rem;
border-width: 0.0625rem 0.0625rem 0.1875rem;
border-style: solid;
border-color: rgb(54, 57, 64);
border-image: initial;
}
</style>
<div class="backdrop" part="backdrop">
<div class="window" part="window">
<pre class="message" part="message"><span class="plugin" part="plugin"></span><span class="message-body" part="message-body"></span></pre>
<pre class="file" part="file"></pre>
<pre class="frame" part="frame"></pre>
<pre class="stack" part="stack"></pre>
<div class="tip" part="tip">
Click outside, press <kbd>Esc</kbd> key, or fix the code to dismiss.<br>
You can also disable this overlay by setting
<code part="config-option-name">server.hmr.overlay</code> to <code part="config-option-value">false</code> in <code part="config-file-name">${hmrConfigName}.</code>
</div>
</div>
</div>
`;
const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
// Allow `ErrorOverlay` to extend `HTMLElement` even in environments where
// `HTMLElement` was not originally defined.
const { HTMLElement = class {
} } = globalThis;
class ErrorOverlay extends HTMLElement {
constructor(err, links = true) {
var _a;
super();
this.root = this.attachShadow({ mode: 'open' });
this.root.innerHTML = template;
codeframeRE.lastIndex = 0;
const hasFrame = err.frame && codeframeRE.test(err.frame);
const message = hasFrame
? err.message.replace(codeframeRE, '')
: err.message;
if (err.plugin) {
this.text('.plugin', `[plugin:${err.plugin}] `);
}
this.text('.message-body', message.trim());
const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`);
if (err.loc) {
this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, links);
}
else if (err.id) {
this.text('.file', file);
}
if (hasFrame) {
this.text('.frame', err.frame.trim());
}
this.text('.stack', err.stack, links);
this.root.querySelector('.window').addEventListener('click', (e) => {
e.stopPropagation();
});
this.addEventListener('click', () => {
this.close();
});
this.closeOnEsc = (e) => {
if (e.key === 'Escape' || e.code === 'Escape') {
this.close();
}
};
document.addEventListener('keydown', this.closeOnEsc);
}
text(selector, text, linkFiles = false) {
const el = this.root.querySelector(selector);
if (!linkFiles) {
el.textContent = text;
}
else {
let curIndex = 0;
let match;
fileRE.lastIndex = 0;
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match;
if (index != null) {
const frag = text.slice(curIndex, index);
el.appendChild(document.createTextNode(frag));
const link = document.createElement('a');
link.textContent = file;
link.className = 'file-link';
link.onclick = () => {
fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url));
};
el.appendChild(link);
curIndex += frag.length + file.length;
}
}
}
}
close() {
var _a;
(_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this);
document.removeEventListener('keydown', this.closeOnEsc);
}
}
const overlayId = 'vite-error-overlay';
const { customElements } = globalThis; // Ensure `customElements` is defined before the next line.
if (customElements && !customElements.get(overlayId)) {
customElements.define(overlayId, ErrorOverlay);
}
console.debug('[vite] connecting...');
const importMetaUrl = new URL(import.meta.url);
// use server configuration, then fallback to inference
const serverHost = __SERVER_HOST__;
const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === 'https:' ? 'wss' : 'ws');
const hmrPort = __HMR_PORT__;
const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
const directSocketHost = __HMR_DIRECT_TARGET__;
const base = __BASE__ || '/';
let socket;
try {
let fallback;
// only use fallback when port is inferred to prevent confusion
if (!hmrPort) {
fallback = () => {
// fallback to connecting directly to the hmr server
// for servers which does not support proxying websocket
socket = setupWebSocket(socketProtocol, directSocketHost, () => {
const currentScriptHostURL = new URL(import.meta.url);
const currentScriptHost = currentScriptHostURL.host +
currentScriptHostURL.pathname.replace(/@vite\/client$/, '');
console.error('[vite] failed to connect to websocket.\n' +
'your current setup:\n' +
` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n` +
` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\n` +
'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .');
});
socket.addEventListener('open', () => {
console.info('[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.');
}, { once: true });
};
}
socket = setupWebSocket(socketProtocol, socketHost, fallback);
}
catch (error) {
console.error(`[vite] failed to connect to websocket (${error}). `);
}
function setupWebSocket(protocol, hostAndPath, onCloseWithoutOpen) {
const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr');
let isOpened = false;
socket.addEventListener('open', () => {
isOpened = true;
notifyListeners('vite:ws:connect', { webSocket: socket });
}, { once: true });
// Listen for messages
socket.addEventListener('message', async ({ data }) => {
handleMessage(JSON.parse(data));
});
// ping server
socket.addEventListener('close', async ({ wasClean }) => {
if (wasClean)
return;
if (!isOpened && onCloseWithoutOpen) {
onCloseWithoutOpen();
return;
}
notifyListeners('vite:ws:disconnect', { webSocket: socket });
console.log(`[vite] server connection lost. polling for restart...`);
await waitForSuccessfulPing(protocol, hostAndPath);
location.reload();
});
return socket;
}
function cleanUrl(pathname) {
const url = new URL(pathname, location.toString());
url.searchParams.delete('direct');
return url.pathname + url.search;
}
let isFirstUpdate = true;
const outdatedLinkTags = new WeakSet();
const debounceReload = (time) => {
let timer;
return () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
location.reload();
}, time);
};
};
const pageReload = debounceReload(50);
const hmrClient = new HMRClient(console, {
isReady: () => socket && socket.readyState === 1,
send: (message) => socket.send(message),
}, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport, }) {
const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`);
const importPromise = import(
/* @vite-ignore */
base +
acceptedPathWithoutQuery.slice(1) +
`?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${query ? `&${query}` : ''}`);
if (isWithinCircularImport) {
importPromise.catch(() => {
console.info(`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. ` +
`To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`);
pageReload();
});
}
return await importPromise;
});
async function handleMessage(payload) {
switch (payload.type) {
case 'connected':
console.debug(`[vite] connected.`);
hmrClient.messenger.flush();
// proxy(nginx, docker) hmr ws maybe caused timeout,
// so send ping package let ws keep alive.
setInterval(() => {
if (socket.readyState === socket.OPEN) {
socket.send('{"type":"ping"}');
}
}, __HMR_TIMEOUT__);
break;
case 'update':
notifyListeners('vite:beforeUpdate', payload);
// if this is the first update and there's already an error overlay, it
// means the page opened with existing server compile error and the whole
// module script failed to load (since one of the nested imports is 500).
// in this case a normal update won't work and a full reload is needed.
if (isFirstUpdate && hasErrorOverlay()) {
window.location.reload();
return;
}
else {
clearErrorOverlay();
isFirstUpdate = false;
}
await Promise.all(payload.updates.map(async (update) => {
if (update.type === 'js-update') {
return hmrClient.queueUpdate(update);
}
// css-update
// this is only sent when a css file referenced with <link> is updated
const { path, timestamp } = update;
const searchUrl = cleanUrl(path);
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = Array.from(document.querySelectorAll('link')).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl));
if (!el) {
return;
}
const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes('?') ? '&' : '?'}t=${timestamp}`;
// rather than swapping the href on the existing tag, we will
// create a new link tag. Once the new stylesheet has loaded we
// will remove the existing link tag. This removes a Flash Of
// Unstyled Content that can occur when swapping out the tag href
// directly, as the new stylesheet has not yet been loaded.
return new Promise((resolve) => {
const newLinkTag = el.cloneNode();
newLinkTag.href = new URL(newPath, el.href).href;
const removeOldEl = () => {
el.remove();
console.debug(`[vite] css hot updated: ${searchUrl}`);
resolve();
};
newLinkTag.addEventListener('load', removeOldEl);
newLinkTag.addEventListener('error', removeOldEl);
outdatedLinkTags.add(el);
el.after(newLinkTag);
});
}));
notifyListeners('vite:afterUpdate', payload);
break;
case 'custom': {
notifyListeners(payload.event, payload.data);
break;
}
case 'full-reload':
notifyListeners('vite:beforeFullReload', payload);
if (payload.path && payload.path.endsWith('.html')) {
// if html file is edited, only reload the page if the browser is
// currently on that page.
const pagePath = decodeURI(location.pathname);
const payloadPath = base + payload.path.slice(1);
if (pagePath === payloadPath ||
payload.path === '/index.html' ||
(pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) {
pageReload();
}
return;
}
else {
pageReload();
}
break;
case 'prune':
notifyListeners('vite:beforePrune', payload);
hmrClient.prunePaths(payload.paths);
break;
case 'error': {
notifyListeners('vite:error', payload);
const err = payload.err;
if (enableOverlay) {
createErrorOverlay(err);
}
else {
console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`);
}
break;
}
default: {
const check = payload;
return check;
}
}
}
function notifyListeners(event, data) {
hmrClient.notifyListeners(event, data);
}
const enableOverlay = __HMR_ENABLE_OVERLAY__;
function createErrorOverlay(err) {
clearErrorOverlay();
document.body.appendChild(new ErrorOverlay(err));
}
function clearErrorOverlay() {
document.querySelectorAll(overlayId).forEach((n) => n.close());
}
function hasErrorOverlay() {
return document.querySelectorAll(overlayId).length;
}
async function waitForSuccessfulPing(socketProtocol, hostAndPath, ms = 1000) {
const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http';
const ping = async () => {
// A fetch on a websocket URL will return a successful promise with status 400,
// but will reject a networking error.
// When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
try {
await fetch(`${pingHostProtocol}://${hostAndPath}`, {
mode: 'no-cors',
headers: {
// Custom headers won't be included in a request with no-cors so (ab)use one of the
// safelisted headers to identify the ping request
Accept: 'text/x-vite-ping',
},
});
return true;
}
catch { }
return false;
};
if (await ping()) {
return;
}
await wait(ms);
// eslint-disable-next-line no-constant-condition
while (true) {
if (document.visibilityState === 'visible') {
if (await ping()) {
break;
}
await wait(ms);
}
else {
await waitForWindowShow();
}
}
}
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function waitForWindowShow() {
return new Promise((resolve) => {
const onChange = async () => {
if (document.visibilityState === 'visible') {
resolve();
document.removeEventListener('visibilitychange', onChange);
}
};
document.addEventListener('visibilitychange', onChange);
});
}
const sheetsMap = new Map();
// collect existing style elements that may have been inserted during SSR
// to avoid FOUC or duplicate styles
if ('document' in globalThis) {
document
.querySelectorAll('style[data-vite-dev-id]')
.forEach((el) => {
sheetsMap.set(el.getAttribute('data-vite-dev-id'), el);
});
}
// all css imports should be inserted at the same position
// because after build it will be a single css file
let lastInsertedStyle;
function updateStyle(id, content) {
let style = sheetsMap.get(id);
if (!style) {
style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.setAttribute('data-vite-dev-id', id);
style.textContent = content;
if (!lastInsertedStyle) {
document.head.appendChild(style);
// reset lastInsertedStyle after async
// because dynamically imported css will be splitted into a different file
setTimeout(() => {
lastInsertedStyle = undefined;
}, 0);
}
else {
lastInsertedStyle.insertAdjacentElement('afterend', style);
}
lastInsertedStyle = style;
}
else {
style.textContent = content;
}
sheetsMap.set(id, style);
}
function removeStyle(id) {
const style = sheetsMap.get(id);
if (style) {
document.head.removeChild(style);
sheetsMap.delete(id);
}
}
function createHotContext(ownerPath) {
return new HMRContext(hmrClient, ownerPath);
}
/**
* urls here are dynamic import() urls that couldn't be statically analyzed
*/
function injectQuery(url, queryToInject) {
// skip urls that won't be handled by vite
if (url[0] !== '.' && url[0] !== '/') {
return url;
}
// can't use pathname from URL since it may be relative like ../
const pathname = url.replace(/[?#].*$/s, '');
const { search, hash } = new URL(url, 'http://vitejs.dev');
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`;
}
export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle };
//# sourceMappingURL=client.mjs.map

View File

@ -0,0 +1,304 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLanguage = void 0;
const language_core_1 = require("@volar/language-core");
const language_core_2 = require("@volar/language-core");
const path = require("path-browserify");
const resolveModuleName_1 = require("../resolveModuleName");
const scriptVersions = new Map();
const fsFileSnapshots = new Map();
function createLanguage(ts, sys, languagePlugins, configFileName, projectHost, { fileIdToFileName, fileNameToFileId }) {
const files = (0, language_core_1.createFileRegistry)(languagePlugins, sys.useCaseSensitiveFileNames, fileId => {
const fileName = fileIdToFileName(fileId);
// opened files
let snapshot = projectHost.getScriptSnapshot(fileName);
if (!snapshot) {
// fs files
const cache = fsFileSnapshots.get(fileName);
const modifiedTime = sys.getModifiedTime?.(fileName)?.valueOf();
if (!cache || cache[0] !== modifiedTime) {
if (sys.fileExists(fileName)) {
const text = sys.readFile(fileName);
const snapshot = text !== undefined ? ts.ScriptSnapshot.fromString(text) : undefined;
fsFileSnapshots.set(fileName, [modifiedTime, snapshot]);
}
else {
fsFileSnapshots.set(fileName, [modifiedTime, undefined]);
}
}
snapshot = fsFileSnapshots.get(fileName)?.[1];
}
if (snapshot) {
files.set(fileId, projectHost.getLanguageId(fileId), snapshot);
}
else {
files.delete(fileId);
}
});
let { languageServiceHost, getExtraScript } = createLanguageServiceHost();
for (const language of languagePlugins) {
if (language.typescript?.resolveLanguageServiceHost) {
languageServiceHost = language.typescript.resolveLanguageServiceHost(languageServiceHost);
}
}
if (languagePlugins.some(language => language.typescript?.extraFileExtensions.length)) {
// TODO: can this share between monorepo packages?
const moduleCache = ts.createModuleResolutionCache(languageServiceHost.getCurrentDirectory(), languageServiceHost.useCaseSensitiveFileNames ? s => s : s => s.toLowerCase(), languageServiceHost.getCompilationSettings());
const resolveModuleName = (0, resolveModuleName_1.createResolveModuleName)(ts, languageServiceHost, languagePlugins, fileName => files.get(fileNameToFileId(fileName)));
let lastSysVersion = 'version' in sys ? sys.version : undefined;
languageServiceHost.resolveModuleNameLiterals = (moduleLiterals, containingFile, redirectedReference, options, sourceFile) => {
if ('version' in sys && lastSysVersion !== sys.version) {
lastSysVersion = sys.version;
moduleCache.clear();
}
return moduleLiterals.map(moduleLiteral => {
return resolveModuleName(moduleLiteral.text, containingFile, options, moduleCache, redirectedReference, sourceFile.impliedNodeFormat);
});
};
languageServiceHost.resolveModuleNames = (moduleNames, containingFile, _reusedNames, redirectedReference, options) => {
if ('version' in sys && lastSysVersion !== sys.version) {
lastSysVersion = sys.version;
moduleCache.clear();
}
return moduleNames.map(moduleName => {
return resolveModuleName(moduleName, containingFile, options, moduleCache, redirectedReference).resolvedModule;
});
};
}
return {
files,
typescript: {
configFileName,
sys,
projectHost,
languageServiceHost,
getExtraScript,
},
};
function createLanguageServiceHost() {
let lastProjectVersion;
let tsProjectVersion = 0;
let tsFileRegistry = new language_core_1.FileMap(sys.useCaseSensitiveFileNames);
let extraScriptRegistry = new language_core_1.FileMap(sys.useCaseSensitiveFileNames);
let lastTsVirtualFileSnapshots = new Set();
let lastOtherVirtualFileSnapshots = new Set();
const languageServiceHost = {
...sys,
getCurrentDirectory: projectHost.getCurrentDirectory,
getCompilationSettings() {
const options = projectHost.getCompilationSettings();
if (languagePlugins.some(language => language.typescript?.extraFileExtensions.length)) {
options.allowNonTsExtensions ??= true;
if (!options.allowNonTsExtensions) {
console.warn('`allowNonTsExtensions` must be `true`.');
}
}
return options;
},
getLocalizedDiagnosticMessages: projectHost.getLocalizedDiagnosticMessages,
getProjectReferences: projectHost.getProjectReferences,
getDefaultLibFileName: options => {
try {
return ts.getDefaultLibFilePath(options);
}
catch {
// web
return `/node_modules/typescript/lib/${ts.getDefaultLibFileName(options)}`;
}
},
useCaseSensitiveFileNames() {
return sys.useCaseSensitiveFileNames;
},
getNewLine() {
return sys.newLine;
},
getTypeRootsVersion: () => {
return 'version' in sys ? sys.version : -1; // TODO: only update for /node_modules changes?
},
getDirectories(dirName) {
return sys.getDirectories(dirName);
},
readDirectory(dirName, extensions, excludes, includes, depth) {
const exts = new Set(extensions);
for (const languagePlugin of languagePlugins) {
for (const ext of languagePlugin.typescript?.extraFileExtensions ?? []) {
exts.add('.' + ext.extension);
}
}
extensions = [...exts];
return sys.readDirectory(dirName, extensions, excludes, includes, depth);
},
readFile(fileName) {
const snapshot = getScriptSnapshot(fileName);
if (snapshot) {
return snapshot.getText(0, snapshot.getLength());
}
},
fileExists(fileName) {
return getScriptVersion(fileName) !== '';
},
getProjectVersion() {
sync();
return tsProjectVersion + ('version' in sys ? `:${sys.version}` : '');
},
getScriptFileNames() {
sync();
return [...tsFileRegistry.keys()];
},
getScriptKind(fileName) {
sync();
if (extraScriptRegistry.has(fileName)) {
return extraScriptRegistry.get(fileName).scriptKind;
}
const sourceFile = files.get(fileNameToFileId(fileName));
if (sourceFile?.generated) {
const tsCode = sourceFile.generated.languagePlugin.typescript?.getScript(sourceFile.generated.code);
if (tsCode) {
return tsCode.scriptKind;
}
}
switch (path.extname(fileName)) {
case '.js':
case '.cjs':
case '.mjs':
return ts.ScriptKind.JS;
case '.jsx':
return ts.ScriptKind.JSX;
case '.ts':
case '.cts':
case '.mts':
return ts.ScriptKind.TS;
case '.tsx':
return ts.ScriptKind.TSX;
case '.json':
return ts.ScriptKind.JSON;
default:
return ts.ScriptKind.Unknown;
}
},
getScriptVersion,
getScriptSnapshot,
};
return {
languageServiceHost,
getExtraScript,
};
function getExtraScript(fileName) {
sync();
return extraScriptRegistry.get(fileName);
}
function sync() {
const newProjectVersion = projectHost.getProjectVersion?.();
const shouldUpdate = newProjectVersion === undefined || newProjectVersion !== lastProjectVersion;
if (!shouldUpdate) {
return;
}
lastProjectVersion = newProjectVersion;
extraScriptRegistry.clear();
const newTsVirtualFileSnapshots = new Set();
const newOtherVirtualFileSnapshots = new Set();
const tsFileNamesSet = new Set();
for (const fileName of projectHost.getScriptFileNames()) {
const sourceFile = files.get(fileNameToFileId(fileName));
if (sourceFile?.generated) {
const script = sourceFile.generated.languagePlugin.typescript?.getScript(sourceFile.generated.code);
if (script) {
newTsVirtualFileSnapshots.add(script.code.snapshot);
tsFileNamesSet.add(fileName);
}
for (const extraScript of sourceFile.generated.languagePlugin.typescript?.getExtraScripts?.(fileName, sourceFile.generated.code) ?? []) {
newTsVirtualFileSnapshots.add(extraScript.code.snapshot);
tsFileNamesSet.add(extraScript.fileName);
extraScriptRegistry.set(extraScript.fileName, extraScript);
}
for (const code of (0, language_core_2.forEachEmbeddedCode)(sourceFile.generated.code)) {
newOtherVirtualFileSnapshots.add(code.snapshot);
}
}
else {
tsFileNamesSet.add(fileName);
}
}
if (!setEquals(lastTsVirtualFileSnapshots, newTsVirtualFileSnapshots)) {
tsProjectVersion++;
}
else if (setEquals(lastOtherVirtualFileSnapshots, newOtherVirtualFileSnapshots)) {
// no any meta language files update, it mean project version was update by source files this time
tsProjectVersion++;
}
lastTsVirtualFileSnapshots = newTsVirtualFileSnapshots;
lastOtherVirtualFileSnapshots = newOtherVirtualFileSnapshots;
tsFileRegistry.clear();
for (const fileName of tsFileNamesSet) {
tsFileRegistry.set(fileName, true);
}
}
function getScriptSnapshot(fileName) {
sync();
if (extraScriptRegistry.has(fileName)) {
return extraScriptRegistry.get(fileName).code.snapshot;
}
const sourceFile = files.get(fileNameToFileId(fileName));
if (sourceFile?.generated) {
const script = sourceFile.generated.languagePlugin.typescript?.getScript(sourceFile.generated.code);
if (script) {
return script.code.snapshot;
}
}
else if (sourceFile) {
return sourceFile.snapshot;
}
}
function getScriptVersion(fileName) {
sync();
if (!scriptVersions.has(fileName)) {
scriptVersions.set(fileName, { lastVersion: 0, map: new WeakMap() });
}
const version = scriptVersions.get(fileName);
if (extraScriptRegistry.has(fileName)) {
const snapshot = extraScriptRegistry.get(fileName).code.snapshot;
if (!version.map.has(snapshot)) {
version.map.set(snapshot, version.lastVersion++);
}
return version.map.get(snapshot).toString();
}
const sourceFile = files.get(fileNameToFileId(fileName));
if (sourceFile?.generated) {
const script = sourceFile.generated.languagePlugin.typescript?.getScript(sourceFile.generated.code);
if (script) {
if (!version.map.has(script.code.snapshot)) {
version.map.set(script.code.snapshot, version.lastVersion++);
}
return version.map.get(script.code.snapshot).toString();
}
}
const isOpenedFile = !!projectHost.getScriptSnapshot(fileName);
if (isOpenedFile) {
const sourceFile = files.get(fileNameToFileId(fileName));
if (sourceFile && !sourceFile.generated) {
if (!version.map.has(sourceFile.snapshot)) {
version.map.set(sourceFile.snapshot, version.lastVersion++);
}
return version.map.get(sourceFile.snapshot).toString();
}
}
if (sys.fileExists(fileName)) {
return sys.getModifiedTime?.(fileName)?.valueOf().toString() ?? '0';
}
return '';
}
}
}
exports.createLanguage = createLanguage;
function setEquals(a, b) {
if (a.size !== b.size) {
return false;
}
for (const item of a) {
if (!b.has(item)) {
return false;
}
}
return true;
}
//# sourceMappingURL=createProject.js.map

View File

@ -0,0 +1,138 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SnapshotDocument = void 0;
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const combine_1 = require("./combine");
class SnapshotDocument {
constructor(uri, languageId, version, text) {
this.snapshots = [];
this.document = vscode_languageserver_textdocument_1.TextDocument.create(uri, languageId, version, text);
this.resetChanges();
}
get uri() {
return this.document.uri;
}
get languageId() {
return this.document.languageId;
}
get version() {
return this.document.version;
}
get lineCount() {
return this.document.lineCount;
}
getText(range) {
return this.document.getText(range);
}
positionAt(offset) {
return this.document.positionAt(offset);
}
offsetAt(position) {
return this.document.offsetAt(position);
}
/**
* Update the document with the given content changes and version.
* If all changes is incremental, calculate the change range and add a new snapshot.
* Otherwise, reset the changes.
*/
update(contentChanges, version) {
if (contentChanges.every(change => 'range' in change)) {
const { minStart, oldLength, lengthDiff } = this.calculateChangeRange(contentChanges);
vscode_languageserver_textdocument_1.TextDocument.update(this.document, contentChanges, version);
this.snapshots.push({
changeRange: {
span: {
start: minStart,
length: oldLength,
},
newLength: oldLength + lengthDiff,
},
version,
ref: undefined,
});
}
else {
vscode_languageserver_textdocument_1.TextDocument.update(this.document, contentChanges, version);
this.resetChanges();
}
}
getSnapshot() {
this.clearUnreferencedVersions();
const lastChange = this.snapshots[this.snapshots.length - 1];
if (!lastChange.ref) {
const text = this.document.getText();
const changeRangeCache = new WeakMap();
const snapshot = {
getText: (start, end) => text.substring(start, end),
getLength: () => text.length,
getChangeRange: oldSnapshot => {
if (!changeRangeCache.has(oldSnapshot)) {
const oldIndex = this.snapshots.findIndex(change => change.ref?.deref() === oldSnapshot);
if (oldIndex >= 0) {
const start = oldIndex + 1;
const end = this.snapshots.indexOf(lastChange) + 1;
const changeRanges = this.snapshots
.slice(start, end)
.map(change => change.changeRange);
const changeRange = (0, combine_1.combineChangeRanges)(...changeRanges);
changeRangeCache.set(oldSnapshot, changeRange);
}
else {
changeRangeCache.set(oldSnapshot, undefined);
}
}
return changeRangeCache.get(oldSnapshot);
},
};
lastChange.ref = new WeakRef(snapshot);
}
return lastChange.ref.deref();
}
resetChanges() {
this.snapshots = [
{
changeRange: {
span: {
start: 0,
length: 0,
},
newLength: this.document.getText().length,
},
version: this.document.version,
ref: undefined,
}
];
}
/**
* Calculate the change range from the given content changes.
*/
calculateChangeRange(contentChanges) {
let lengthDiff = 0;
const starts = [];
const ends = [];
for (const contentChange of contentChanges) {
if (!('range' in contentChange)) {
continue;
}
const start = this.offsetAt(contentChange.range.start);
const length = contentChange.rangeLength ?? this.offsetAt(contentChange.range.end) - start;
const end = start + length;
starts.push(start);
ends.push(end);
lengthDiff += contentChange.text.length - length;
}
const minStart = Math.min(...starts);
const maxEnd = Math.max(...ends);
const oldLength = maxEnd - minStart;
return { minStart, oldLength, lengthDiff };
}
clearUnreferencedVersions() {
let firstReferencedIndex = 0;
while (firstReferencedIndex < this.snapshots.length - 1 && !this.snapshots[firstReferencedIndex].ref?.deref()) {
firstReferencedIndex++;
}
this.snapshots = this.snapshots.slice(firstReferencedIndex);
}
}
exports.SnapshotDocument = SnapshotDocument;
//# sourceMappingURL=snapshotDocument.js.map

View File

@ -0,0 +1,47 @@
{
"name": "@astrojs/check",
"version": "0.5.4",
"author": "withastro",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/withastro/language-tools",
"directory": "packages/astro-check"
},
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"astro-check": "./dist/bin.js"
},
"files": [
"bin",
"dist/**/*.js",
"dist/**/*.d.ts"
],
"dependencies": {
"@astrojs/language-server": "^2.7.4",
"chokidar": "^3.5.3",
"fast-glob": "^3.3.1",
"kleur": "^4.1.5",
"yargs": "^17.7.2"
},
"devDependencies": {
"@types/node": "^18.17.8",
"@types/yargs": "^17.0.24",
"@types/chai": "^4.3.5",
"@types/mocha": "^10.0.1",
"chai": "^4.3.7",
"mocha": "^10.2.0",
"tsx": "^3.12.7"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"test": "mocha --timeout 50000 --require tsx test/**/*.test.ts",
"test:match": "pnpm run test -g"
}
}

View File

@ -0,0 +1,538 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
// Truthiness utilities
// #region
const isTruthyLiteral = (type) => tsutils.isTrueLiteralType(type) ||
// || type.
(type.isLiteral() && !!type.value);
const isPossiblyFalsy = (type) => tsutils
.unionTypeParts(type)
// Intersections like `string & {}` can also be possibly falsy,
// requiring us to look into the intersection.
.flatMap(type => tsutils.intersectionTypeParts(type))
// PossiblyFalsy flag includes literal values, so exclude ones that
// are definitely truthy
.filter(t => !isTruthyLiteral(t))
.some(type => (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.PossiblyFalsy));
const isPossiblyTruthy = (type) => tsutils
.unionTypeParts(type)
.map(type => tsutils.intersectionTypeParts(type))
.some(intersectionParts =>
// It is possible to define intersections that are always falsy,
// like `"" & { __brand: string }`.
intersectionParts.every(type => !tsutils.isFalsyType(type)));
// Nullish utilities
const nullishFlag = ts.TypeFlags.Undefined | ts.TypeFlags.Null;
const isNullishType = (type) => (0, util_1.isTypeFlagSet)(type, nullishFlag);
const isPossiblyNullish = (type) => tsutils.unionTypeParts(type).some(isNullishType);
const isAlwaysNullish = (type) => tsutils.unionTypeParts(type).every(isNullishType);
// isLiteralType only covers numbers and strings, this is a more exhaustive check.
const isLiteral = (type) => tsutils.isBooleanLiteralType(type) ||
type.flags === ts.TypeFlags.Undefined ||
type.flags === ts.TypeFlags.Null ||
type.flags === ts.TypeFlags.Void ||
type.isLiteral();
exports.default = (0, util_1.createRule)({
name: 'no-unnecessary-condition',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow conditionals where the type is always truthy or always falsy',
recommended: 'strict',
requiresTypeChecking: true,
},
schema: [
{
type: 'object',
properties: {
allowConstantLoopConditions: {
description: 'Whether to ignore constant loop conditions, such as `while (true)`.',
type: 'boolean',
},
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: {
description: 'Whether to not error when running with a tsconfig that has strictNullChecks turned.',
type: 'boolean',
},
},
additionalProperties: false,
},
],
fixable: 'code',
messages: {
alwaysTruthy: 'Unnecessary conditional, value is always truthy.',
alwaysFalsy: 'Unnecessary conditional, value is always falsy.',
alwaysTruthyFunc: 'This callback should return a conditional, but return is always truthy.',
alwaysFalsyFunc: 'This callback should return a conditional, but return is always falsy.',
neverNullish: 'Unnecessary conditional, expected left-hand side of `??` operator to be possibly null or undefined.',
alwaysNullish: 'Unnecessary conditional, left-hand side of `??` operator is always `null` or `undefined`.',
literalBooleanExpression: 'Unnecessary conditional, both sides of the expression are literal values.',
noOverlapBooleanExpression: 'Unnecessary conditional, the types have no overlap.',
never: 'Unnecessary conditional, value is `never`.',
neverOptionalChain: 'Unnecessary optional chain on a non-nullish value.',
noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.',
},
},
defaultOptions: [
{
allowConstantLoopConditions: false,
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
},
],
create(context, [{ allowConstantLoopConditions, allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing, },]) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks');
if (!isStrictNullChecks &&
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) {
context.report({
loc: {
start: { line: 0, column: 0 },
end: { line: 0, column: 0 },
},
messageId: 'noStrictNullCheck',
});
}
function nodeIsArrayType(node) {
const nodeType = (0, util_1.getConstrainedTypeAtLocation)(services, node);
return checker.isArrayType(nodeType);
}
function nodeIsTupleType(node) {
const nodeType = (0, util_1.getConstrainedTypeAtLocation)(services, node);
return checker.isTupleType(nodeType);
}
function isArrayIndexExpression(node) {
return (
// Is an index signature
node.type === utils_1.AST_NODE_TYPES.MemberExpression &&
node.computed &&
// ...into an array type
(nodeIsArrayType(node.object) ||
// ... or a tuple type
(nodeIsTupleType(node.object) &&
// Exception: literal index into a tuple - will have a sound type
node.property.type !== utils_1.AST_NODE_TYPES.Literal)));
}
function isNullableMemberExpression(node) {
const objectType = services.getTypeAtLocation(node.object);
if (node.computed) {
const propertyType = services.getTypeAtLocation(node.property);
return isNullablePropertyType(objectType, propertyType);
}
const property = node.property;
if (property.type === utils_1.AST_NODE_TYPES.Identifier) {
const propertyType = objectType.getProperty(property.name);
if (propertyType &&
tsutils.isSymbolFlagSet(propertyType, ts.SymbolFlags.Optional)) {
return true;
}
}
return false;
}
/**
* Checks if a conditional node is necessary:
* if the type of the node is always true or always false, it's not necessary.
*/
function checkNode(node, isUnaryNotArgument = false) {
// Check if the node is Unary Negation expression and handle it
if (node.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
node.operator === '!') {
return checkNode(node.argument, true);
}
// Since typescript array index signature types don't represent the
// possibility of out-of-bounds access, if we're indexing into an array
// just skip the check, to avoid false positives
if (isArrayIndexExpression(node)) {
return;
}
// When checking logical expressions, only check the right side
// as the left side has been checked by checkLogicalExpressionForUnnecessaryConditionals
//
// Unless the node is nullish coalescing, as it's common to use patterns like `nullBool ?? true` to to strict
// boolean checks if we inspect the right here, it'll usually be a constant condition on purpose.
// In this case it's better to inspect the type of the expression as a whole.
if (node.type === utils_1.AST_NODE_TYPES.LogicalExpression &&
node.operator !== '??') {
return checkNode(node.right);
}
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node);
// Conditional is always necessary if it involves:
// `any` or `unknown` or a naked type variable
if (tsutils
.unionTypeParts(type)
.some(part => (0, util_1.isTypeAnyType)(part) ||
(0, util_1.isTypeUnknownType)(part) ||
(0, util_1.isTypeFlagSet)(part, ts.TypeFlags.TypeVariable))) {
return;
}
let messageId = null;
if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Never)) {
messageId = 'never';
}
else if (!isPossiblyTruthy(type)) {
messageId = !isUnaryNotArgument ? 'alwaysFalsy' : 'alwaysTruthy';
}
else if (!isPossiblyFalsy(type)) {
messageId = !isUnaryNotArgument ? 'alwaysTruthy' : 'alwaysFalsy';
}
if (messageId) {
context.report({ node, messageId });
}
}
function checkNodeForNullish(node) {
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node);
// Conditional is always necessary if it involves `any`, `unknown` or a naked type parameter
if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Any |
ts.TypeFlags.Unknown |
ts.TypeFlags.TypeParameter |
ts.TypeFlags.TypeVariable)) {
return;
}
let messageId = null;
if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Never)) {
messageId = 'never';
}
else if (!isPossiblyNullish(type) &&
!(node.type === utils_1.AST_NODE_TYPES.MemberExpression &&
isNullableMemberExpression(node))) {
// Since typescript array index signature types don't represent the
// possibility of out-of-bounds access, if we're indexing into an array
// just skip the check, to avoid false positives
if (!isArrayIndexExpression(node) &&
!(node.type === utils_1.AST_NODE_TYPES.ChainExpression &&
node.expression.type !== utils_1.AST_NODE_TYPES.TSNonNullExpression &&
optionChainContainsOptionArrayIndex(node.expression))) {
messageId = 'neverNullish';
}
}
else if (isAlwaysNullish(type)) {
messageId = 'alwaysNullish';
}
if (messageId) {
context.report({ node, messageId });
}
}
/**
* Checks that a binary expression is necessarily conditional, reports otherwise.
* If both sides of the binary expression are literal values, it's not a necessary condition.
*
* NOTE: It's also unnecessary if the types that don't overlap at all
* but that case is handled by the Typescript compiler itself.
* Known exceptions:
* - https://github.com/microsoft/TypeScript/issues/32627
* - https://github.com/microsoft/TypeScript/issues/37160 (handled)
*/
const BOOL_OPERATORS = new Set([
'<',
'>',
'<=',
'>=',
'==',
'===',
'!=',
'!==',
]);
function checkIfBinaryExpressionIsNecessaryConditional(node) {
if (!BOOL_OPERATORS.has(node.operator)) {
return;
}
const leftType = (0, util_1.getConstrainedTypeAtLocation)(services, node.left);
const rightType = (0, util_1.getConstrainedTypeAtLocation)(services, node.right);
if (isLiteral(leftType) && isLiteral(rightType)) {
context.report({ node, messageId: 'literalBooleanExpression' });
return;
}
// Workaround for https://github.com/microsoft/TypeScript/issues/37160
if (isStrictNullChecks) {
const UNDEFINED = ts.TypeFlags.Undefined;
const NULL = ts.TypeFlags.Null;
const VOID = ts.TypeFlags.Void;
const isComparable = (type, flag) => {
// Allow comparison to `any`, `unknown` or a naked type parameter.
flag |=
ts.TypeFlags.Any |
ts.TypeFlags.Unknown |
ts.TypeFlags.TypeParameter |
ts.TypeFlags.TypeVariable;
// Allow loose comparison to nullish values.
if (node.operator === '==' || node.operator === '!=') {
flag |= NULL | UNDEFINED | VOID;
}
return (0, util_1.isTypeFlagSet)(type, flag);
};
if ((leftType.flags === UNDEFINED &&
!isComparable(rightType, UNDEFINED | VOID)) ||
(rightType.flags === UNDEFINED &&
!isComparable(leftType, UNDEFINED | VOID)) ||
(leftType.flags === NULL && !isComparable(rightType, NULL)) ||
(rightType.flags === NULL && !isComparable(leftType, NULL))) {
context.report({ node, messageId: 'noOverlapBooleanExpression' });
return;
}
}
}
/**
* Checks that a logical expression contains a boolean, reports otherwise.
*/
function checkLogicalExpressionForUnnecessaryConditionals(node) {
if (node.operator === '??') {
checkNodeForNullish(node.left);
return;
}
// Only checks the left side, since the right side might not be "conditional" at all.
// The right side will be checked if the LogicalExpression is used in a conditional context
checkNode(node.left);
}
/**
* Checks that a testable expression of a loop is necessarily conditional, reports otherwise.
*/
function checkIfLoopIsNecessaryConditional(node) {
if (node.test == null) {
// e.g. `for(;;)`
return;
}
/**
* Allow:
* while (true) {}
* for (;true;) {}
* do {} while (true)
*/
if (allowConstantLoopConditions &&
tsutils.isTrueLiteralType((0, util_1.getConstrainedTypeAtLocation)(services, node.test))) {
return;
}
checkNode(node.test);
}
const ARRAY_PREDICATE_FUNCTIONS = new Set([
'filter',
'find',
'some',
'every',
]);
function isArrayPredicateFunction(node) {
const { callee } = node;
return (
// looks like `something.filter` or `something.find`
callee.type === utils_1.AST_NODE_TYPES.MemberExpression &&
callee.property.type === utils_1.AST_NODE_TYPES.Identifier &&
ARRAY_PREDICATE_FUNCTIONS.has(callee.property.name) &&
// and the left-hand side is an array, according to the types
(nodeIsArrayType(callee.object) || nodeIsTupleType(callee.object)));
}
function checkCallExpression(node) {
// If this is something like arr.filter(x => /*condition*/), check `condition`
if (isArrayPredicateFunction(node) && node.arguments.length) {
const callback = node.arguments[0];
// Inline defined functions
if (callback.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression ||
callback.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
// Two special cases, where we can directly check the node that's returned:
// () => something
if (callback.body.type !== utils_1.AST_NODE_TYPES.BlockStatement) {
return checkNode(callback.body);
}
// () => { return something; }
const callbackBody = callback.body.body;
if (callbackBody.length === 1 &&
callbackBody[0].type === utils_1.AST_NODE_TYPES.ReturnStatement &&
callbackBody[0].argument) {
return checkNode(callbackBody[0].argument);
}
// Potential enhancement: could use code-path analysis to check
// any function with a single return statement
// (Value to complexity ratio is dubious however)
}
// Otherwise just do type analysis on the function as a whole.
const returnTypes = tsutils
.getCallSignaturesOfType((0, util_1.getConstrainedTypeAtLocation)(services, callback))
.map(sig => sig.getReturnType());
/* istanbul ignore if */ if (returnTypes.length === 0) {
// Not a callable function
return;
}
// Predicate is always necessary if it involves `any` or `unknown`
if (returnTypes.some(t => (0, util_1.isTypeAnyType)(t) || (0, util_1.isTypeUnknownType)(t))) {
return;
}
if (!returnTypes.some(isPossiblyFalsy)) {
return context.report({
node: callback,
messageId: 'alwaysTruthyFunc',
});
}
if (!returnTypes.some(isPossiblyTruthy)) {
return context.report({
node: callback,
messageId: 'alwaysFalsyFunc',
});
}
}
}
// Recursively searches an optional chain for an array index expression
// Has to search the entire chain, because an array index will "infect" the rest of the types
// Example:
// ```
// [{x: {y: "z"} }][n] // type is {x: {y: "z"}}
// ?.x // type is {y: "z"}
// ?.y // This access is considered "unnecessary" according to the types
// ```
function optionChainContainsOptionArrayIndex(node) {
const lhsNode = node.type === utils_1.AST_NODE_TYPES.CallExpression ? node.callee : node.object;
if (node.optional && isArrayIndexExpression(lhsNode)) {
return true;
}
if (lhsNode.type === utils_1.AST_NODE_TYPES.MemberExpression ||
lhsNode.type === utils_1.AST_NODE_TYPES.CallExpression) {
return optionChainContainsOptionArrayIndex(lhsNode);
}
return false;
}
function isNullablePropertyType(objType, propertyType) {
if (propertyType.isUnion()) {
return propertyType.types.some(type => isNullablePropertyType(objType, type));
}
if (propertyType.isNumberLiteral() || propertyType.isStringLiteral()) {
const propType = (0, util_1.getTypeOfPropertyOfName)(checker, objType, propertyType.value.toString());
if (propType) {
return (0, util_1.isNullableType)(propType);
}
}
const typeName = (0, util_1.getTypeName)(checker, propertyType);
return !!checker
.getIndexInfosOfType(objType)
.find(info => (0, util_1.getTypeName)(checker, info.keyType) === typeName);
}
// Checks whether a member expression is nullable or not regardless of it's previous node.
// Example:
// ```
// // 'bar' is nullable if 'foo' is null.
// // but this function checks regardless of 'foo' type, so returns 'true'.
// declare const foo: { bar : { baz: string } } | null
// foo?.bar;
// ```
function isMemberExpressionNullableOriginFromObject(node) {
const prevType = (0, util_1.getConstrainedTypeAtLocation)(services, node.object);
const property = node.property;
if (prevType.isUnion() && (0, util_1.isIdentifier)(property)) {
const isOwnNullable = prevType.types.some(type => {
if (node.computed) {
const propertyType = (0, util_1.getConstrainedTypeAtLocation)(services, node.property);
return isNullablePropertyType(type, propertyType);
}
const propType = (0, util_1.getTypeOfPropertyOfName)(checker, type, property.name);
if (propType) {
return (0, util_1.isNullableType)(propType);
}
return !!checker.getIndexInfoOfType(type, ts.IndexKind.String);
});
return !isOwnNullable && (0, util_1.isNullableType)(prevType);
}
return false;
}
function isCallExpressionNullableOriginFromCallee(node) {
const prevType = (0, util_1.getConstrainedTypeAtLocation)(services, node.callee);
if (prevType.isUnion()) {
const isOwnNullable = prevType.types.some(type => {
const signatures = type.getCallSignatures();
return signatures.some(sig => (0, util_1.isNullableType)(sig.getReturnType(), { allowUndefined: true }));
});
return (!isOwnNullable && (0, util_1.isNullableType)(prevType, { allowUndefined: true }));
}
return false;
}
function isOptionableExpression(node) {
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node);
const isOwnNullable = node.type === utils_1.AST_NODE_TYPES.MemberExpression
? !isMemberExpressionNullableOriginFromObject(node)
: node.type === utils_1.AST_NODE_TYPES.CallExpression
? !isCallExpressionNullableOriginFromCallee(node)
: true;
const possiblyVoid = (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Void);
return ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown) ||
(isOwnNullable && ((0, util_1.isNullableType)(type) || possiblyVoid)));
}
function checkOptionalChain(node, beforeOperator, fix) {
// We only care if this step in the chain is optional. If just descend
// from an optional chain, then that's fine.
if (!node.optional) {
return;
}
// Since typescript array index signature types don't represent the
// possibility of out-of-bounds access, if we're indexing into an array
// just skip the check, to avoid false positives
if (optionChainContainsOptionArrayIndex(node)) {
return;
}
const nodeToCheck = node.type === utils_1.AST_NODE_TYPES.CallExpression ? node.callee : node.object;
if (isOptionableExpression(nodeToCheck)) {
return;
}
const questionDotOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(beforeOperator, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && token.value === '?.'), util_1.NullThrowsReasons.MissingToken('operator', node.type));
context.report({
node,
loc: questionDotOperator.loc,
messageId: 'neverOptionalChain',
fix(fixer) {
return fixer.replaceText(questionDotOperator, fix);
},
});
}
function checkOptionalMemberExpression(node) {
checkOptionalChain(node, node.object, node.computed ? '' : '.');
}
function checkOptionalCallExpression(node) {
checkOptionalChain(node, node.callee, '');
}
function checkAssignmentExpression(node) {
// Similar to checkLogicalExpressionForUnnecessaryConditionals, since
// a ||= b is equivalent to a || (a = b)
if (['||=', '&&='].includes(node.operator)) {
checkNode(node.left);
}
else if (node.operator === '??=') {
checkNodeForNullish(node.left);
}
}
return {
AssignmentExpression: checkAssignmentExpression,
BinaryExpression: checkIfBinaryExpressionIsNecessaryConditional,
CallExpression: checkCallExpression,
ConditionalExpression: (node) => checkNode(node.test),
DoWhileStatement: checkIfLoopIsNecessaryConditional,
ForStatement: checkIfLoopIsNecessaryConditional,
IfStatement: (node) => checkNode(node.test),
LogicalExpression: checkLogicalExpressionForUnnecessaryConditionals,
WhileStatement: checkIfLoopIsNecessaryConditional,
'MemberExpression[optional = true]': checkOptionalMemberExpression,
'CallExpression[optional = true]': checkOptionalCallExpression,
};
},
});
//# sourceMappingURL=no-unnecessary-condition.js.map

View File

@ -0,0 +1,243 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const typescript_1 = require("typescript");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'consistent-type-exports',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce consistent usage of type exports',
requiresTypeChecking: true,
},
messages: {
typeOverValue: 'All exports in the declaration are only used as types. Use `export type`.',
singleExportIsType: 'Type export {{exportNames}} is not a value and should be exported using `export type`.',
multipleExportsAreTypes: 'Type exports {{exportNames}} are not values and should be exported using `export type`.',
},
schema: [
{
type: 'object',
properties: {
fixMixedExportsWithInlineTypeSpecifier: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
fixable: 'code',
},
defaultOptions: [
{
fixMixedExportsWithInlineTypeSpecifier: false,
},
],
create(context, [{ fixMixedExportsWithInlineTypeSpecifier }]) {
const sourceExportsMap = {};
const services = (0, util_1.getParserServices)(context);
/**
* Helper for identifying if an export specifier resolves to a
* JavaScript value or a TypeScript type.
*
* @returns True/false if is a type or not, or undefined if the specifier
* can't be resolved.
*/
function isSpecifierTypeBased(specifier) {
const checker = services.program.getTypeChecker();
const symbol = services.getSymbolAtLocation(specifier.exported);
if (!symbol) {
return undefined;
}
const aliasedSymbol = checker.getAliasedSymbol(symbol);
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
if (aliasedSymbol.escapedName === 'unknown') {
return undefined;
}
return !(aliasedSymbol.flags & typescript_1.SymbolFlags.Value);
}
return {
ExportNamedDeclaration(node) {
// Coerce the source into a string for use as a lookup entry.
const source = getSourceFromExport(node) ?? 'undefined';
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const sourceExports = (sourceExportsMap[source] ||= {
source,
reportValueExports: [],
typeOnlyNamedExport: null,
valueOnlyNamedExport: null,
});
// Cache the first encountered exports for the package. We will need to come
// back to these later when fixing the problems.
if (node.exportKind === 'type') {
if (sourceExports.typeOnlyNamedExport == null) {
// The export is a type export
sourceExports.typeOnlyNamedExport = node;
}
}
else if (sourceExports.valueOnlyNamedExport == null) {
// The export is a value export
sourceExports.valueOnlyNamedExport = node;
}
// Next for the current export, we will separate type/value specifiers.
const typeBasedSpecifiers = [];
const inlineTypeSpecifiers = [];
const valueSpecifiers = [];
// Note: it is valid to export values as types. We will avoid reporting errors
// when this is encountered.
if (node.exportKind !== 'type') {
for (const specifier of node.specifiers) {
if (specifier.exportKind === 'type') {
inlineTypeSpecifiers.push(specifier);
continue;
}
const isTypeBased = isSpecifierTypeBased(specifier);
if (isTypeBased === true) {
typeBasedSpecifiers.push(specifier);
}
else if (isTypeBased === false) {
// When isTypeBased is undefined, we should avoid reporting them.
valueSpecifiers.push(specifier);
}
}
}
if ((node.exportKind === 'value' && typeBasedSpecifiers.length) ||
(node.exportKind === 'type' && valueSpecifiers.length)) {
sourceExports.reportValueExports.push({
node,
typeBasedSpecifiers,
valueSpecifiers,
inlineTypeSpecifiers,
});
}
},
'Program:exit'() {
for (const sourceExports of Object.values(sourceExportsMap)) {
// If this export has no issues, move on.
if (sourceExports.reportValueExports.length === 0) {
continue;
}
for (const report of sourceExports.reportValueExports) {
if (report.valueSpecifiers.length === 0) {
// Export is all type-only with no type specifiers; convert the entire export to `export type`.
context.report({
node: report.node,
messageId: 'typeOverValue',
*fix(fixer) {
yield* fixExportInsertType(fixer, context.sourceCode, report.node);
},
});
continue;
}
// We have both type and value violations.
const allExportNames = report.typeBasedSpecifiers.map(specifier => specifier.local.name);
if (allExportNames.length === 1) {
const exportNames = allExportNames[0];
context.report({
node: report.node,
messageId: 'singleExportIsType',
data: { exportNames },
*fix(fixer) {
if (fixMixedExportsWithInlineTypeSpecifier) {
yield* fixAddTypeSpecifierToNamedExports(fixer, report);
}
else {
yield* fixSeparateNamedExports(fixer, context.sourceCode, report);
}
},
});
}
else {
const exportNames = (0, util_1.formatWordList)(allExportNames);
context.report({
node: report.node,
messageId: 'multipleExportsAreTypes',
data: { exportNames },
*fix(fixer) {
if (fixMixedExportsWithInlineTypeSpecifier) {
yield* fixAddTypeSpecifierToNamedExports(fixer, report);
}
else {
yield* fixSeparateNamedExports(fixer, context.sourceCode, report);
}
},
});
}
}
}
},
};
},
});
/**
* Inserts "type" into an export.
*
* Example:
*
* export type { Foo } from 'foo';
* ^^^^
*/
function* fixExportInsertType(fixer, sourceCode, node) {
const exportToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(node), util_1.NullThrowsReasons.MissingToken('export', node.type));
yield fixer.insertTextAfter(exportToken, ' type');
for (const specifier of node.specifiers) {
if (specifier.exportKind === 'type') {
const kindToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(specifier), util_1.NullThrowsReasons.MissingToken('export', specifier.type));
const firstTokenAfter = (0, util_1.nullThrows)(sourceCode.getTokenAfter(kindToken, {
includeComments: true,
}), 'Missing token following the export kind.');
yield fixer.removeRange([kindToken.range[0], firstTokenAfter.range[0]]);
}
}
}
/**
* Separates the exports which mismatch the kind of export the given
* node represents. For example, a type export's named specifiers which
* represent values will be inserted in a separate `export` statement.
*/
function* fixSeparateNamedExports(fixer, sourceCode, report) {
const { node, typeBasedSpecifiers, inlineTypeSpecifiers, valueSpecifiers } = report;
const typeSpecifiers = typeBasedSpecifiers.concat(inlineTypeSpecifiers);
const source = getSourceFromExport(node);
const specifierNames = typeSpecifiers.map(getSpecifierText).join(', ');
const exportToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(node), util_1.NullThrowsReasons.MissingToken('export', node.type));
// Filter the bad exports from the current line.
const filteredSpecifierNames = valueSpecifiers
.map(getSpecifierText)
.join(', ');
const openToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(node, util_1.isOpeningBraceToken), util_1.NullThrowsReasons.MissingToken('{', node.type));
const closeToken = (0, util_1.nullThrows)(sourceCode.getLastToken(node, util_1.isClosingBraceToken), util_1.NullThrowsReasons.MissingToken('}', node.type));
// Remove exports from the current line which we're going to re-insert.
yield fixer.replaceTextRange([openToken.range[1], closeToken.range[0]], ` ${filteredSpecifierNames} `);
// Insert the bad exports into a new export line above.
yield fixer.insertTextBefore(exportToken, `export type { ${specifierNames} }${source ? ` from '${source}'` : ''};\n`);
}
function* fixAddTypeSpecifierToNamedExports(fixer, report) {
if (report.node.exportKind === 'type') {
return;
}
for (const specifier of report.typeBasedSpecifiers) {
yield fixer.insertTextBefore(specifier, 'type ');
}
}
/**
* Returns the source of the export, or undefined if the named export has no source.
*/
function getSourceFromExport(node) {
if (node.source?.type === utils_1.AST_NODE_TYPES.Literal &&
typeof node.source.value === 'string') {
return node.source.value;
}
return undefined;
}
/**
* Returns the specifier text for the export. If it is aliased, we take care to return
* the proper formatting.
*/
function getSpecifierText(specifier) {
return `${specifier.local.name}${specifier.exported.name !== specifier.local.name
? ` as ${specifier.exported.name}`
: ''}`;
}
//# sourceMappingURL=consistent-type-exports.js.map

View File

@ -0,0 +1,19 @@
'use strict';
var $EvalError = require('es-errors/eval');
var DaysInYear = require('./DaysInYear');
var YearFromTime = require('./YearFromTime');
// https://262.ecma-international.org/5.1/#sec-15.9.1.3
module.exports = function InLeapYear(t) {
var days = DaysInYear(YearFromTime(t));
if (days === 365) {
return 0;
}
if (days === 366) {
return 1;
}
throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days);
};

View File

@ -0,0 +1,27 @@
'use strict';
var $TypeError = require('es-errors/type');
var DefinePropertyOrThrow = require('./DefinePropertyOrThrow');
var IsPropertyKey = require('./IsPropertyKey');
var Type = require('./Type');
// https://262.ecma-international.org/13.0/#sec-createnonenumerabledatapropertyorthrow
module.exports = function CreateNonEnumerableDataPropertyOrThrow(O, P, V) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
}
var newDesc = {
'[[Configurable]]': true,
'[[Enumerable]]': false,
'[[Value]]': V,
'[[Writable]]': true
};
return DefinePropertyOrThrow(O, P, newDesc);
};

View File

@ -0,0 +1,2 @@
import '@unocss/core';
export { a as combineLoaders, b as createCDNFetchLoader, c as createPresetIcons, g as getEnvFlags, i as icons } from './shared/preset-icons.0wSl5XJL.mjs';

View File

@ -0,0 +1,4 @@
import type * as vscode from '@volar/language-service';
import type { SharedContext } from '../types';
export declare function register(ctx: SharedContext): (uri: string, position: vscode.Position, referenceContext: vscode.ReferenceContext) => vscode.Location[];
//# sourceMappingURL=references.d.ts.map

View File

@ -0,0 +1,42 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.2](https://github.com/inspect-js/has-tostringtag/compare/v1.0.1...v1.0.2) - 2024-02-01
### Fixed
- [Fix] move `has-symbols` back to prod deps [`#3`](https://github.com/inspect-js/has-tostringtag/issues/3)
## [v1.0.1](https://github.com/inspect-js/has-tostringtag/compare/v1.0.0...v1.0.1) - 2024-02-01
### Commits
- [patch] add types [`9276414`](https://github.com/inspect-js/has-tostringtag/commit/9276414b22fab3eeb234688841722c4be113201f)
- [meta] use `npmignore` to autogenerate an npmignore file [`5c0dcd1`](https://github.com/inspect-js/has-tostringtag/commit/5c0dcd1ff66419562a30d1fd88b966cc36bce5fc)
- [actions] reuse common workflows [`dee9509`](https://github.com/inspect-js/has-tostringtag/commit/dee950904ab5719b62cf8d73d2ac950b09093266)
- [actions] update codecov uploader [`b8cb3a0`](https://github.com/inspect-js/has-tostringtag/commit/b8cb3a0b8ffbb1593012c4c2daa45fb25642825d)
- [Tests] generate coverage [`be5b288`](https://github.com/inspect-js/has-tostringtag/commit/be5b28889e2735cdbcef387f84c2829995f2f05e)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`69a0827`](https://github.com/inspect-js/has-tostringtag/commit/69a0827974e9b877b2c75b70b057555da8f25a65)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`4c9e210`](https://github.com/inspect-js/has-tostringtag/commit/4c9e210a5682f0557a3235d36b68ce809d7fb825)
- [actions] update rebase action to use reusable workflow [`ca8dcd3`](https://github.com/inspect-js/has-tostringtag/commit/ca8dcd3a6f3f5805d7e3fd461b654aedba0946e7)
- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`07f3eaf`](https://github.com/inspect-js/has-tostringtag/commit/07f3eafa45dd98208c94479737da77f9a69b94c4)
- [Deps] update `has-symbols` [`999e009`](https://github.com/inspect-js/has-tostringtag/commit/999e0095a7d1749a58f55472ec8bf8108cdfdcf3)
- [Tests] remove staging tests since they fail on modern node [`9d9526b`](https://github.com/inspect-js/has-tostringtag/commit/9d9526b1dc1ca7f2292b52efda4c3d857b0e39bd)
## v1.0.0 - 2021-08-05
### Commits
- Tests [`6b6f573`](https://github.com/inspect-js/has-tostringtag/commit/6b6f5734dc2058badb300ff0783efdad95fe1a65)
- Initial commit [`2f8190e`](https://github.com/inspect-js/has-tostringtag/commit/2f8190e799fac32ba9b95a076c0255e01d7ce475)
- [meta] do not publish github action workflow files [`6e08cc4`](https://github.com/inspect-js/has-tostringtag/commit/6e08cc4e0fea7ec71ef66e70734b2af2c4a8b71b)
- readme [`94bed6c`](https://github.com/inspect-js/has-tostringtag/commit/94bed6c9560cbbfda034f8d6c260bb7b0db33c1a)
- npm init [`be67840`](https://github.com/inspect-js/has-tostringtag/commit/be67840ab92ee7adb98bcc65261975543f815fa5)
- Implementation [`c4914ec`](https://github.com/inspect-js/has-tostringtag/commit/c4914ecc51ddee692c85b471ae0a5d8123030fbf)
- [meta] use `auto-changelog` [`4aaf768`](https://github.com/inspect-js/has-tostringtag/commit/4aaf76895ae01d7b739f2b19f967ef2372506cd7)
- Only apps should have lockfiles [`bc4d99e`](https://github.com/inspect-js/has-tostringtag/commit/bc4d99e4bf494afbaa235c5f098df6e642edf724)
- [meta] add `safe-publish-latest` [`6523c05`](https://github.com/inspect-js/has-tostringtag/commit/6523c05c9b87140f3ae74c9daf91633dd9ff4e1f)

View File

@ -0,0 +1,74 @@
{
"name": "@astrojs/language-server",
"version": "2.7.4",
"author": "withastro",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/withastro/language-tools",
"directory": "packages/language-server"
},
"type": "commonjs",
"main": "dist/index.js",
"files": [
"bin",
"dist/**/*.js",
"dist/**/*.d.ts",
"types/**/*.d.ts"
],
"bin": {
"astro-ls": "./bin/nodeServer.js"
},
"dependencies": {
"@astrojs/compiler": "^2.4.0",
"@jridgewell/sourcemap-codec": "^1.4.15",
"@volar/kit": "~2.0.4",
"@volar/language-core": "~2.0.4",
"@volar/language-server": "~2.0.4",
"@volar/language-service": "~2.0.4",
"@volar/typescript": "~2.0.4",
"fast-glob": "^3.2.12",
"volar-service-css": "0.0.29",
"volar-service-emmet": "0.0.29",
"volar-service-html": "0.0.29",
"volar-service-prettier": "0.0.29",
"volar-service-typescript": "0.0.29",
"volar-service-typescript-twoslash-queries": "0.0.29",
"vscode-html-languageservice": "^5.1.2",
"vscode-uri": "^3.0.8"
},
"devDependencies": {
"svelte": "^4.2.10",
"@astrojs/svelte": "^5.0.3",
"@astrojs/vue": "^4.0.8",
"@types/chai": "^4.3.5",
"@types/mocha": "^10.0.1",
"@types/node": "^18.17.8",
"@volar/test-utils": "~2.0.4",
"astro": "^4.3.5",
"chai": "^4.3.7",
"mocha": "^10.2.0",
"tsx": "^3.12.7",
"typescript": "^5.2.2",
"vscode-languageserver-protocol": "^3.17.5",
"vscode-languageserver-textdocument": "^1.0.11"
},
"peerDependencies": {
"prettier": "^3.0.0",
"prettier-plugin-astro": ">=0.11.0"
},
"peerDependenciesMeta": {
"prettier": {
"optional": true
},
"prettier-plugin-astro": {
"optional": true
}
},
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"test": "mocha --timeout 10000 --require tsx --require test/takedown.ts test/misc/init.test.ts test/**/*.test.ts",
"test:match": "pnpm run test -g"
}
}

View File

@ -0,0 +1,5 @@
import type { ParseResult } from '@astrojs/compiler/types';
import { type VirtualCode } from '@volar/language-core';
import type ts from 'typescript';
import type { HTMLDocument } from 'vscode-html-languageservice';
export declare function extractScriptTags(snapshot: ts.IScriptSnapshot, htmlDocument: HTMLDocument, ast: ParseResult['ast']): VirtualCode[];

View File

@ -0,0 +1,230 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const regexpp_1 = require("@eslint-community/regexpp");
const utils_1 = require("@typescript-eslint/utils");
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'prefer-includes',
defaultOptions: [],
meta: {
type: 'suggestion',
docs: {
description: 'Enforce `includes` method over `indexOf` method',
recommended: 'strict',
requiresTypeChecking: true,
},
fixable: 'code',
messages: {
preferIncludes: "Use 'includes()' method instead.",
preferStringIncludes: 'Use `String#includes()` method with a string instead.',
},
schema: [],
},
create(context) {
const globalScope = context.sourceCode.getScope(context.sourceCode.ast);
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
function isNumber(node, value) {
const evaluated = (0, util_1.getStaticValue)(node, globalScope);
return evaluated != null && evaluated.value === value;
}
function isPositiveCheck(node) {
switch (node.operator) {
case '!==':
case '!=':
case '>':
return isNumber(node.right, -1);
case '>=':
return isNumber(node.right, 0);
default:
return false;
}
}
function isNegativeCheck(node) {
switch (node.operator) {
case '===':
case '==':
case '<=':
return isNumber(node.right, -1);
case '<':
return isNumber(node.right, 0);
default:
return false;
}
}
function hasSameParameters(nodeA, nodeB) {
if (!ts.isFunctionLike(nodeA) || !ts.isFunctionLike(nodeB)) {
return false;
}
const paramsA = nodeA.parameters;
const paramsB = nodeB.parameters;
if (paramsA.length !== paramsB.length) {
return false;
}
for (let i = 0; i < paramsA.length; ++i) {
const paramA = paramsA[i];
const paramB = paramsB[i];
// Check name, type, and question token once.
if (paramA.getText() !== paramB.getText()) {
return false;
}
}
return true;
}
/**
* Parse a given node if it's a `RegExp` instance.
* @param node The node to parse.
*/
function parseRegExp(node) {
const evaluated = (0, util_1.getStaticValue)(node, globalScope);
if (evaluated == null || !(evaluated.value instanceof RegExp)) {
return null;
}
const { pattern, flags } = (0, regexpp_1.parseRegExpLiteral)(evaluated.value);
if (pattern.alternatives.length !== 1 ||
flags.ignoreCase ||
flags.global) {
return null;
}
// Check if it can determine a unique string.
const chars = pattern.alternatives[0].elements;
if (!chars.every(c => c.type === 'Character')) {
return null;
}
// To string.
return String.fromCodePoint(...chars.map(c => c.value));
}
function escapeString(str) {
const EscapeMap = {
'\0': '\\0',
"'": "\\'",
'\\': '\\\\',
'\n': '\\n',
'\r': '\\r',
'\v': '\\v',
'\t': '\\t',
'\f': '\\f',
// "\b" cause unexpected replacements
// '\b': '\\b',
};
const replaceRegex = new RegExp(Object.values(EscapeMap).join('|'), 'g');
return str.replace(replaceRegex, char => EscapeMap[char]);
}
function checkArrayIndexOf(node, allowFixing) {
// Check if the comparison is equivalent to `includes()`.
const callNode = node.parent;
const compareNode = (callNode.parent.type === utils_1.AST_NODE_TYPES.ChainExpression
? callNode.parent.parent
: callNode.parent);
const negative = isNegativeCheck(compareNode);
if (!negative && !isPositiveCheck(compareNode)) {
return;
}
// Get the symbol of `indexOf` method.
const indexofMethodDeclarations = services
.getSymbolAtLocation(node.property)
?.getDeclarations();
if (indexofMethodDeclarations == null ||
indexofMethodDeclarations.length === 0) {
return;
}
// Check if every declaration of `indexOf` method has `includes` method
// and the two methods have the same parameters.
for (const instanceofMethodDecl of indexofMethodDeclarations) {
const typeDecl = instanceofMethodDecl.parent;
const type = checker.getTypeAtLocation(typeDecl);
const includesMethodDecl = type
.getProperty('includes')
?.getDeclarations();
if (!includesMethodDecl?.some(includesMethodDecl => hasSameParameters(includesMethodDecl, instanceofMethodDecl))) {
return;
}
}
// Report it.
context.report({
node: compareNode,
messageId: 'preferIncludes',
...(allowFixing && {
*fix(fixer) {
if (negative) {
yield fixer.insertTextBefore(callNode, '!');
}
yield fixer.replaceText(node.property, 'includes');
yield fixer.removeRange([callNode.range[1], compareNode.range[1]]);
},
}),
});
}
return {
// a.indexOf(b) !== 1
"BinaryExpression > CallExpression.left > MemberExpression.callee[property.name='indexOf'][computed=false]"(node) {
checkArrayIndexOf(node, /* allowFixing */ true);
},
// a?.indexOf(b) !== 1
"BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name='indexOf'][computed=false]"(node) {
checkArrayIndexOf(node, /* allowFixing */ false);
},
// /bar/.test(foo)
'CallExpression[arguments.length=1] > MemberExpression.callee[property.name="test"][computed=false]'(node) {
const callNode = node.parent;
const text = parseRegExp(node.object);
if (text == null) {
return;
}
//check the argument type of test methods
const argument = callNode.arguments[0];
const type = (0, util_1.getConstrainedTypeAtLocation)(services, argument);
const includesMethodDecl = type
.getProperty('includes')
?.getDeclarations();
if (includesMethodDecl == null) {
return;
}
context.report({
node: callNode,
messageId: 'preferStringIncludes',
*fix(fixer) {
const argNode = callNode.arguments[0];
const needsParen = argNode.type !== utils_1.AST_NODE_TYPES.Literal &&
argNode.type !== utils_1.AST_NODE_TYPES.TemplateLiteral &&
argNode.type !== utils_1.AST_NODE_TYPES.Identifier &&
argNode.type !== utils_1.AST_NODE_TYPES.MemberExpression &&
argNode.type !== utils_1.AST_NODE_TYPES.CallExpression;
yield fixer.removeRange([callNode.range[0], argNode.range[0]]);
yield fixer.removeRange([argNode.range[1], callNode.range[1]]);
if (needsParen) {
yield fixer.insertTextBefore(argNode, '(');
yield fixer.insertTextAfter(argNode, ')');
}
yield fixer.insertTextAfter(argNode, `${node.optional ? '?.' : '.'}includes('${escapeString(text)}')`);
},
});
},
};
},
});
//# sourceMappingURL=prefer-includes.js.map

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Jordan Harband
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,266 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.astroDirectives = exports.astroAttributes = exports.astroElements = exports.classListAttribute = void 0;
const vscode_html_languageservice_1 = require("vscode-html-languageservice");
const defaultProvider = (0, vscode_html_languageservice_1.getDefaultHTMLDataProvider)();
const slotAttr = defaultProvider.provideAttributes('div').find((attr) => attr.name === 'slot');
exports.classListAttribute = (0, vscode_html_languageservice_1.newHTMLDataProvider)('class-list', {
version: 1,
globalAttributes: [
{
name: 'class:list',
description: 'Utility to provide a list of class',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#classlist',
},
],
},
],
});
exports.astroElements = (0, vscode_html_languageservice_1.newHTMLDataProvider)('astro-elements', {
version: 1,
tags: [
{
name: 'slot',
description: 'The slot element is a placeholder for external HTML content, allowing you to inject (or “slot”) child elements from other files into your component template.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/core-concepts/astro-components/#slots',
},
],
attributes: [
{
name: 'name',
description: 'The name attribute allows you to pass only HTML elements with the corresponding slot name into a slots location.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/core-concepts/astro-components/#named-slots',
},
],
},
],
},
{
name: 'script',
attributes: [
{
// The VS Code tag definitions does not provide a description for the deprecated `charset` attribute on script tags
// Which mean that since we get no hover info for this, we instead get JSX hover info. So we'll just specify a description ourselves for this specific case
name: 'charset',
description: "**Deprecated**\n\nIt's unnecessary to specify the charset attribute, because documents must use UTF-8, and the script element inherits its character encoding from the document.",
},
{
name: 'define:vars',
description: 'Passes serializable server-side variables into a client-side script element',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#definevars',
},
],
},
{
name: 'hoist',
description: '**Deprecated in Astro >= 0.26.0**\n\nBuilds, optimizes, and bundles your script with the other JavaScript on the page',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/core-concepts/astro-components/#using-hoisted-scripts',
},
],
},
{
name: 'is:inline',
description: 'Leave a script tag inline in the page template. No processing will be done on its content',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isinline',
},
],
},
],
},
{
name: 'style',
attributes: [
{
name: 'define:vars',
description: 'Passes serializable server-side variables into a client-side style element',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#definevars',
},
],
},
{
name: 'global',
description: '**Deprecated in favor of `is:global` in >= Astro 0.26.0**\n\nOpts-out of automatic CSS scoping, all contents will be available globally',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isglobal',
},
],
},
{
name: 'is:global',
description: 'Opts-out of automatic CSS scoping, all contents will be available globally',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isglobal',
},
],
},
{
name: 'is:inline',
description: 'Leave a style tag inline in the page template. No processing will be done on its content',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#isinline',
},
],
},
],
},
],
});
exports.astroAttributes = (0, vscode_html_languageservice_1.newHTMLDataProvider)('astro-attributes', {
version: 1,
globalAttributes: [
{
name: 'set:html',
description: 'Inject unescaped HTML into this tag',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#sethtml',
},
],
},
{
name: 'set:text',
description: 'Inject escaped text into this tag',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#settext',
},
],
},
{
name: 'is:raw',
description: 'Instructs the Astro compiler to treat any children of this element as text',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#israw',
},
],
},
{
name: 'transition:animate',
description: 'Specifies an animation to use with this element on page transition.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/guides/view-transitions/#transition-directives',
},
],
},
{
name: 'transition:name',
description: 'Specifies a `view-transition-name` for this element. The name must be unique on the page.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/guides/view-transitions/#transition-directives',
},
],
},
{
name: 'transition:persist',
description: 'Marks this element to be moved to the next page during view transitions.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/guides/view-transitions/#transition-directives',
},
],
},
slotAttr,
],
});
exports.astroDirectives = (0, vscode_html_languageservice_1.newHTMLDataProvider)('astro-directives', {
version: 1,
globalAttributes: [
{
name: 'client:load',
description: 'Start importing the component JS at page load. Hydrate the component when import completes.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientload',
},
],
},
{
name: 'client:idle',
description: 'Start importing the component JS as soon as main thread is free (uses requestIdleCallback()). Hydrate the component when import completes.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientidle',
},
],
},
{
name: 'client:visible',
description: 'Start importing the component JS as soon as the element enters the viewport (uses IntersectionObserver). Hydrate the component when import completes. Useful for content lower down on the page.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientvisible',
},
],
},
{
name: 'client:media',
description: 'Start importing the component JS as soon as the browser matches the given media query (uses matchMedia). Hydrate the component when import completes. Useful for sidebar toggles, or other elements that should only display on mobile or desktop devices.',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientmedia',
},
],
},
{
name: 'client:only',
description: 'Start importing the component JS at page load and hydrate when the import completes, similar to client:load. The component will be skipped at build time, useful for components that are entirely dependent on client-side APIs. This is best avoided unless absolutely needed, in most cases it is best to render placeholder content on the server and delay any browser API calls until the component hydrates in the browser.',
valueSet: 'v',
references: [
{
name: 'Astro reference',
url: 'https://docs.astro.build/en/reference/directives-reference/#clientonly',
},
],
},
],
});
//# sourceMappingURL=html-data.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"block-spacing.js","sourceRoot":"","sources":["../../src/rules/block-spacing.ts"],"names":[],"mappings":";;AACA,oDAA2D;AAM3D,kCAAwD;AACxD,iEAA8D;AAE9D,MAAM,QAAQ,GAAG,IAAA,qCAAiB,EAAC,eAAe,CAAC,CAAC;AAKpD,kBAAe,IAAA,iBAAU,EAAsB;IAC7C,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE;QACJ,UAAU,EAAE,IAAI;QAChB,UAAU,EAAE,CAAC,6BAA6B,CAAC;QAC3C,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE;YACJ,WAAW,EACT,0FAA0F;YAC5F,eAAe,EAAE,IAAI;SACtB;QACD,OAAO,EAAE,YAAY;QACrB,cAAc,EAAE,QAAQ,CAAC,IAAI,CAAC,cAAc;QAC5C,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,MAAM;QAC5B,QAAQ,EAAE,QAAQ,CAAC,IAAI,CAAC,QAAQ;KACjC;IACD,cAAc,EAAE,CAAC,QAAQ,CAAC;IAE1B,MAAM,CAAC,OAAO,EAAE,CAAC,iBAAiB,CAAC;QACjC,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC3C,MAAM,MAAM,GAAG,iBAAiB,KAAK,OAAO,CAAC;QAC7C,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;QAC/C;;;WAGG;QACH,SAAS,YAAY,CACnB,IAAgC;YAEhC,uBAAuB;YACvB,uDAAuD;YACvD,OAAO,OAAO,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,EAAE;gBAC5C,MAAM,EAAE,KAAK,CAAC,EAAE,CACd,KAAK,CAAC,IAAI,KAAK,uBAAe,CAAC,UAAU,IAAI,KAAK,CAAC,KAAK,KAAK,GAAG;aACnE,CAA6B,CAAC;QACjC,CAAC;QAED;;;;;;;;;;WAUG;QACH,SAAS,OAAO,CAAC,IAAoB,EAAE,KAAqB;YAC1D,OAAO,CACL,CAAC,IAAA,wBAAiB,EAAC,IAAI,EAAE,KAAK,CAAC;gBAC/B,OAAO,CAAC,UAAU,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,MAAM,CAC1D,CAAC;QACJ,CAAC;QAED;;WAEG;QACH,SAAS,wBAAwB,CAAC,IAAgC;YAChE,mDAAmD;YACnD,MAAM,SAAS,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;YACrC,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CAAE,CAAC;YAC1D,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,aAAa,CAAC,SAAS,EAAE;gBAC7D,eAAe,EAAE,IAAI;aACtB,CAAE,CAAC;YACJ,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,cAAc,CAAC,UAAU,EAAE;gBAC9D,eAAe,EAAE,IAAI;aACtB,CAAE,CAAC;YAEJ,wCAAwC;YACxC,IACE,SAAS,CAAC,KAAK,KAAK,GAAG;gBACvB,UAAU,CAAC,IAAI,KAAK,uBAAe,CAAC,UAAU;gBAC9C,UAAU,CAAC,KAAK,KAAK,GAAG;gBACxB,UAAU,KAAK,UAAU,EACzB,CAAC;gBACD,OAAO;YACT,CAAC;YAED,sCAAsC;YACtC,IAAI,CAAC,MAAM,IAAI,UAAU,CAAC,IAAI,KAAK,uBAAe,CAAC,IAAI,EAAE,CAAC;gBACxD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,UAAU,CAAC,EAAE,CAAC;gBACpC,IAAI,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC;gBAExB,IAAI,SAAS,KAAK,OAAO,EAAE,CAAC;oBAC1B,GAAG,GAAG;wBACJ,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG;wBACxB,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,KAAK;qBAC1B,CAAC;gBACJ,CAAC;gBAED,OAAO,CAAC,MAAM,CAAC;oBACb,IAAI;oBACJ,GAAG;oBACH,SAAS;oBACT,IAAI,EAAE;wBACJ,QAAQ,EAAE,OAAO;wBACjB,KAAK,EAAE,SAAS,CAAC,KAAK;qBACvB;oBACD,GAAG,CAAC,KAAK;wBACP,IAAI,MAAM,EAAE,CAAC;4BACX,OAAO,KAAK,CAAC,gBAAgB,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;wBACjD,CAAC;wBAED,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBACtE,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;YACD,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,UAAU,CAAC,EAAE,CAAC;gBACpC,IAAI,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC;gBAEzB,IAAI,SAAS,KAAK,OAAO,EAAE,CAAC;oBAC1B,GAAG,GAAG;wBACJ,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG;wBACxB,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,KAAK;qBAC1B,CAAC;gBACJ,CAAC;gBACD,OAAO,CAAC,MAAM,CAAC;oBACb,IAAI;oBACJ,GAAG;oBACH,SAAS;oBACT,IAAI,EAAE;wBACJ,QAAQ,EAAE,QAAQ;wBAClB,KAAK,EAAE,UAAU,CAAC,KAAK;qBACxB;oBACD,GAAG,CAAC,KAAK;wBACP,IAAI,MAAM,EAAE,CAAC;4BACX,OAAO,KAAK,CAAC,eAAe,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;wBAC/C,CAAC;wBAED,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBACtE,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,OAAO;YACL,GAAG,SAAS;YAEZ,mEAAmE;YACnE,mIAAmI;YACnI,wFAAwF;YACxF,sEAAsE;YACtE,eAAe,EAAE,SAAS,CAAC,cAAuB;YAClD,aAAa,EAAE,SAAS,CAAC,cAAuB;YAChD,iBAAiB,EAAE,wBAAwB;SAC5C,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}

View File

@ -0,0 +1,25 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $BigInt = GetIntrinsic('%BigInt%', true);
var $RangeError = require('es-errors/range');
var $SyntaxError = require('es-errors/syntax');
var $TypeError = require('es-errors/type');
var IsIntegralNumber = require('./IsIntegralNumber');
// https://262.ecma-international.org/12.0/#sec-numbertobigint
module.exports = function NumberToBigInt(number) {
if (typeof number !== 'number') {
throw new $TypeError('Assertion failed: `number` must be a String');
}
if (!IsIntegralNumber(number)) {
throw new $RangeError('The number ' + number + ' cannot be converted to a BigInt because it is not an integer');
}
if (!$BigInt) {
throw new $SyntaxError('BigInts are not supported in this environment');
}
return $BigInt(number);
};

View File

@ -0,0 +1,89 @@
import type { ParserServices, TSESTree } from '../ts-estree';
import type { ParserOptions } from './ParserOptions';
import type { Scope } from './Scope';
export declare namespace Parser {
interface ParserMeta {
/**
* The unique name of the parser.
*/
name: string;
/**
* The a string identifying the version of the parser.
*/
version?: string;
}
/**
* A loose definition of the ParserModule type for use with configs
* This type intended to relax validation of configs so that parsers that have
* different AST types or scope managers can still be passed to configs
*/
type LooseParserModule = {
/**
* Information about the parser to uniquely identify it when serializing.
*/
meta?: ParserMeta;
/**
* Parses the given text into an ESTree AST
*/
parse(text: string, options?: unknown): unknown;
} | {
/**
* Information about the parser to uniquely identify it when serializing.
*/
meta?: ParserMeta;
/**
* Parses the given text into an AST
*/
parseForESLint(text: string, options?: unknown): {
[k in keyof ParseResult]: unknown;
};
};
type ParserModule = {
/**
* Information about the parser to uniquely identify it when serializing.
*/
meta?: ParserMeta;
/**
* Parses the given text into an ESTree AST
*/
parse(text: string, options?: ParserOptions): TSESTree.Program;
} | {
/**
* Information about the parser to uniquely identify it when serializing.
*/
meta?: ParserMeta;
/**
* Parses the given text into an AST
*/
parseForESLint(text: string, options?: ParserOptions): ParseResult;
};
interface ParseResult {
/**
* The ESTree AST
*/
ast: TSESTree.Program;
/**
* Any parser-dependent services (such as type checkers for nodes).
* The value of the services property is available to rules as `context.sourceCode.parserServices`.
* The default is an empty object.
*/
services?: ParserServices;
/**
* A `ScopeManager` object.
* Custom parsers can use customized scope analysis for experimental/enhancement syntaxes.
* The default is the `ScopeManager` object which is created by `eslint-scope`.
*/
scopeManager?: Scope.ScopeManager;
/**
* An object to customize AST traversal.
* The keys of the object are the type of AST nodes.
* Each value is an array of the property names which should be traversed.
* The default is `KEYS` of `eslint-visitor-keys`.
*/
visitorKeys?: VisitorKeys;
}
interface VisitorKeys {
[nodeType: string]: readonly string[];
}
}
//# sourceMappingURL=Parser.d.ts.map

View File

@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../util");
const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-loss-of-precision');
exports.default = (0, util_1.createRule)({
name: 'no-loss-of-precision',
meta: {
type: 'problem',
docs: {
description: 'Disallow literal numbers that lose precision',
recommended: 'recommended',
extendsBaseRule: true,
},
hasSuggestions: baseRule.meta.hasSuggestions,
schema: [],
messages: baseRule.meta.messages,
},
defaultOptions: [],
create(context) {
const rules = baseRule.create(context);
function isSeparatedNumeric(node) {
return typeof node.value === 'number' && node.raw.includes('_');
}
return {
Literal(node) {
rules.Literal({
...node,
raw: isSeparatedNumeric(node) ? node.raw.replace(/_/g, '') : node.raw,
});
},
};
},
});
//# sourceMappingURL=no-loss-of-precision.js.map

View File

@ -0,0 +1,15 @@
'use strict';
// eslint-disable-next-line consistent-return
module.exports = /** @type {(t: import('tape').Test) => void | false} */ function runSymbolTests(t) {
t.equal(typeof Symbol, 'function', 'global Symbol is a function');
t.ok(Symbol.toStringTag, 'Symbol.toStringTag exists');
if (typeof Symbol !== 'function' || !Symbol.toStringTag) { return false; }
/** @type {{ [Symbol.toStringTag]?: 'test'}} */
var obj = {};
obj[Symbol.toStringTag] = 'test';
t.equal(Object.prototype.toString.call(obj), '[object test]');
};

View File

@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.register = void 0;
const PConst = require("../protocol.const");
const shared_1 = require("../shared");
const modifiers_1 = require("../utils/modifiers");
const getSymbolKind = (kind) => {
switch (kind) {
case PConst.Kind.module: return 2;
case PConst.Kind.class: return 5;
case PConst.Kind.enum: return 10;
case PConst.Kind.interface: return 11;
case PConst.Kind.method: return 6;
case PConst.Kind.memberVariable: return 7;
case PConst.Kind.memberGetAccessor: return 7;
case PConst.Kind.memberSetAccessor: return 7;
case PConst.Kind.variable: return 13;
case PConst.Kind.const: return 13;
case PConst.Kind.localVariable: return 13;
case PConst.Kind.function: return 12;
case PConst.Kind.localFunction: return 12;
case PConst.Kind.constructSignature: return 9;
case PConst.Kind.constructorImplementation: return 9;
}
return 13;
};
function register(ctx) {
return (uri) => {
const document = ctx.getTextDocument(uri);
if (!document)
return [];
const fileName = ctx.uriToFileName(document.uri);
const barItems = (0, shared_1.safeCall)(() => ctx.languageService.getNavigationTree(fileName));
if (!barItems)
return [];
// The root represents the file. Ignore this when showing in the UI
const result = barItems.childItems
?.map(function convertNavTree(item) {
if (!shouldIncludeEntry(item)) {
return [];
}
let remain = item.childItems ?? [];
return item.spans.map(span => {
const childItems = [];
remain = remain.filter(child => {
const childStart = child.spans[0].start;
const childEnd = child.spans[child.spans.length - 1].start + child.spans[child.spans.length - 1].length;
if (childStart >= span.start && childEnd <= span.start + span.length) {
childItems.push(child);
return false;
}
return true;
});
const nameSpan = item.spans.length === 1
? (item.nameSpan ?? span)
: span;
const fullRange = {
start: Math.min(span.start, nameSpan.start),
end: Math.max(span.start + span.length, nameSpan.start + nameSpan.length),
};
const symbol = {
name: item.text,
kind: getSymbolKind(item.kind),
range: {
start: document.positionAt(fullRange.start),
end: document.positionAt(fullRange.end),
},
selectionRange: {
start: document.positionAt(nameSpan.start),
end: document.positionAt(nameSpan.start + nameSpan.length),
},
children: childItems.map(convertNavTree).flat(),
};
const kindModifiers = (0, modifiers_1.parseKindModifier)(item.kindModifiers);
if (kindModifiers.has(PConst.KindModifiers.deprecated)) {
symbol.deprecated = true;
symbol.tags ??= [];
symbol.tags.push(1);
}
return symbol;
});
})
.flat();
return result ?? [];
function shouldIncludeEntry(item) {
if (item.kind === PConst.Kind.alias) {
return false;
}
return !!(item.text && item.text !== '<function>' && item.text !== '<class>');
}
};
}
exports.register = register;
//# sourceMappingURL=documentSymbol.js.map

View File

@ -0,0 +1,9 @@
import type * as vscode from 'vscode-languageserver-protocol';
import type { ServiceContext } from '../types';
export interface ServiceCodeActionData {
uri: string;
version: number;
original: Pick<vscode.CodeAction, 'data' | 'edit'>;
serviceIndex: number;
}
export declare function register(context: ServiceContext): (uri: string, range: vscode.Range, codeActionContext: vscode.CodeActionContext, token?: vscode.CancellationToken) => Promise<vscode.CodeAction[] | undefined>;

View File

@ -0,0 +1,162 @@
import { B as BaseCoverageOptions, a as ResolvedCoverageOptions } from './reporters-1evA5lom.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,113 @@
'use strict';
var forEach = require('for-each');
var availableTypedArrays = require('available-typed-arrays');
var callBind = require('call-bind');
var callBound = require('call-bind/callBound');
var gOPD = require('gopd');
var $toString = callBound('Object.prototype.toString');
var hasToStringTag = require('has-tostringtag/shams')();
var g = typeof globalThis === 'undefined' ? global : globalThis;
var typedArrays = availableTypedArrays();
var $slice = callBound('String.prototype.slice');
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
var $indexOf = callBound('Array.prototype.indexOf', true) || /** @type {(array: readonly unknown[], value: unknown) => keyof array} */ function indexOf(array, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value) {
return i;
}
}
return -1;
};
/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array} TypedArray */
/** @typedef {'Int8Array' | 'Uint8Array' | 'Uint8ClampedArray' | 'Int16Array' | 'Uint16Array' | 'Int32Array' | 'Uint32Array' | 'Float32Array' | 'Float64Array' | 'BigInt64Array' | 'BigUint64Array'} TypedArrayName */
/** @type {{ [k in `\$${TypedArrayName}`]?: (receiver: TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call } & { __proto__: null }} */
var cache = { __proto__: null };
if (hasToStringTag && gOPD && getPrototypeOf) {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
if (Symbol.toStringTag in arr) {
var proto = getPrototypeOf(arr);
// @ts-expect-error TS won't narrow inside a closure
var descriptor = gOPD(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
// @ts-expect-error TS won't narrow inside a closure
descriptor = gOPD(superProto, Symbol.toStringTag);
}
// @ts-expect-error TODO: fix
cache['$' + typedArray] = callBind(descriptor.get);
}
});
} else {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
var fn = arr.slice || arr.set;
if (fn) {
// @ts-expect-error TODO: fix
cache['$' + typedArray] = callBind(fn);
}
});
}
/** @type {import('.')} */
var tryTypedArrays = function tryAllTypedArrays(value) {
/** @type {ReturnType<tryAllTypedArrays>} */ var found = false;
forEach(
// eslint-disable-next-line no-extra-parens
/** @type {Record<`\$${TypedArrayName}`, typeof cache>} */ /** @type {any} */ (cache),
/** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */ function (getter, typedArray) {
if (!found) {
try {
// @ts-expect-error TODO: fix
if ('$' + getter(value) === typedArray) {
found = $slice(typedArray, 1);
}
} catch (e) { /**/ }
}
}
);
return found;
};
/** @type {import('.')} */
var trySlices = function tryAllSlices(value) {
/** @type {ReturnType<tryAllSlices>} */ var found = false;
forEach(
// eslint-disable-next-line no-extra-parens
/** @type {any} */ (cache),
/** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */ function (getter, name) {
if (!found) {
try {
// @ts-expect-error TODO: fix
getter(value);
found = $slice(name, 1);
} catch (e) { /**/ }
}
}
);
return found;
};
/** @type {import('.')} */
module.exports = function whichTypedArray(value) {
if (!value || typeof value !== 'object') { return false; }
if (!hasToStringTag) {
var tag = $slice($toString(value), 8, -1);
if ($indexOf(typedArrays, tag) > -1) {
return tag;
}
if (tag !== 'Object') {
return false;
}
// node < 0.6 hits here on real Typed Arrays
return trySlices(value);
}
if (!gOPD) { return null; } // unknown engine
return tryTypedArrays(value);
};

View File

@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'prefer-namespace-keyword',
meta: {
type: 'suggestion',
docs: {
description: 'Require using `namespace` keyword over `module` keyword to declare custom TypeScript modules',
recommended: 'stylistic',
},
fixable: 'code',
messages: {
useNamespace: "Use 'namespace' instead of 'module' to declare custom TypeScript modules.",
},
schema: [],
},
defaultOptions: [],
create(context) {
return {
TSModuleDeclaration(node) {
// Do nothing if the name is a string.
if (node.id.type === utils_1.AST_NODE_TYPES.Literal) {
return;
}
// Get tokens of the declaration header.
const moduleType = context.sourceCode.getTokenBefore(node.id);
if (moduleType &&
moduleType.type === utils_1.AST_TOKEN_TYPES.Identifier &&
moduleType.value === 'module') {
context.report({
node,
messageId: 'useNamespace',
fix(fixer) {
return fixer.replaceText(moduleType, 'namespace');
},
});
}
},
};
},
});
//# sourceMappingURL=prefer-namespace-keyword.js.map

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-1evA5lom.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-1evA5lom.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,22 @@
'use strict';
var $TypeError = require('es-errors/type');
var ToInt32 = require('../ToInt32');
var ToUint32 = require('../ToUint32');
var modulo = require('../modulo');
// https://262.ecma-international.org/12.0/#sec-numeric-types-number-signedRightShift
module.exports = function NumberSignedRightShift(x, y) {
if (typeof x !== 'number' || typeof y !== 'number') {
throw new $TypeError('Assertion failed: `x` and `y` arguments must be Numbers');
}
var lnum = ToInt32(x);
var rnum = ToUint32(y);
var shiftCount = modulo(rnum, 32);
return lnum >> shiftCount;
};

View File

@ -0,0 +1,43 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $Number = GetIntrinsic('%Number%');
var $RegExp = GetIntrinsic('%RegExp%');
var $TypeError = require('es-errors/type');
var $parseInteger = GetIntrinsic('%parseInt%');
var callBound = require('call-bind/callBound');
var regexTester = require('safe-regex-test');
var $strSlice = callBound('String.prototype.slice');
var isBinary = regexTester(/^0b[01]+$/i);
var isOctal = regexTester(/^0o[0-7]+$/i);
var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
var hasNonWS = regexTester(nonWSregex);
var $trim = require('string.prototype.trim');
// https://262.ecma-international.org/13.0/#sec-stringtonumber
module.exports = function StringToNumber(argument) {
if (typeof argument !== 'string') {
throw new $TypeError('Assertion failed: `argument` is not a String');
}
if (isBinary(argument)) {
return $Number($parseInteger($strSlice(argument, 2), 2));
}
if (isOctal(argument)) {
return $Number($parseInteger($strSlice(argument, 2), 8));
}
if (hasNonWS(argument) || isInvalidHexLiteral(argument)) {
return NaN;
}
var trimmed = $trim(argument);
if (trimmed !== argument) {
return StringToNumber(trimmed);
}
return $Number(argument);
};

View File

@ -0,0 +1,61 @@
import { type LanguageContext } from '@volar/language-core';
import type * as vscode from 'vscode-languageserver-protocol';
import type { ServiceContext, ServiceEnvironment, ServicePlugin } from './types';
export type LanguageService = ReturnType<typeof createLanguageService>;
export declare function createLanguageService(languageContext: LanguageContext, servicePlugins: ServicePlugin[], env: ServiceEnvironment): {
getTriggerCharacters: () => string[];
getAutoFormatTriggerCharacters: () => string[];
getSignatureHelpTriggerCharacters: () => string[];
getSignatureHelpRetriggerCharacters: () => string[];
format: (uri: string, options: vscode.FormattingOptions, range: vscode.Range | undefined, onTypeParams: {
ch: string;
position: vscode.Position;
} | undefined, token?: vscode.CancellationToken) => Promise<vscode.TextEdit[] | undefined>;
getFoldingRanges: (uri: string, token?: vscode.CancellationToken) => Promise<vscode.FoldingRange[] | undefined>;
getSelectionRanges: (uri: string, positions: vscode.Position[], token?: vscode.CancellationToken) => Promise<vscode.SelectionRange[] | undefined>;
findLinkedEditingRanges: (uri: string, position: vscode.Position, token?: vscode.CancellationToken) => Promise<vscode.LinkedEditingRanges | undefined>;
findDocumentSymbols: (uri: string, token?: vscode.CancellationToken) => Promise<vscode.DocumentSymbol[] | undefined>;
findDocumentColors: (uri: string, token?: vscode.CancellationToken) => Promise<vscode.ColorInformation[] | undefined>;
getColorPresentations: (uri: string, color: vscode.Color, range: vscode.Range, token?: vscode.CancellationToken) => Promise<vscode.ColorPresentation[] | undefined>;
doValidation: (uri: string, token?: vscode.CancellationToken, response?: ((result: vscode.Diagnostic[]) => void) | undefined) => Promise<vscode.Diagnostic[]>;
findReferences: (uri: string, position: vscode.Position, referenceContext: vscode.ReferenceContext, token?: vscode.CancellationToken) => Promise<vscode.Location[] | undefined>;
findFileReferences: (uri: string, token?: vscode.CancellationToken) => import("./types").NullableResult<vscode.Location[]>;
findDefinition: (uri: string, position: vscode.Position, token?: vscode.CancellationToken) => Promise<vscode.LocationLink[] | undefined>;
findTypeDefinition: (uri: string, position: vscode.Position, token?: vscode.CancellationToken) => Promise<vscode.LocationLink[] | undefined>;
findImplementations: (uri: string, position: vscode.Position, token?: vscode.CancellationToken) => Promise<vscode.LocationLink[] | undefined>;
prepareRename: (uri: string, position: vscode.Position, token?: vscode.CancellationToken) => Promise<vscode.Range | {
range: vscode.Range;
placeholder: string;
} | {
message: string;
} | undefined>;
doRename: (uri: string, position: vscode.Position, newName: string, token?: vscode.CancellationToken) => Promise<vscode.WorkspaceEdit | undefined>;
getEditsForFileRename: (oldUri: string, newUri: string, token?: vscode.CancellationToken) => Promise<vscode.WorkspaceEdit | undefined>;
getSemanticTokens: (uri: string, range: vscode.Range | undefined, legend: vscode.SemanticTokensLegend, token?: vscode.CancellationToken, _reportProgress?: ((tokens: vscode.SemanticTokens) => void) | undefined) => Promise<vscode.SemanticTokens | undefined>;
doHover: (uri: string, position: vscode.Position, token?: vscode.CancellationToken) => Promise<vscode.Hover | undefined>;
doComplete: (uri: string, position: vscode.Position, completionContext?: vscode.CompletionContext, token?: vscode.CancellationToken) => Promise<vscode.CompletionList>;
doCodeActions: (uri: string, range: vscode.Range, codeActionContext: vscode.CodeActionContext, token?: vscode.CancellationToken) => Promise<vscode.CodeAction[] | undefined>;
doCodeActionResolve: (item: vscode.CodeAction, token?: vscode.CancellationToken) => Promise<vscode.CodeAction>;
doCompletionResolve: (item: vscode.CompletionItem, token?: vscode.CancellationToken) => Promise<vscode.CompletionItem>;
getSignatureHelp: (uri: string, position: vscode.Position, signatureHelpContext?: vscode.SignatureHelpContext, token?: vscode.CancellationToken) => Promise<vscode.SignatureHelp | undefined>;
doCodeLens: (uri: string, token?: vscode.CancellationToken) => Promise<vscode.CodeLens[]>;
doCodeLensResolve: (item: vscode.CodeLens, token?: vscode.CancellationToken) => Promise<vscode.CodeLens>;
findDocumentHighlights: (uri: string, position: vscode.Position, token?: vscode.CancellationToken) => Promise<vscode.DocumentHighlight[] | undefined>;
findDocumentLinks: (uri: string, token?: vscode.CancellationToken) => Promise<vscode.DocumentLink[]>;
doDocumentLinkResolve: (item: vscode.DocumentLink, token?: vscode.CancellationToken) => Promise<vscode.DocumentLink>;
findWorkspaceSymbols: (query: string, token?: vscode.CancellationToken) => Promise<vscode.WorkspaceSymbol[]>;
doAutoInsert: (uri: string, position: vscode.Position, lastChange: {
range: vscode.Range;
text: string;
}, token?: vscode.CancellationToken) => Promise<string | vscode.TextEdit | undefined>;
doDocumentDrop: (uri: string, position: vscode.Position, dataTransfer: Map<string, import("./types").DataTransferItem>, token?: vscode.CancellationToken) => Promise<import("./types").DocumentDropEdit | undefined>;
getInlayHints: (uri: string, range: vscode.Range, token?: vscode.CancellationToken) => Promise<vscode.InlayHint[] | undefined>;
doInlayHintResolve: (item: vscode.InlayHint, token?: vscode.CancellationToken) => Promise<vscode.InlayHint>;
callHierarchy: {
doPrepare(uri: string, position: vscode.Position, token?: vscode.CancellationToken): Promise<vscode.CallHierarchyItem[] | undefined>;
getIncomingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyIncomingCall[]>;
getOutgoingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyOutgoingCall[]>;
};
dispose: () => void;
context: ServiceContext;
};

View File

@ -0,0 +1,141 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectClassesAndIdsFromDocument = exports.extractStylesheets = void 0;
const utils_1 = require("@astrojs/compiler/utils");
const language_core_1 = require("@volar/language-core");
function extractStylesheets(snapshot, htmlDocument, ast) {
const embeddedCSSCodes = findEmbeddedStyles(snapshot, htmlDocument.roots);
const inlineStyles = findInlineStyles(ast);
if (inlineStyles.length > 0) {
const codes = [];
for (const inlineStyle of inlineStyles) {
codes.push('x { ');
codes.push([
inlineStyle.value,
undefined,
inlineStyle.position.start.offset + 'style="'.length,
{
completion: true,
verification: false,
semantic: true,
navigation: true,
structure: true,
format: false,
},
]);
codes.push(' }\n');
}
const mappings = (0, language_core_1.buildMappings)(codes);
const text = (0, language_core_1.toString)(codes);
embeddedCSSCodes.push({
id: 'inline.css',
languageId: 'css',
snapshot: {
getText: (start, end) => text.substring(start, end),
getLength: () => text.length,
getChangeRange: () => undefined,
},
embeddedCodes: [],
mappings,
});
}
return embeddedCSSCodes;
}
exports.extractStylesheets = extractStylesheets;
/**
* Find all embedded styles in a document.
* Embedded styles are styles that are defined in `<style>` tags.
*/
function findEmbeddedStyles(snapshot, roots) {
const embeddedCSSCodes = [];
let cssIndex = 0;
getEmbeddedCSSInNodes(roots);
function getEmbeddedCSSInNodes(nodes) {
for (const [_, node] of nodes.entries()) {
if (node.tag === 'style' &&
node.startTagEnd !== undefined &&
node.endTagStart !== undefined) {
const styleText = snapshot.getText(node.startTagEnd, node.endTagStart);
embeddedCSSCodes.push({
id: `${cssIndex}.css`,
languageId: 'css',
snapshot: {
getText: (start, end) => styleText.substring(start, end),
getLength: () => styleText.length,
getChangeRange: () => undefined,
},
mappings: [
{
sourceOffsets: [node.startTagEnd],
generatedOffsets: [0],
lengths: [styleText.length],
data: {
verification: false,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: false,
},
},
],
embeddedCodes: [],
});
cssIndex++;
}
if (node.children)
getEmbeddedCSSInNodes(node.children);
}
}
return embeddedCSSCodes;
}
/**
* Find all inline styles using the Astro AST
* Inline styles are styles that are defined in the `style` attribute of an element.
* TODO: Merge this with `findEmbeddedCSS`? Unlike scripts, there's no scoping being done here, so merging all of it in
* the same virtual file is possible, though it might make mapping more tricky.
*/
function findInlineStyles(ast) {
const styleAttrs = [];
// `@astrojs/compiler`'s `walk` method is async, so we can't use it here. Arf
function walkDown(parent) {
if (!parent.children)
return;
parent.children.forEach((child) => {
if (utils_1.is.element(child)) {
const styleAttribute = child.attributes.find((attr) => attr.name === 'style' && attr.kind === 'quoted');
if (styleAttribute && styleAttribute.position) {
styleAttrs.push(styleAttribute);
}
}
if (utils_1.is.parent(child)) {
walkDown(child);
}
});
}
walkDown(ast);
return styleAttrs;
}
// TODO: Provide completion for classes and IDs
function collectClassesAndIdsFromDocument(ast) {
const classesAndIds = [];
function walkDown(parent) {
if (!parent.children)
return;
parent.children.forEach((child) => {
if (utils_1.is.element(child)) {
const classOrIDAttributes = child.attributes
.filter((attr) => attr.kind === 'quoted' && (attr.name === 'class' || attr.name === 'id'))
.flatMap((attr) => attr.value.split(' '));
classesAndIds.push(...classOrIDAttributes);
}
if (utils_1.is.parent(child)) {
walkDown(child);
}
});
}
walkDown(ast);
return classesAndIds;
}
exports.collectClassesAndIdsFromDocument = collectClassesAndIdsFromDocument;
//# sourceMappingURL=parseCSS.js.map

View File

@ -0,0 +1,113 @@
---
description: 'Enforce consistent usage of type assertions.'
---
> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/consistent-type-assertions** for documentation.
TypeScript provides two syntaxes for "type assertions":
- Angle brackets: `<Type>value`
- As: `value as Type`
This rule aims to standardize the use of type assertion style across the codebase.
Keeping to one syntax consistently helps with code readability.
:::note
Type assertions are also commonly referred as "type casting" in TypeScript.
However, that term is technically slightly different to what is understood by type casting in other languages.
Type assertions are a way to say to the TypeScript compiler, _"I know better than you, it's actually this different type!"_.
:::
[`const` assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) are always allowed by this rule.
Examples of them include `let x = "hello" as const;` and `let x = <const>"hello";`.
## Options
### `assertionStyle`
This option defines the expected assertion style. Valid values for `assertionStyle` are:
- `as` will enforce that you always use `... as foo`.
- `angle-bracket` will enforce that you always use `<foo>...`
- `never` will enforce that you do not do any type assertions.
Most codebases will want to enforce not using `angle-bracket` style because it conflicts with JSX syntax, and is confusing when paired with generic syntax.
Some codebases like to go for an extra level of type safety, and ban assertions altogether via the `never` option.
### `objectLiteralTypeAssertions`
Always prefer `const x: T = { ... };` to `const x = { ... } as T;` (or similar with angle brackets). The type assertion in the latter case is either unnecessary or will probably hide an error.
The compiler will warn for excess properties with this syntax, but not missing _required_ fields. For example: `const x: { foo: number } = {};` will fail to compile, but `const x = {} as { foo: number }` will succeed.
The const assertion `const x = { foo: 1 } as const`, introduced in TypeScript 3.4, is considered beneficial and is ignored by this option.
Assertions to `any` are also ignored by this option.
Examples of code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }`:
<!--tabs-->
#### ❌ Incorrect
```ts option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "never" }'
const x = { foo: 1 } as T;
function bar() {
return { foo: 1 } as T;
}
```
#### ✅ Correct
```ts option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "never" }'
const x: T = { foo: 1 };
const y = { foo: 1 } as any;
const z = { foo: 1 } as unknown;
function bar(): T {
return { foo: 1 };
}
```
<!--/tabs-->
Examples of code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'allow-as-parameter' }`:
<!--tabs-->
#### ❌ Incorrect
```ts option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "allow-as-parameter" }'
const x = { foo: 1 } as T;
function bar() {
return { foo: 1 } as T;
}
```
#### ✅ Correct
```tsx option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "allow-as-parameter" }'
const x: T = { foo: 1 };
const y = { foo: 1 } as any;
const z = { foo: 1 } as unknown;
bar({ foo: 1 } as T);
new Clazz({ foo: 1 } as T);
function bar() {
throw { foo: 1 } as Foo;
}
const foo = <Foo props={{ bar: 1 } as Bar} />;
```
<!--/tabs-->
## When Not To Use It
If you do not want to enforce consistent type assertions.
However, keep in mind that inconsistent style can harm readability in a project.
We recommend picking a single option for this rule that works best for your project.

View File

@ -0,0 +1,47 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.2](https://github.com/inspect-js/get-symbol-description/compare/v1.0.1...v1.0.2) - 2024-02-07
### Fixed
- [Deps] add missing `get-intrinsic` [`#3`](https://github.com/inspect-js/get-symbol-description/issues/3)
## [v1.0.1](https://github.com/inspect-js/get-symbol-description/compare/v1.0.0...v1.0.1) - 2024-02-05
### Commits
- [actions] reuse common workflows [`168adf2`](https://github.com/inspect-js/get-symbol-description/commit/168adf213f86e5c69a93b4768a20ad543a70b231)
- [meta] use `npmignore` to autogenerate an npmignore file [`fa3b323`](https://github.com/inspect-js/get-symbol-description/commit/fa3b323f0605cf966a5cef1a103ada46d63e466b)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-value-fixtures`, `foreach`, `object-inspect`, `tape` [`9301b9e`](https://github.com/inspect-js/get-symbol-description/commit/9301b9e274fd9b7544af3d7d437dd254e83095e0)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`a92a011`](https://github.com/inspect-js/get-symbol-description/commit/a92a0119f373fb61c58e3eb1d5fb6b3a3f66f157)
- [actions] update rebase action to use reusable workflow [`66cea29`](https://github.com/inspect-js/get-symbol-description/commit/66cea29835bc88ab5e937ccf996ea96409475a0e)
- [actions] update codecov uploader [`84079e1`](https://github.com/inspect-js/get-symbol-description/commit/84079e12e1421a79b63757cc3ab9c599e8eecc75)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `safe-publish-latest`, `tape` [`9f298a5`](https://github.com/inspect-js/get-symbol-description/commit/9f298a521e6f8a9b974b6b95e0b3de8aeaf74d9c)
- [Dev Deps] use `hasown` instead of `has` [`e993bd6`](https://github.com/inspect-js/get-symbol-description/commit/e993bd62a08a1adc2f75664be99a36e031ecf604)
- [Dev Deps] update `aud`, `npmignore`, `tape` [`5044bed`](https://github.com/inspect-js/get-symbol-description/commit/5044bed49a1b2b529b0c92fee0504747fda78147)
- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`3923eab`](https://github.com/inspect-js/get-symbol-description/commit/3923eabcf3eb2ddad7dbfd542102c29646dac242)
- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`a24f5c5`](https://github.com/inspect-js/get-symbol-description/commit/a24f5c5f6ddd1f24b22ecdc2546eb9b06924f62a)
- [Deps] update `call-bind`, `get-intrinsic` [`accd484`](https://github.com/inspect-js/get-symbol-description/commit/accd484cb970c11fb39eb5ec4301572fa4043e37)
- [Dev Deps] update `object-inspect`, `tape` [`6c66623`](https://github.com/inspect-js/get-symbol-description/commit/6c666237114333bcb548e2c9ba6eb4924cb154ad)
- [Dev Deps] update `object-inspect`, `tape` [`586dfe3`](https://github.com/inspect-js/get-symbol-description/commit/586dfe35b9b6e7dba3fb7577c5973b7466d101a3)
- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`bc8c7e0`](https://github.com/inspect-js/get-symbol-description/commit/bc8c7e0382682164f78b87f41764a0a2e389c435)
- [Tests] use `for-each` instead of `foreach` [`ca97918`](https://github.com/inspect-js/get-symbol-description/commit/ca97918eaad4ff1df11fd6f187da60227722dfcd)
- [Robustness] cache String slice [`5ce0c56`](https://github.com/inspect-js/get-symbol-description/commit/5ce0c5658224ed5cf5c6775a18ee2ad60c5b7ba8)
- [Deps] update `get-intrinsic` [`b656c5c`](https://github.com/inspect-js/get-symbol-description/commit/b656c5c68fbeec35d75a635ca991b61ed004bf54)
- [Deps] update `get-intrinsic` [`74cf3b6`](https://github.com/inspect-js/get-symbol-description/commit/74cf3b6525c49998f2c984d350e4d59d7f70794c)
- [meta] fix FUNDING.yml [`6cf76c8`](https://github.com/inspect-js/get-symbol-description/commit/6cf76c8c56bf366f767a84e82038db54b508641a)
## v1.0.0 - 2021-08-17
### Commits
- Initial commit: pulled from es-abstract [`6e34a05`](https://github.com/inspect-js/get-symbol-description/commit/6e34a05ef10ce8620078cf4cecbe276c1fc1ae77)
- Initial commit [`3862092`](https://github.com/inspect-js/get-symbol-description/commit/3862092248d8ffa071ec90ec39d73e8be14ba6f1)
- [meta] do not publish github action workflow files [`9d1e2b9`](https://github.com/inspect-js/get-symbol-description/commit/9d1e2b94dd97664da5d0666985a3695c23f45865)
- npm init [`5051b32`](https://github.com/inspect-js/get-symbol-description/commit/5051b3221829f364c44b4d5e9a0c35aab3247f6a)
- Only apps should have lockfiles [`b866d1c`](https://github.com/inspect-js/get-symbol-description/commit/b866d1c4b4029277618d968cfb3cbe00f012d1a7)

View File

@ -0,0 +1,4 @@
import type { ServicePlugin } from '@volar/language-service';
import { InitializationOptions } from './types';
import * as vscode from 'vscode-languageserver';
export declare function setupCapabilities(server: vscode.ServerCapabilities, initOptions: InitializationOptions, watchExts: string[], services: ServicePlugin[], semanticTokensLegend: vscode.SemanticTokensLegend): void;

View File

@ -0,0 +1,108 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $SyntaxError = require('es-errors/syntax');
var $TypeError = require('es-errors/type');
var $Uint8Array = GetIntrinsic('%Uint8Array%', true);
var callBound = require('call-bind/callBound');
var $slice = callBound('Array.prototype.slice');
var isInteger = require('../helpers/isInteger');
var IsDetachedBuffer = require('./IsDetachedBuffer');
var RawBytesToNumber = require('./RawBytesToNumber');
var isArrayBuffer = require('is-array-buffer');
var isSharedArrayBuffer = require('is-shared-array-buffer');
var safeConcat = require('safe-array-concat');
var table50 = {
__proto__: null,
$Int8: 1,
$Uint8: 1,
$Uint8C: 1,
$Int16: 2,
$Uint16: 2,
$Int32: 4,
$Uint32: 4,
$Float32: 4,
$Float64: 8
};
var defaultEndianness = require('../helpers/defaultEndianness');
// https://262.ecma-international.org/8.0/#sec-getvaluefrombuffer
module.exports = function GetValueFromBuffer(arrayBuffer, byteIndex, type, isTypedArray, order) {
var isSAB = isSharedArrayBuffer(arrayBuffer);
if (!isArrayBuffer(arrayBuffer) && !isSAB) {
throw new $TypeError('Assertion failed: `arrayBuffer` must be an ArrayBuffer or a SharedArrayBuffer');
}
if (!isInteger(byteIndex)) {
throw new $TypeError('Assertion failed: `byteIndex` must be an integer');
}
if (typeof type !== 'string') {
throw new $TypeError('Assertion failed: `type` must be a string');
}
if (typeof isTypedArray !== 'boolean') {
throw new $TypeError('Assertion failed: `isTypedArray` must be a boolean');
}
if (typeof order !== 'string') {
throw new $TypeError('Assertion failed: `order` must be a string');
}
if (arguments.length > 5 && typeof arguments[5] !== 'boolean') {
throw new $TypeError('Assertion failed: `isLittleEndian` must be a boolean, if present');
}
if (IsDetachedBuffer(arrayBuffer)) {
throw new $TypeError('Assertion failed: `arrayBuffer` is detached'); // step 1
}
// 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.
if (byteIndex < 0) {
throw new $TypeError('Assertion failed: `byteIndex` must be non-negative'); // step 3
}
// 4. Let block be arrayBuffer.[[ArrayBufferData]].
var elementSize = table50['$' + type]; // step 5
if (!elementSize) {
throw new $TypeError('Assertion failed: `type` must be one of "Int8", "Uint8", "Uint8C", "Int16", "Uint16", "Int32", "Uint32", "Float32", or "Float64"');
}
var rawValue;
if (isSAB) { // step 6
/*
a. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
b. Let eventList be the [[EventList]] field of the element in execution.[[EventLists]] whose [[AgentSignifier]] is AgentSignifier().
c. If isTypedArray is true and type is "Int8", "Uint8", "Int16", "Uint16", "Int32", or "Uint32", let noTear be true; otherwise let noTear be false.
d. Let rawValue be a List of length elementSize of nondeterministically chosen byte values.
e. NOTE: In implementations, rawValue is the result of a non-atomic or atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the memory model to describe observable behaviour of hardware with weak consistency.
f. Let readEvent be ReadSharedMemory{ [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
g. Append readEvent to eventList.
h. Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
*/
throw new $SyntaxError('TODO: support SharedArrayBuffers');
} else {
// 7. Let rawValue be a List of elementSize containing, in order, the elementSize sequence of bytes starting with block[byteIndex].
rawValue = $slice(new $Uint8Array(arrayBuffer, byteIndex), 0, elementSize); // step 6
}
// 8. If isLittleEndian is not present, set isLittleEndian to either true or false. The choice is implementation dependent and should be the alternative that is most efficient for the implementation. An implementation must use the same value each time this step is executed and the same value must be used for the corresponding step in the SetValueInBuffer abstract operation.
var isLittleEndian = arguments.length > 5 ? arguments[5] : defaultEndianness === 'little'; // step 8
var bytes = isLittleEndian
? $slice(safeConcat([0, 0, 0, 0, 0, 0, 0, 0], rawValue), -elementSize)
: $slice(safeConcat(rawValue, [0, 0, 0, 0, 0, 0, 0, 0]), 0, elementSize);
return RawBytesToNumber(type, bytes, isLittleEndian);
};

View File

@ -0,0 +1,123 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'non-nullable-type-assertion-style',
meta: {
docs: {
description: 'Enforce non-null assertions over explicit type casts',
recommended: 'stylistic',
requiresTypeChecking: true,
},
fixable: 'code',
messages: {
preferNonNullAssertion: 'Use a ! assertion to more succinctly remove null and undefined from the type.',
},
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
const services = (0, util_1.getParserServices)(context);
const getTypesIfNotLoose = (node) => {
const type = services.getTypeAtLocation(node);
if (tsutils.isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return undefined;
}
return tsutils.unionTypeParts(type);
};
const couldBeNullish = (type) => {
if (type.flags & ts.TypeFlags.TypeParameter) {
const constraint = type.getConstraint();
return constraint == null || couldBeNullish(constraint);
}
else if (tsutils.isUnionType(type)) {
for (const part of type.types) {
if (couldBeNullish(part)) {
return true;
}
}
return false;
}
return (type.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0;
};
const sameTypeWithoutNullish = (assertedTypes, originalTypes) => {
const nonNullishOriginalTypes = originalTypes.filter(type => (type.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) === 0);
if (nonNullishOriginalTypes.length === originalTypes.length) {
return false;
}
for (const assertedType of assertedTypes) {
if (couldBeNullish(assertedType) ||
!nonNullishOriginalTypes.includes(assertedType)) {
return false;
}
}
for (const originalType of nonNullishOriginalTypes) {
if (!assertedTypes.includes(originalType)) {
return false;
}
}
return true;
};
const isConstAssertion = (node) => {
return (node.typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeReference &&
node.typeAnnotation.typeName.type === utils_1.AST_NODE_TYPES.Identifier &&
node.typeAnnotation.typeName.name === 'const');
};
return {
'TSAsExpression, TSTypeAssertion'(node) {
if (isConstAssertion(node)) {
return;
}
const originalTypes = getTypesIfNotLoose(node.expression);
if (!originalTypes) {
return;
}
const assertedTypes = getTypesIfNotLoose(node.typeAnnotation);
if (!assertedTypes) {
return;
}
if (sameTypeWithoutNullish(assertedTypes, originalTypes)) {
const expressionSourceCode = context.sourceCode.getText(node.expression);
const higherPrecedenceThanUnary = (0, util_1.getOperatorPrecedence)(services.esTreeNodeToTSNodeMap.get(node.expression).kind, ts.SyntaxKind.Unknown) > util_1.OperatorPrecedence.Unary;
context.report({
fix(fixer) {
return fixer.replaceText(node, higherPrecedenceThanUnary
? `${expressionSourceCode}!`
: `(${expressionSourceCode})!`);
},
messageId: 'preferNonNullAssertion',
node,
});
}
},
};
},
});
//# sourceMappingURL=non-nullable-type-assertion-style.js.map

View File

@ -0,0 +1,123 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $TypeError = require('es-errors/type');
var AsyncFromSyncIteratorContinuation = require('./AsyncFromSyncIteratorContinuation');
var Call = require('./Call');
var CreateIterResultObject = require('./CreateIterResultObject');
var Get = require('./Get');
var GetMethod = require('./GetMethod');
var IteratorNext = require('./IteratorNext');
var OrdinaryObjectCreate = require('./OrdinaryObjectCreate');
var Type = require('./Type');
var isIteratorRecord = require('../helpers/records/iterator-record');
var SLOT = require('internal-slot');
var $AsyncFromSyncIteratorPrototype = GetIntrinsic('%AsyncFromSyncIteratorPrototype%', true) || {
next: function next(value) {
var O = this; // step 1
SLOT.assert(O, '[[SyncIteratorRecord]]'); // step 2
var argsLength = arguments.length;
return new Promise(function (resolve) { // step 3
var syncIteratorRecord = SLOT.get(O, '[[SyncIteratorRecord]]'); // step 4
var result;
if (argsLength > 0) {
result = IteratorNext(syncIteratorRecord['[[Iterator]]'], value); // step 5.a
} else { // step 6
result = IteratorNext(syncIteratorRecord['[[Iterator]]']);// step 6.a
}
resolve(AsyncFromSyncIteratorContinuation(result)); // step 8
});
},
'return': function () {
var O = this; // step 1
SLOT.assert(O, '[[SyncIteratorRecord]]'); // step 2
var valueIsPresent = arguments.length > 0;
var value = valueIsPresent ? arguments[0] : void undefined;
return new Promise(function (resolve, reject) { // step 3
var syncIterator = SLOT.get(O, '[[SyncIteratorRecord]]')['[[Iterator]]']; // step 4
var iteratorReturn = GetMethod(syncIterator, 'return'); // step 5
if (typeof iteratorReturn === 'undefined') { // step 7
var iterResult = CreateIterResultObject(value, true); // step 7.a
Call(resolve, undefined, [iterResult]); // step 7.b
return;
}
var result;
if (valueIsPresent) { // step 8
result = Call(iteratorReturn, syncIterator, [value]); // step 8.a
} else { // step 9
result = Call(iteratorReturn, syncIterator); // step 9.a
}
if (Type(result) !== 'Object') { // step 11
Call(reject, undefined, [new $TypeError('Iterator `return` method returned a non-object value.')]); // step 11.a
return;
}
resolve(AsyncFromSyncIteratorContinuation(result)); // step 12
});
},
'throw': function () {
var O = this; // step 1
SLOT.assert(O, '[[SyncIteratorRecord]]'); // step 2
var valueIsPresent = arguments.length > 0;
var value = valueIsPresent ? arguments[0] : void undefined;
return new Promise(function (resolve, reject) { // step 3
var syncIterator = SLOT.get(O, '[[SyncIteratorRecord]]')['[[Iterator]]']; // step 4
var throwMethod = GetMethod(syncIterator, 'throw'); // step 5
if (typeof throwMethod === 'undefined') { // step 7
Call(reject, undefined, [value]); // step 7.a
return;
}
var result;
if (valueIsPresent) { // step 8
result = Call(throwMethod, syncIterator, [value]); // step 8.a
} else { // step 9
result = Call(throwMethod, syncIterator); // step 9.a
}
if (Type(result) !== 'Object') { // step 11
Call(reject, undefined, [new $TypeError('Iterator `throw` method returned a non-object value.')]); // step 11.a
return;
}
resolve(AsyncFromSyncIteratorContinuation(result/* , promiseCapability */)); // step 12
});
}
};
// https://262.ecma-international.org/11.0/#sec-createasyncfromsynciterator
module.exports = function CreateAsyncFromSyncIterator(syncIteratorRecord) {
if (!isIteratorRecord(syncIteratorRecord)) {
throw new $TypeError('Assertion failed: `syncIteratorRecord` must be an Iterator Record');
}
// var asyncIterator = OrdinaryObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »); // step 1
var asyncIterator = OrdinaryObjectCreate($AsyncFromSyncIteratorPrototype);
SLOT.set(asyncIterator, '[[SyncIteratorRecord]]', syncIteratorRecord); // step 2
var nextMethod = Get(asyncIterator, 'next'); // step 3
return { // steps 3-4
'[[Iterator]]': asyncIterator,
'[[NextMethod]]': nextMethod,
'[[Done]]': false
};
};

View File

@ -0,0 +1,3 @@
import type * as ts from 'typescript';
import { LanguagePlugin } from '@volar/language-core';
export declare function proxyCreateProgram(ts: typeof import('typescript'), original: typeof ts['createProgram'], extensions: string[], getLanguagePlugins: (ts: typeof import('typescript'), options: ts.CreateProgramOptions) => LanguagePlugin[]): typeof import("typescript").createProgram;

View File

@ -0,0 +1,83 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var callBound = require('call-bind/callBound');
var $RangeError = require('es-errors/range');
var $SyntaxError = require('es-errors/syntax');
var $TypeError = require('es-errors/type');
var $BigInt = GetIntrinsic('%BigInt%', true);
var hasOwnProperty = require('./HasOwnProperty');
var IsArray = require('./IsArray');
var IsBigIntElementType = require('./IsBigIntElementType');
var IsUnsignedElementType = require('./IsUnsignedElementType');
var bytesAsFloat32 = require('../helpers/bytesAsFloat32');
var bytesAsFloat64 = require('../helpers/bytesAsFloat64');
var bytesAsInteger = require('../helpers/bytesAsInteger');
var every = require('../helpers/every');
var isByteValue = require('../helpers/isByteValue');
var $reverse = callBound('Array.prototype.reverse');
var $slice = callBound('Array.prototype.slice');
var keys = require('object-keys');
// https://262.ecma-international.org/11.0/#table-the-typedarray-constructors
var TypeToSizes = {
__proto__: null,
Int8: 1,
Uint8: 1,
Uint8C: 1,
Int16: 2,
Uint16: 2,
Int32: 4,
Uint32: 4,
BigInt64: 8,
BigUint64: 8,
Float32: 4,
Float64: 8
};
// https://262.ecma-international.org/11.0/#sec-rawbytestonumeric
module.exports = function RawBytesToNumeric(type, rawBytes, isLittleEndian) {
if (!hasOwnProperty(TypeToSizes, type)) {
throw new $TypeError('Assertion failed: `type` must be a TypedArray element type: ' + keys(TypeToSizes));
}
if (!IsArray(rawBytes) || !every(rawBytes, isByteValue)) {
throw new $TypeError('Assertion failed: `rawBytes` must be an Array of bytes');
}
if (typeof isLittleEndian !== 'boolean') {
throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
}
var elementSize = TypeToSizes[type]; // step 1
if (rawBytes.length !== elementSize) {
// this assertion is not in the spec, but it'd be an editorial error if it were ever violated
throw new $RangeError('Assertion failed: `rawBytes` must have a length of ' + elementSize + ' for type ' + type);
}
var isBigInt = IsBigIntElementType(type);
if (isBigInt && !$BigInt) {
throw new $SyntaxError('this environment does not support BigInts');
}
// eslint-disable-next-line no-param-reassign
rawBytes = $slice(rawBytes, 0, elementSize);
if (!isLittleEndian) {
$reverse(rawBytes); // step 2
}
if (type === 'Float32') { // step 3
return bytesAsFloat32(rawBytes);
}
if (type === 'Float64') { // step 4
return bytesAsFloat64(rawBytes);
}
return bytesAsInteger(rawBytes, elementSize, IsUnsignedElementType(type), isBigInt);
};

View File

@ -0,0 +1,6 @@
import type * as vscode from '@volar/language-service';
import type { TextDocument } from 'vscode-languageserver-textdocument';
import type { SharedContext } from '../../types';
export declare function register(ctx: SharedContext): (item: vscode.CompletionItem, newPosition?: vscode.Position) => Promise<vscode.CompletionItem>;
export declare function getLineText(document: TextDocument, line: number): string;
//# sourceMappingURL=resolve.d.ts.map

View File

@ -0,0 +1,138 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('block-spacing');
exports.default = (0, util_1.createRule)({
name: 'block-spacing',
meta: {
deprecated: true,
replacedBy: ['@stylistic/ts/block-spacing'],
type: 'layout',
docs: {
description: 'Disallow or enforce spaces inside of blocks after opening block and before closing block',
extendsBaseRule: true,
},
fixable: 'whitespace',
hasSuggestions: baseRule.meta.hasSuggestions,
schema: baseRule.meta.schema,
messages: baseRule.meta.messages,
},
defaultOptions: ['always'],
create(context, [whenToApplyOption]) {
const baseRules = baseRule.create(context);
const always = whenToApplyOption !== 'never';
const messageId = always ? 'missing' : 'extra';
/**
* Gets the open brace token from a given node.
* @returns The token of the open brace.
*/
function getOpenBrace(node) {
// guaranteed for enums
// This is the only change made here from the base rule
return context.sourceCode.getFirstToken(node, {
filter: token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && token.value === '{',
});
}
/**
* Checks whether or not:
* - given tokens are on same line.
* - there is/isn't a space between given tokens.
* @param left A token to check.
* @param right The token which is next to `left`.
* @returns
* When the option is `"always"`, `true` if there are one or more spaces between given tokens.
* When the option is `"never"`, `true` if there are not any spaces between given tokens.
* If given tokens are not on same line, it's always `true`.
*/
function isValid(left, right) {
return (!(0, util_1.isTokenOnSameLine)(left, right) ||
context.sourceCode.isSpaceBetween(left, right) === always);
}
/**
* Checks and reports invalid spacing style inside braces.
*/
function checkSpacingInsideBraces(node) {
// Gets braces and the first/last token of content.
const openBrace = getOpenBrace(node);
const closeBrace = context.sourceCode.getLastToken(node);
const firstToken = context.sourceCode.getTokenAfter(openBrace, {
includeComments: true,
});
const lastToken = context.sourceCode.getTokenBefore(closeBrace, {
includeComments: true,
});
// Skip if the node is invalid or empty.
if (openBrace.value !== '{' ||
closeBrace.type !== utils_1.AST_TOKEN_TYPES.Punctuator ||
closeBrace.value !== '}' ||
firstToken === closeBrace) {
return;
}
// Skip line comments for option never
if (!always && firstToken.type === utils_1.AST_TOKEN_TYPES.Line) {
return;
}
if (!isValid(openBrace, firstToken)) {
let loc = openBrace.loc;
if (messageId === 'extra') {
loc = {
start: openBrace.loc.end,
end: firstToken.loc.start,
};
}
context.report({
node,
loc,
messageId,
data: {
location: 'after',
token: openBrace.value,
},
fix(fixer) {
if (always) {
return fixer.insertTextBefore(firstToken, ' ');
}
return fixer.removeRange([openBrace.range[1], firstToken.range[0]]);
},
});
}
if (!isValid(lastToken, closeBrace)) {
let loc = closeBrace.loc;
if (messageId === 'extra') {
loc = {
start: lastToken.loc.end,
end: closeBrace.loc.start,
};
}
context.report({
node,
loc,
messageId,
data: {
location: 'before',
token: closeBrace.value,
},
fix(fixer) {
if (always) {
return fixer.insertTextAfter(lastToken, ' ');
}
return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]);
},
});
}
}
return {
...baseRules,
// This code worked "out of the box" for interface and type literal
// Enums were very close to match as well, the only reason they are not is that was that enums don't have a body node in the parser
// So the opening brace punctuator starts in the middle of the node - `getFirstToken` in
// the base rule did not filter for the first opening brace punctuator
TSInterfaceBody: baseRules.BlockStatement,
TSTypeLiteral: baseRules.BlockStatement,
TSEnumDeclaration: checkSpacingInsideBraces,
};
},
});
//# sourceMappingURL=block-spacing.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"comma-dangle.js","sourceRoot":"","sources":["../../src/rules/comma-dangle.ts"],"names":[],"mappings":";;AACA,oDAA0D;AAM1D,kCAAmD;AACnD,iEAA8D;AAE9D,MAAM,QAAQ,GAAG,IAAA,qCAAiB,EAAC,cAAc,CAAC,CAAC;AAUnD,MAAM,mBAAmB,GAAG;IAC1B,kBAAkB;IAClB,QAAQ;IACR,OAAO;IACP,gBAAgB;CACjB,CAAC;AAEF,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAErC,SAAS,gBAAgB,CAAC,OAAe;IACvC,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO;YACL,KAAK,EAAE,OAAO;YACd,QAAQ,EAAE,OAAO;YACjB,MAAM,EAAE,OAAO;SAChB,CAAC;IACJ,CAAC;IACD,OAAO;QACL,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,oBAAoB;QAC5C,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,oBAAoB;QAClD,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,oBAAoB;KAC/C,CAAC;AACJ,CAAC;AAED,kBAAe,IAAA,iBAAU,EAAsB;IAC7C,IAAI,EAAE,cAAc;IACpB,IAAI,EAAE;QACJ,UAAU,EAAE,IAAI;QAChB,UAAU,EAAE,CAAC,4BAA4B,CAAC;QAC1C,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE;YACJ,WAAW,EAAE,qCAAqC;YAClD,eAAe,EAAE,IAAI;SACtB;QACD,MAAM,EAAE;YACN,KAAK,EAAE;gBACL,KAAK,EAAE;oBACL,IAAI,EAAE,QAAQ;oBACd,IAAI,EAAE,mBAAmB;iBAC1B;gBACD,eAAe,EAAE;oBACf,IAAI,EAAE,QAAQ;oBACd,IAAI,EAAE,CAAC,GAAG,mBAAmB,EAAE,QAAQ,CAAC;iBACzC;aACF;YACD,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACL;oBACE,KAAK,EAAE;wBACL;4BACE,IAAI,EAAE,eAAe;yBACtB;wBACD;4BACE,IAAI,EAAE,QAAQ;4BACd,UAAU,EAAE;gCACV,MAAM,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;gCAC3C,OAAO,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;gCAC5C,OAAO,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;gCAC5C,OAAO,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;gCAC5C,SAAS,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;gCAC9C,KAAK,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;gCAC1C,QAAQ,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;gCAC7C,MAAM,EAAE,EAAE,IAAI,EAAE,yBAAyB,EAAE;6BAC5C;4BACD,oBAAoB,EAAE,KAAK;yBAC5B;qBACF;iBACF;aACF;YACD,eAAe,EAAE,KAAK;SACvB;QACD,OAAO,EAAE,MAAM;QACf,cAAc,EAAE,QAAQ,CAAC,IAAI,CAAC,cAAc;QAC5C,QAAQ,EAAE,QAAQ,CAAC,IAAI,CAAC,QAAQ;KACjC;IACD,cAAc,EAAE,CAAC,OAAO,CAAC;IACzB,MAAM,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC;QACvB,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAEvC,MAAM,iBAAiB,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;QAEpD,MAAM,SAAS,GAAG;YAChB,MAAM,EAAE,UAAU;YAClB,kBAAkB,EAAE,qBAAqB;YACzC,gBAAgB,EAAE,qBAAqB;YACvC,KAAK,EAAE,WAAW;YAClB,qEAAqE;YACrE,kHAAkH;YAClH,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;SACjB,CAAC;QAEF,SAAS,IAAI,CAAC,KAAsB;YAClC,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC;QACzC,CAAC;QAED,SAAS,WAAW,CAAC,IAAmB;YACtC,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;gBAClB,KAAK,sBAAc,CAAC,iBAAiB;oBACnC,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAC5B,KAAK,sBAAc,CAAC,0BAA0B;oBAC5C,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAC3B,KAAK,sBAAc,CAAC,WAAW;oBAC7B,OAAO,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;gBACjC;oBACE,OAAO,IAAI,CAAC;YAChB,CAAC;QACH,CAAC;QAED,SAAS,gBAAgB,CAAC,IAAmB;YAC3C,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,IAAI,IAAI,OAAO,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAChE,OAAO,QAAQ,CAAC;QAClB,CAAC;QAED,SAAS,WAAW,CAAC,IAAmB;YACtC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;YACxD,OAAO,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,SAAS,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC;QACxD,CAAC;QAED,SAAS,WAAW,CAAC,IAAmB;YACtC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;YACxC,IAAI,IAAI,IAAI,QAAQ,IAAI,IAAA,mBAAY,EAAC,QAAQ,CAAC,EAAE,CAAC;gBAC/C,OAAO,CAAC,MAAM,CAAC;oBACb,IAAI;oBACJ,SAAS,EAAE,YAAY;oBACvB,GAAG,CAAC,KAAK;wBACP,OAAO,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;oBAChC,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,SAAS,UAAU,CAAC,IAAmB;YACrC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;YACxC,IAAI,IAAI,IAAI,QAAQ,IAAI,CAAC,IAAA,mBAAY,EAAC,QAAQ,CAAC,EAAE,CAAC;gBAChD,OAAO,CAAC,MAAM,CAAC;oBACb,IAAI;oBACJ,SAAS,EAAE,SAAS;oBACpB,GAAG,CAAC,KAAK;wBACP,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;oBAC1C,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,SAAS,qBAAqB,CAAC,IAAmB;YAChD,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC;gBACvB,WAAW,CAAC,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QAED,SAAS,qBAAqB,CAAC,IAAmB;YAChD,IAAI,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC;gBACtB,UAAU,CAAC,IAAI,CAAC,CAAC;YACnB,CAAC;iBAAM,CAAC;gBACN,WAAW,CAAC,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QAED,OAAO;YACL,GAAG,KAAK;YACR,iBAAiB,EAAE,SAAS,CAAC,iBAAiB,CAAC,KAAK,CAAC;YACrD,0BAA0B,EAAE,SAAS,CAAC,iBAAiB,CAAC,QAAQ,CAAC;YACjE,WAAW,EAAE,SAAS,CAAC,iBAAiB,CAAC,MAAM,CAAC;SACjD,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}

View File

@ -0,0 +1,18 @@
'use strict';
var $TypeError = require('es-errors/type');
var SameValue = require('./SameValue');
var Type = require('./Type');
// https://262.ecma-international.org/11.0/#sec-samevaluenonnumeric
module.exports = function SameValueNonNumeric(x, y) {
if (typeof x === 'number' || typeof x === 'bigint') {
throw new $TypeError('Assertion failed: SameValueNonNumeric does not accept Number or BigInt values');
}
if (Type(x) !== Type(y)) {
throw new $TypeError('SameValueNonNumeric requires two non-numeric values of the same type.');
}
return SameValue(x, y);
};

View File

@ -0,0 +1,19 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $TypeError = require('es-errors/type');
var $fromCharCode = GetIntrinsic('%String.fromCharCode%');
var isLeadingSurrogate = require('../helpers/isLeadingSurrogate');
var isTrailingSurrogate = require('../helpers/isTrailingSurrogate');
// https://tc39.es/ecma262/2020/#sec-utf16decodesurrogatepair
module.exports = function UTF16SurrogatePairToCodePoint(lead, trail) {
if (!isLeadingSurrogate(lead) || !isTrailingSurrogate(trail)) {
throw new $TypeError('Assertion failed: `lead` must be a leading surrogate char code, and `trail` must be a trailing surrogate char code');
}
// var cp = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
return $fromCharCode(lead) + $fromCharCode(trail);
};

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