feat: docker compose maybe

This commit is contained in:
2023-11-13 16:10:04 -05:00
parent 180b261e40
commit b625ccd8d6
8031 changed files with 2182966 additions and 0 deletions

View File

@ -0,0 +1,15 @@
import type ESTree from "estree";
import type { ScopeManager } from "eslint-scope";
import type { SvelteScriptElement } from "../ast";
/**
* Analyze scope
*/
export declare function analyzeScope(node: ESTree.Node, parserOptions?: any): ScopeManager;
/** Analyze reactive scope */
export declare function analyzeReactiveScope(scopeManager: ScopeManager): void;
/**
* Analyze store scope. e.g. $count
*/
export declare function analyzeStoreScope(scopeManager: ScopeManager): void;
/** Transform props exports */
export declare function analyzePropsScope(body: SvelteScriptElement, scopeManager: ScopeManager): void;

View File

@ -0,0 +1,210 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.analyzePropsScope = exports.analyzeStoreScope = exports.analyzeReactiveScope = exports.analyzeScope = void 0;
const eslint_scope_1 = require("eslint-scope");
const traverse_1 = require("../traverse");
const scope_1 = require("../scope");
const utils_1 = require("../utils");
/**
* Analyze scope
*/
function analyzeScope(node, parserOptions = {}) {
const ecmaVersion = parserOptions.ecmaVersion || 2020;
const ecmaFeatures = parserOptions.ecmaFeatures || {};
const sourceType = parserOptions.sourceType || "module";
const root = node.type === "Program"
? node
: {
type: "Program",
body: [node],
sourceType,
};
return (0, eslint_scope_1.analyze)(root, {
ignoreEval: true,
nodejsScope: false,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 2022,
sourceType,
fallback: traverse_1.getFallbackKeys,
});
}
exports.analyzeScope = analyzeScope;
/** Analyze reactive scope */
function analyzeReactiveScope(scopeManager) {
for (const reference of [...scopeManager.globalScope.through]) {
const parent = reference.writeExpr && getParent(reference.writeExpr);
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "AssignmentExpression") {
const pp = getParent(parent);
if ((pp === null || pp === void 0 ? void 0 : pp.type) === "ExpressionStatement") {
const ppp = getParent(pp);
if ((ppp === null || ppp === void 0 ? void 0 : ppp.type) === "SvelteReactiveStatement" && ppp.label.name === "$") {
const referenceScope = reference.from;
if (referenceScope.type === "module") {
// It is computed
transformComputedVariable(parent, ppp, reference);
continue;
}
}
}
}
}
/** Transform ref to ComputedVariable */
function transformComputedVariable(node, parent, reference) {
const referenceScope = reference.from;
const name = reference.identifier.name;
let variable = referenceScope.set.get(name);
if (!variable) {
variable = new eslint_scope_1.Variable();
variable.scope = referenceScope;
variable.name = name;
(0, utils_1.addElementToSortedArray)(variable.defs, {
type: "ComputedVariable",
node: node,
parent: parent,
name: reference.identifier,
}, (a, b) => a.node.range[0] - b.node.range[0]);
(0, scope_1.addVariable)(referenceScope.variables, variable);
referenceScope.set.set(name, variable);
}
(0, utils_1.addElementToSortedArray)(variable.identifiers, reference.identifier, (a, b) => a.range[0] - b.range[0]);
reference.resolved = variable;
removeReferenceFromThrough(reference, referenceScope);
}
}
exports.analyzeReactiveScope = analyzeReactiveScope;
/**
* Analyze store scope. e.g. $count
*/
function analyzeStoreScope(scopeManager) {
const moduleScope = scopeManager.scopes.find((scope) => scope.type === "module");
if (!moduleScope) {
return;
}
const toBeMarkAsUsedReferences = [];
for (const reference of [...scopeManager.globalScope.through]) {
if (reference.identifier.name.startsWith("$")) {
const realName = reference.identifier.name.slice(1);
const variable = moduleScope.set.get(realName);
if (variable) {
if (reference.isWriteOnly()) {
// Need mark as used
toBeMarkAsUsedReferences.push(reference);
}
// It does not write directly to the original variable.
// Therefore, this variable is always a reference.
reference.isWrite = () => false;
reference.isWriteOnly = () => false;
reference.isReadWrite = () => false;
reference.isReadOnly = () => true;
reference.isRead = () => true;
(0, scope_1.addReference)(variable.references, reference);
reference.resolved = variable;
removeReferenceFromThrough(reference, moduleScope);
}
}
}
for (const variable of new Set(toBeMarkAsUsedReferences.map((ref) => ref.resolved))) {
if (variable.references.some((ref) => !toBeMarkAsUsedReferences.includes(ref) &&
ref.identifier !== variable.identifiers[0])) {
// It is already used.
continue;
}
// Add the virtual reference for reading.
addVirtualReference(variable.identifiers[0], variable, moduleScope, {
read: true,
}).svelteMarkAsUsed = true;
}
}
exports.analyzeStoreScope = analyzeStoreScope;
/** Transform props exports */
function analyzePropsScope(body, scopeManager) {
const moduleScope = scopeManager.scopes.find((scope) => scope.type === "module");
if (!moduleScope) {
return;
}
for (const node of body.body) {
if (node.type !== "ExportNamedDeclaration") {
continue;
}
if (node.declaration) {
if (node.declaration.type === "VariableDeclaration") {
for (const decl of node.declaration.declarations) {
if (decl.id.type === "Identifier") {
addPropsReference(decl.id, moduleScope);
}
}
}
}
else {
for (const spec of node.specifiers) {
addPropsReference(spec.local, moduleScope);
}
}
}
/** Add virtual props reference */
function addPropsReference(node, scope) {
for (const variable of scope.variables) {
if (variable.name !== node.name) {
continue;
}
if (variable.references.some((ref) => ref.sveltePropReference)) {
continue;
}
// Add the virtual reference for writing.
const reference = addVirtualReference(Object.assign(Object.assign({}, node), {
// @ts-expect-error -- ignore
parent: body, loc: {
start: Object.assign({}, node.loc.start),
end: Object.assign({}, node.loc.end),
}, range: [...node.range] }), variable, scope, {
write: true,
read: true,
});
reference.sveltePropReference = true;
}
}
}
exports.analyzePropsScope = analyzePropsScope;
/** Remove reference from through */
function removeReferenceFromThrough(reference, baseScope) {
const variable = reference.resolved;
const name = reference.identifier.name;
let scope = baseScope;
while (scope) {
scope.through = scope.through.filter((ref) => {
if (reference === ref) {
return false;
}
else if (ref.identifier.name === name) {
ref.resolved = variable;
if (!variable.references.includes(ref)) {
(0, scope_1.addReference)(variable.references, ref);
}
return false;
}
return true;
});
scope = scope.upper;
}
}
/**
* Add the virtual reference.
*/
function addVirtualReference(node, variable, scope, readWrite) {
const reference = new eslint_scope_1.Reference();
reference.svelteVirtualReference = true;
reference.from = scope;
reference.identifier = node;
reference.isWrite = () => Boolean(readWrite.write);
reference.isWriteOnly = () => Boolean(readWrite.write) && !readWrite.read;
reference.isRead = () => Boolean(readWrite.read);
reference.isReadOnly = () => Boolean(readWrite.read) && !readWrite.write;
reference.isReadWrite = () => Boolean(readWrite.read && readWrite.write);
(0, scope_1.addReference)(variable.references, reference);
reference.resolved = variable;
return reference;
}
/** Get parent node */
function getParent(node) {
return node.parent;
}

View File

@ -0,0 +1,8 @@
import type { SvelteAttribute, SvelteShorthandAttribute, SvelteDirective, SvelteSpreadAttribute, SvelteStartTag, SvelteStyleDirective } from "../../ast";
import type { Context } from "../../context";
import type * as SvAST from "../svelte-ast-types";
import type { AttributeToken } from "../html";
/** Convert for Attributes */
export declare function convertAttributes(attributes: SvAST.AttributeOrDirective[], parent: SvelteStartTag, ctx: Context): IterableIterator<SvelteAttribute | SvelteShorthandAttribute | SvelteSpreadAttribute | SvelteDirective | SvelteStyleDirective>;
/** Convert for attribute tokens */
export declare function convertAttributeTokens(attributes: AttributeToken[], parent: SvelteStartTag, ctx: Context): IterableIterator<SvelteAttribute>;

View File

@ -0,0 +1,491 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertAttributeTokens = exports.convertAttributes = void 0;
const common_1 = require("./common");
const mustache_1 = require("./mustache");
const text_1 = require("./text");
const errors_1 = require("../../errors");
/** Convert for Attributes */
function* convertAttributes(attributes, parent, ctx) {
for (const attr of attributes) {
if (attr.type === "Attribute") {
yield convertAttribute(attr, parent, ctx);
continue;
}
if (attr.type === "Spread") {
yield convertSpreadAttribute(attr, parent, ctx);
continue;
}
if (attr.type === "Binding") {
yield convertBindingDirective(attr, parent, ctx);
continue;
}
if (attr.type === "EventHandler") {
yield convertEventHandlerDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Class") {
yield convertClassDirective(attr, parent, ctx);
continue;
}
if (attr.type === "StyleDirective") {
yield convertStyleDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Transition") {
yield convertTransitionDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Animation") {
yield convertAnimationDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Action") {
yield convertActionDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Let") {
yield convertLetDirective(attr, parent, ctx);
continue;
}
if (attr.type === "Ref") {
throw new errors_1.ParseError("Ref are not supported.", attr.start, ctx);
}
if (attr.type === "Style") {
throw new errors_1.ParseError(`Svelte v3.46.0 is no longer supported. Please use Svelte>=v3.46.1.`, attr.start, ctx);
}
throw new errors_1.ParseError(`Unknown directive or attribute (${attr.type}) are not supported.`, attr.start, ctx);
}
}
exports.convertAttributes = convertAttributes;
/** Convert for attribute tokens */
function* convertAttributeTokens(attributes, parent, ctx) {
var _a, _b;
for (const attr of attributes) {
const attribute = Object.assign({ type: "SvelteAttribute", boolean: false, key: null, value: [], parent }, ctx.getConvertLocation({
start: attr.key.start,
end: (_b = (_a = attr.value) === null || _a === void 0 ? void 0 : _a.end) !== null && _b !== void 0 ? _b : attr.key.end,
}));
attribute.key = Object.assign({ type: "SvelteName", name: attr.key.name, parent: attribute }, ctx.getConvertLocation(attr.key));
ctx.addToken("HTMLIdentifier", attr.key);
if (attr.value == null) {
attribute.boolean = true;
}
else {
attribute.value.push((0, text_1.convertAttributeValueTokenToLiteral)(attr.value, attribute, ctx));
}
yield attribute;
}
}
exports.convertAttributeTokens = convertAttributeTokens;
/** Convert for Attribute */
function convertAttribute(node, parent, ctx) {
const attribute = Object.assign({ type: "SvelteAttribute", boolean: false, key: null, value: [], parent }, ctx.getConvertLocation(node));
const keyStart = ctx.code.indexOf(node.name, node.start);
const keyRange = { start: keyStart, end: keyStart + node.name.length };
attribute.key = Object.assign({ type: "SvelteName", name: node.name, parent: attribute }, ctx.getConvertLocation(keyRange));
if (node.value === true) {
// Boolean attribute
attribute.boolean = true;
ctx.addToken("HTMLIdentifier", keyRange);
return attribute;
}
const shorthand = node.value.find((v) => v.type === "AttributeShorthand");
if (shorthand) {
const key = Object.assign(Object.assign({}, attribute.key), { type: "Identifier" });
const sAttr = {
type: "SvelteShorthandAttribute",
key,
value: key,
parent,
loc: attribute.loc,
range: attribute.range,
};
key.parent = sAttr;
ctx.scriptLet.addObjectShorthandProperty(attribute.key, sAttr, (es) => {
if (
// FIXME: Older parsers may use the same node. In that case, do not replace.
// We will drop support for ESLint v7 in the next major version and remove this branch.
es.key !== es.value) {
sAttr.key = es.key;
}
sAttr.value = es.value;
});
return sAttr;
}
processAttributeValue(node.value, attribute, ctx);
// Not required for shorthands. Therefore, register the token here.
ctx.addToken("HTMLIdentifier", keyRange);
return attribute;
}
/** Common process attribute value */
function processAttributeValue(nodeValue, attribute, ctx) {
for (let index = 0; index < nodeValue.length; index++) {
const v = nodeValue[index];
if (v.type === "Text") {
if (v.start === v.end) {
// Empty
// https://github.com/sveltejs/svelte/pull/6539
continue;
}
const next = nodeValue[index + 1];
if (next && next.start < v.end) {
// Maybe bug in Svelte can cause the completion index to shift.
// console.log(ctx.getText(v), v.data)
v.end = next.start;
}
attribute.value.push((0, text_1.convertTextToLiteral)(v, attribute, ctx));
continue;
}
if (v.type === "MustacheTag") {
const mustache = (0, mustache_1.convertMustacheTag)(v, attribute, ctx);
attribute.value.push(mustache);
continue;
}
const u = v;
throw new errors_1.ParseError(`Unknown attribute value (${u.type}) are not supported.`, u.start, ctx);
}
}
/** Convert for Spread */
function convertSpreadAttribute(node, parent, ctx) {
const attribute = Object.assign({ type: "SvelteSpreadAttribute", argument: null, parent }, ctx.getConvertLocation(node));
const spreadStart = ctx.code.indexOf("...", node.start);
ctx.addToken("Punctuator", {
start: spreadStart,
end: spreadStart + 3,
});
ctx.scriptLet.addExpression(node.expression, attribute, null, (es) => {
attribute.argument = es;
});
return attribute;
}
/** Convert for Binding Directive */
function convertBindingDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteDirective", kind: "Binding", key: null, shorthand: false, expression: null, parent }, ctx.getConvertLocation(node));
processDirective(node, directive, ctx, {
processExpression(expression, shorthand) {
directive.shorthand = shorthand;
return ctx.scriptLet.addExpression(expression, directive, null, (es, { getScope }) => {
directive.expression = es;
const scope = getScope(es);
const reference = scope.references.find((ref) => ref.identifier === es);
if (reference) {
// The bind directive does read and write.
reference.isWrite = () => true;
reference.isWriteOnly = () => false;
reference.isReadWrite = () => true;
reference.isReadOnly = () => false;
reference.isRead = () => true;
}
});
},
});
return directive;
}
/** Convert for EventHandler Directive */
function convertEventHandlerDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteDirective", kind: "EventHandler", key: null, expression: null, parent }, ctx.getConvertLocation(node));
const typing = buildEventHandlerType(parent.parent, node.name, ctx);
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, typing),
});
return directive;
}
/** Build event handler type */
function buildEventHandlerType(element, eventName, ctx) {
const nativeEventHandlerType = `(e:${conditional({
check: `'${eventName}'`,
extends: `infer EVT`,
true: conditional({
check: `EVT`,
extends: `keyof HTMLElementEventMap`,
true: `HTMLElementEventMap[EVT]`,
false: `CustomEvent<any>`,
}),
false: `never`,
})})=>void`;
if (element.type !== "SvelteElement") {
return nativeEventHandlerType;
}
const elementName = ctx.elements.get(element).name;
if (element.kind === "component") {
const componentEventsType = `import('svelte').ComponentEvents<${elementName}>`;
return `(e:${conditional({
check: `0`,
extends: `(1 & ${componentEventsType})`,
// `componentEventsType` is `any`
// `@typescript-eslint/parser` currently cannot parse `*.svelte` import types correctly.
// So if we try to do a correct type parsing, it's argument type will be `any`.
// A workaround is to inject the type directly, as `CustomEvent<any>` is better than `any`.
true: `CustomEvent<any>`,
// `componentEventsType` has an exact type.
false: conditional({
check: `'${eventName}'`,
extends: `infer EVT`,
true: conditional({
check: `EVT`,
extends: `keyof ${componentEventsType}`,
true: `${componentEventsType}[EVT]`,
false: `CustomEvent<any>`,
}),
false: `never`,
}),
})})=>void`;
}
if (element.kind === "special") {
if (elementName === "svelte:component")
return `(e:CustomEvent<any>)=>void`;
return nativeEventHandlerType;
}
const attrName = `on:${eventName}`;
const svelteHTMLElementsType = "import('svelte/elements').SvelteHTMLElements";
return conditional({
check: `'${elementName}'`,
extends: "infer EL",
true: conditional({
check: `EL`,
extends: `keyof ${svelteHTMLElementsType}`,
true: conditional({
check: `'${attrName}'`,
extends: "infer ATTR",
true: conditional({
check: `ATTR`,
extends: `keyof ${svelteHTMLElementsType}[EL]`,
true: `${svelteHTMLElementsType}[EL][ATTR]`,
false: nativeEventHandlerType,
}),
false: `never`,
}),
false: nativeEventHandlerType,
}),
false: `never`,
});
/** Generate `C extends E ? T : F` type. */
function conditional(types) {
return `${types.check} extends ${types.extends}?(${types.true}):(${types.false})`;
}
}
/** Convert for Class Directive */
function convertClassDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteDirective", kind: "Class", key: null, shorthand: false, expression: null, parent }, ctx.getConvertLocation(node));
processDirective(node, directive, ctx, {
processExpression(expression, shorthand) {
directive.shorthand = shorthand;
return ctx.scriptLet.addExpression(expression, directive);
},
});
return directive;
}
/** Convert for Style Directive */
function convertStyleDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteStyleDirective", key: null, shorthand: false, value: [], parent }, ctx.getConvertLocation(node));
processDirectiveKey(node, directive, ctx);
const keyName = directive.key.name;
if (node.value === true) {
const shorthandDirective = directive;
shorthandDirective.shorthand = true;
ctx.scriptLet.addExpression(keyName, shorthandDirective.key, null, (expression) => {
if (expression.type !== "Identifier") {
throw new errors_1.ParseError(`Expected JS identifier or attribute value.`, expression.range[0], ctx);
}
shorthandDirective.key.name = expression;
});
return shorthandDirective;
}
ctx.addToken("HTMLIdentifier", {
start: keyName.range[0],
end: keyName.range[1],
});
processAttributeValue(node.value, directive, ctx);
return directive;
}
/** Convert for Transition Directive */
function convertTransitionDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteDirective", kind: "Transition", intro: node.intro, outro: node.outro, key: null, expression: null, parent }, ctx.getConvertLocation(node));
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, null),
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier"], ctx)),
});
return directive;
}
/** Convert for Animation Directive */
function convertAnimationDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteDirective", kind: "Animation", key: null, expression: null, parent }, ctx.getConvertLocation(node));
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, null),
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier"], ctx)),
});
return directive;
}
/** Convert for Action Directive */
function convertActionDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteDirective", kind: "Action", key: null, expression: null, parent }, ctx.getConvertLocation(node));
processDirective(node, directive, ctx, {
processExpression: buildProcessExpressionForExpression(directive, ctx, `Parameters<typeof ${node.name}>[1]`),
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier", "MemberExpression"], ctx)),
});
return directive;
}
/** Convert for Let Directive */
function convertLetDirective(node, parent, ctx) {
const directive = Object.assign({ type: "SvelteDirective", kind: "Let", key: null, expression: null, parent }, ctx.getConvertLocation(node));
processDirective(node, directive, ctx, {
processPattern(pattern) {
return ctx.letDirCollections
.getCollection()
.addPattern(pattern, directive, buildLetDirectiveType(parent.parent, node.name, ctx));
},
processName: node.expression
? undefined
: (name) => {
// shorthand
ctx.letDirCollections
.getCollection()
.addPattern(name, directive, buildLetDirectiveType(parent.parent, node.name, ctx), (es) => {
directive.expression = es;
});
return [];
},
});
return directive;
}
/** Build let directive param type */
function buildLetDirectiveType(element, letName, ctx) {
if (element.type !== "SvelteElement") {
return "any";
}
let slotName = "default";
let componentName;
const svelteNode = ctx.elements.get(element);
const slotAttr = svelteNode.attributes.find((attr) => {
return attr.type === "Attribute" && attr.name === "slot";
});
if (slotAttr) {
if (Array.isArray(slotAttr.value) &&
slotAttr.value.length === 1 &&
slotAttr.value[0].type === "Text") {
slotName = slotAttr.value[0].data;
}
else {
return "any";
}
const parent = findParentComponent(element);
if (parent == null)
return "any";
componentName = ctx.elements.get(parent).name;
}
else {
if (element.kind === "component") {
componentName = svelteNode.name;
}
else {
const parent = findParentComponent(element);
if (parent == null)
return "any";
componentName = ctx.elements.get(parent).name;
}
}
return `${String(componentName)}['$$slot_def'][${JSON.stringify(slotName)}][${JSON.stringify(letName)}]`;
/** Find parent component element */
function findParentComponent(node) {
let parent = node.parent;
while (parent && parent.type !== "SvelteElement") {
parent = parent.parent;
}
if (!parent || parent.kind !== "component") {
return null;
}
return parent;
}
}
/** Common process for directive */
function processDirective(node, directive, ctx, processors) {
processDirectiveKey(node, directive, ctx);
processDirectiveExpression(node, directive, ctx, processors);
}
/** Common process for directive key */
function processDirectiveKey(node, directive, ctx) {
const colonIndex = ctx.code.indexOf(":", directive.range[0]);
ctx.addToken("HTMLIdentifier", {
start: directive.range[0],
end: colonIndex,
});
const nameIndex = ctx.code.indexOf(node.name, colonIndex + 1);
const nameRange = {
start: nameIndex,
end: nameIndex + node.name.length,
};
let keyEndIndex = nameRange.end;
// modifiers
if (ctx.code[nameRange.end] === "|") {
let nextStart = nameRange.end + 1;
let nextEnd = (0, common_1.indexOf)(ctx.code, (c) => c === "=" || c === ">" || c === "/" || c === "|" || !c.trim(), nextStart);
ctx.addToken("HTMLIdentifier", { start: nextStart, end: nextEnd });
while (ctx.code[nextEnd] === "|") {
nextStart = nextEnd + 1;
nextEnd = (0, common_1.indexOf)(ctx.code, (c) => c === "=" || c === ">" || c === "/" || c === "|" || !c.trim(), nextStart);
ctx.addToken("HTMLIdentifier", { start: nextStart, end: nextEnd });
}
keyEndIndex = nextEnd;
}
const key = (directive.key = Object.assign({ type: "SvelteDirectiveKey", name: null, modifiers: node.modifiers, parent: directive }, ctx.getConvertLocation({ start: node.start, end: keyEndIndex })));
// put name
key.name = Object.assign({ type: "SvelteName", name: node.name, parent: key }, ctx.getConvertLocation(nameRange));
}
/** Common process for directive expression */
function processDirectiveExpression(node, directive, ctx, processors) {
const key = directive.key;
const keyName = key.name;
let shorthand = false;
if (node.expression) {
shorthand =
node.expression.type === "Identifier" &&
node.expression.name === node.name &&
(0, common_1.getWithLoc)(node.expression).start === keyName.range[0];
if (shorthand && (0, common_1.getWithLoc)(node.expression).end !== keyName.range[1]) {
// The identifier location may be incorrect in some edge cases.
// e.g. bind:value=""
(0, common_1.getWithLoc)(node.expression).end = keyName.range[1];
}
if (processors.processExpression) {
processors.processExpression(node.expression, shorthand).push((es) => {
if (node.expression && es.type !== node.expression.type) {
throw new errors_1.ParseError(`Expected ${node.expression.type}, but ${es.type} found.`, es.range[0], ctx);
}
directive.expression = es;
});
}
else {
processors.processPattern(node.expression, shorthand).push((es) => {
directive.expression = es;
});
}
}
if (!shorthand) {
if (processors.processName) {
processors.processName(keyName).push((es) => {
key.name = es;
});
}
else {
ctx.addToken("HTMLIdentifier", {
start: keyName.range[0],
end: keyName.range[1],
});
}
}
}
/** Build processExpression for Expression */
function buildProcessExpressionForExpression(directive, ctx, typing) {
return (expression) => {
return ctx.scriptLet.addExpression(expression, directive, typing);
};
}
/** Build expression type checker to script let callbacks */
function buildExpressionTypeChecker(expected, ctx) {
return (node) => {
if (!expected.includes(node.type)) {
throw new errors_1.ParseError(`Expected JS ${expected.join(", or ")}, but ${node.type} found.`, node.range[0], ctx);
}
};
}

View File

@ -0,0 +1,11 @@
import type * as SvAST from "../svelte-ast-types";
import type { SvelteAwaitBlock, SvelteEachBlock, SvelteIfBlock, SvelteIfBlockAlone, SvelteIfBlockElseIf, SvelteKeyBlock } from "../../ast";
import type { Context } from "../../context";
export declare function convertIfBlock(node: SvAST.IfBlock, parent: SvelteIfBlock["parent"], ctx: Context): SvelteIfBlockAlone;
export declare function convertIfBlock(node: SvAST.IfBlock, parent: SvelteIfBlock["parent"], ctx: Context, elseif: true): SvelteIfBlockElseIf;
/** Convert for EachBlock */
export declare function convertEachBlock(node: SvAST.EachBlock, parent: SvelteEachBlock["parent"], ctx: Context): SvelteEachBlock;
/** Convert for AwaitBlock */
export declare function convertAwaitBlock(node: SvAST.AwaitBlock, parent: SvelteAwaitBlock["parent"], ctx: Context): SvelteAwaitBlock;
/** Convert for KeyBlock */
export declare function convertKeyBlock(node: SvAST.KeyBlock, parent: SvelteKeyBlock["parent"], ctx: Context): SvelteKeyBlock;

View File

@ -0,0 +1,308 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertKeyBlock = exports.convertAwaitBlock = exports.convertEachBlock = exports.convertIfBlock = void 0;
const element_1 = require("./element");
const common_1 = require("./common");
/** Get start index of block */
function startBlockIndex(code, endIndex) {
return (0, common_1.lastIndexOf)(code, (c, index) => {
if (c !== "{") {
return false;
}
for (let next = index + 1; next < code.length; next++) {
const nextC = code[next];
if (!nextC.trim()) {
continue;
}
return code.startsWith("#if", next) || code.startsWith(":else", next);
}
return false;
}, endIndex);
}
/** Convert for IfBlock */
function convertIfBlock(node, parent, ctx, elseif) {
// {#if expr} {:else} {/if}
// {:else if expr} {/if}
const nodeStart = elseif
? startBlockIndex(ctx.code, node.start - 1)
: node.start;
const ifBlock = Object.assign({ type: "SvelteIfBlock", elseif: Boolean(elseif), expression: null, children: [], else: null, parent }, ctx.getConvertLocation({ start: nodeStart, end: node.end }));
ctx.scriptLet.nestIfBlock(node.expression, ifBlock, (es) => {
ifBlock.expression = es;
});
ifBlock.children.push(...(0, element_1.convertChildren)(node, ifBlock, ctx));
ctx.scriptLet.closeScope();
if (elseif) {
const index = ctx.code.indexOf("if", nodeStart);
ctx.addToken("MustacheKeyword", { start: index, end: index + 2 });
}
extractMustacheBlockTokens(ifBlock, ctx, { startOnly: elseif });
if (!node.else) {
return ifBlock;
}
const elseStart = startBlockIndex(ctx.code, node.else.start - 1);
if (node.else.children.length === 1) {
const c = node.else.children[0];
if (c.type === "IfBlock" && c.elseif) {
const elseBlock = Object.assign({ type: "SvelteElseBlock", elseif: true, children: [], parent: ifBlock }, ctx.getConvertLocation({
start: elseStart,
end: node.else.end,
}));
ifBlock.else = elseBlock;
const elseIfBlock = convertIfBlock(c, elseBlock, ctx, true);
// adjust loc
elseBlock.range[1] = elseIfBlock.range[1];
elseBlock.loc.end = {
line: elseIfBlock.loc.end.line,
column: elseIfBlock.loc.end.column,
};
elseBlock.children = [elseIfBlock];
return ifBlock;
}
}
const elseBlock = Object.assign({ type: "SvelteElseBlock", elseif: false, children: [], parent: ifBlock }, ctx.getConvertLocation({
start: elseStart,
end: node.else.end,
}));
ifBlock.else = elseBlock;
ctx.scriptLet.nestBlock(elseBlock);
elseBlock.children.push(...(0, element_1.convertChildren)(node.else, elseBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(elseBlock, ctx, { startOnly: true });
return ifBlock;
}
exports.convertIfBlock = convertIfBlock;
/** Convert for EachBlock */
function convertEachBlock(node, parent, ctx) {
// {#each expr as item, index (key)} {/each}
const eachBlock = Object.assign({ type: "SvelteEachBlock", expression: null, context: null, index: null, key: null, children: [], else: null, parent }, ctx.getConvertLocation(node));
let indexRange = null;
if (node.index) {
const start = ctx.code.indexOf(node.index, (0, common_1.getWithLoc)(node.context).end);
indexRange = {
start,
end: start + node.index.length,
};
}
ctx.scriptLet.nestEachBlock(node.expression, node.context, indexRange, eachBlock, (expression, context, index) => {
eachBlock.expression = expression;
eachBlock.context = context;
eachBlock.index = index;
});
const asStart = ctx.code.indexOf("as", (0, common_1.getWithLoc)(node.expression).end);
ctx.addToken("Keyword", {
start: asStart,
end: asStart + 2,
});
if (node.key) {
ctx.scriptLet.addExpression(node.key, eachBlock, null, (key) => {
eachBlock.key = key;
});
}
eachBlock.children.push(...(0, element_1.convertChildren)(node, eachBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(eachBlock, ctx);
if (!node.else) {
return eachBlock;
}
const elseStart = startBlockIndex(ctx.code, node.else.start - 1);
const elseBlock = Object.assign({ type: "SvelteElseBlock", elseif: false, children: [], parent: eachBlock }, ctx.getConvertLocation({
start: elseStart,
end: node.else.end,
}));
eachBlock.else = elseBlock;
ctx.scriptLet.nestBlock(elseBlock);
elseBlock.children.push(...(0, element_1.convertChildren)(node.else, elseBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(elseBlock, ctx, { startOnly: true });
return eachBlock;
}
exports.convertEachBlock = convertEachBlock;
/** Convert for AwaitBlock */
function convertAwaitBlock(node, parent, ctx) {
const awaitBlock = Object.assign({ type: "SvelteAwaitBlock", expression: null, kind: "await", pending: null, then: null, catch: null, parent }, ctx.getConvertLocation(node));
ctx.scriptLet.addExpression(node.expression, awaitBlock, null, (expression) => {
awaitBlock.expression = expression;
});
if (!node.pending.skip) {
const pendingBlock = Object.assign({ type: "SvelteAwaitPendingBlock", children: [], parent: awaitBlock }, ctx.getConvertLocation({
start: awaitBlock.range[0],
end: node.pending.end,
}));
ctx.scriptLet.nestBlock(pendingBlock);
pendingBlock.children.push(...(0, element_1.convertChildren)(node.pending, pendingBlock, ctx));
awaitBlock.pending = pendingBlock;
ctx.scriptLet.closeScope();
}
if (!node.then.skip) {
const awaitThen = Boolean(node.pending.skip);
if (awaitThen) {
awaitBlock.kind = "await-then";
}
const thenStart = awaitBlock.pending ? node.then.start : node.start;
const thenBlock = Object.assign({ type: "SvelteAwaitThenBlock", awaitThen, value: null, children: [], parent: awaitBlock }, ctx.getConvertLocation({
start: thenStart,
end: node.then.end,
}));
if (node.value) {
const baseParam = {
node: node.value,
parent: thenBlock,
callback(value) {
thenBlock.value = value;
},
typing: "any",
};
ctx.scriptLet.nestBlock(thenBlock, (typeCtx) => {
if (!typeCtx) {
return {
param: baseParam,
};
}
const expression = ctx.getText(node.expression);
if (node.expression.type === "Literal") {
return {
param: Object.assign(Object.assign({}, baseParam), { typing: expression }),
};
}
const idAwaitThenValue = typeCtx.generateUniqueId("AwaitThenValue");
if (node.expression.type === "Identifier" &&
// We cannot use type annotations like `(x: Foo<x>)` if they have the same identifier name.
!hasIdentifierFor(node.expression.name, baseParam.node)) {
return {
preparationScript: [generateAwaitThenValueType(idAwaitThenValue)],
param: Object.assign(Object.assign({}, baseParam), { typing: `${idAwaitThenValue}<(typeof ${expression})>` }),
};
}
const id = typeCtx.generateUniqueId(expression);
return {
preparationScript: [
`const ${id} = ${expression};`,
generateAwaitThenValueType(idAwaitThenValue),
],
param: Object.assign(Object.assign({}, baseParam), { typing: `${idAwaitThenValue}<(typeof ${id})>` }),
};
});
}
else {
ctx.scriptLet.nestBlock(thenBlock);
}
thenBlock.children.push(...(0, element_1.convertChildren)(node.then, thenBlock, ctx));
if (awaitBlock.pending) {
extractMustacheBlockTokens(thenBlock, ctx, { startOnly: true });
}
else {
const thenIndex = ctx.code.indexOf("then", (0, common_1.getWithLoc)(node.expression).end);
ctx.addToken("MustacheKeyword", {
start: thenIndex,
end: thenIndex + 4,
});
}
awaitBlock.then = thenBlock;
ctx.scriptLet.closeScope();
}
if (!node.catch.skip) {
const awaitCatch = Boolean(node.pending.skip && node.then.skip);
if (awaitCatch) {
awaitBlock.kind = "await-catch";
}
const catchStart = awaitBlock.pending || awaitBlock.then ? node.catch.start : node.start;
const catchBlock = Object.assign({ type: "SvelteAwaitCatchBlock", awaitCatch, error: null, children: [], parent: awaitBlock }, ctx.getConvertLocation({
start: catchStart,
end: node.catch.end,
}));
if (node.error) {
ctx.scriptLet.nestBlock(catchBlock, [
{
node: node.error,
parent: catchBlock,
typing: "Error",
callback: (error) => {
catchBlock.error = error;
},
},
]);
}
else {
ctx.scriptLet.nestBlock(catchBlock);
}
catchBlock.children.push(...(0, element_1.convertChildren)(node.catch, catchBlock, ctx));
if (awaitBlock.pending || awaitBlock.then) {
extractMustacheBlockTokens(catchBlock, ctx, { startOnly: true });
}
else {
const catchIndex = ctx.code.indexOf("catch", (0, common_1.getWithLoc)(node.expression).end);
ctx.addToken("MustacheKeyword", {
start: catchIndex,
end: catchIndex + 5,
});
}
awaitBlock.catch = catchBlock;
ctx.scriptLet.closeScope();
}
extractMustacheBlockTokens(awaitBlock, ctx);
return awaitBlock;
}
exports.convertAwaitBlock = convertAwaitBlock;
/** Convert for KeyBlock */
function convertKeyBlock(node, parent, ctx) {
const keyBlock = Object.assign({ type: "SvelteKeyBlock", expression: null, children: [], parent }, ctx.getConvertLocation(node));
ctx.scriptLet.addExpression(node.expression, keyBlock, null, (expression) => {
keyBlock.expression = expression;
});
ctx.scriptLet.nestBlock(keyBlock);
keyBlock.children.push(...(0, element_1.convertChildren)(node, keyBlock, ctx));
ctx.scriptLet.closeScope();
extractMustacheBlockTokens(keyBlock, ctx);
return keyBlock;
}
exports.convertKeyBlock = convertKeyBlock;
/** Extract mustache block tokens */
function extractMustacheBlockTokens(node, ctx, option) {
const startSectionNameStart = (0, common_1.indexOf)(ctx.code, (c) => Boolean(c.trim()), node.range[0] + 1);
const startSectionNameEnd = (0, common_1.indexOf)(ctx.code, (c) => c === "}" || !c.trim(), startSectionNameStart + 1);
ctx.addToken("MustacheKeyword", {
start: startSectionNameStart,
end: startSectionNameEnd,
});
if (option === null || option === void 0 ? void 0 : option.startOnly) {
return;
}
const endSectionNameEnd = (0, common_1.lastIndexOf)(ctx.code, (c) => Boolean(c.trim()), node.range[1] - 2) + 1;
const endSectionNameStart = (0, common_1.lastIndexOf)(ctx.code, (c) => c === "{" || c === "/" || !c.trim(), endSectionNameEnd - 1);
ctx.addToken("MustacheKeyword", {
start: endSectionNameStart,
end: endSectionNameEnd,
});
}
/** Generate Awaited like type code */
function generateAwaitThenValueType(id) {
return `type ${id}<T> = T extends null | undefined
? T
: T extends { then(value: infer F): any }
? F extends (value: infer V, ...args: any) => any
? ${id}<V>
: never
: T;`;
}
/** Checks whether the given name identifier is exists or not. */
function hasIdentifierFor(name, node) {
if (node.type === "Identifier") {
return node.name === name;
}
if (node.type === "ObjectPattern") {
return node.properties.some((property) => property.type === "Property"
? hasIdentifierFor(name, property.value)
: hasIdentifierFor(name, property));
}
if (node.type === "ArrayPattern") {
return node.elements.some((element) => element && hasIdentifierFor(name, element));
}
if (node.type === "RestElement") {
return hasIdentifierFor(name, node.argument);
}
if (node.type === "AssignmentPattern") {
return hasIdentifierFor(name, node.left);
}
return false;
}

View File

@ -0,0 +1,23 @@
import type ESTree from "estree";
/** indexOf */
export declare function indexOf(str: string, search: (c: string, index: number) => boolean, start: number, end?: number): number;
/** lastIndexOf */
export declare function lastIndexOf(str: string, search: (c: string, index: number) => boolean, end: number): number;
export declare function getWithLoc<N extends ESTree.Comment>(node: N): N & {
start: number;
end: number;
};
export declare function getWithLoc<N extends ESTree.Node | {
start: number;
end: number;
}>(node: N): N & {
start: number;
end: number;
};
export declare function getWithLoc<N extends ESTree.Node | {
start: number;
end: number;
}>(node: N | null | undefined): (N & {
start: number;
end: number;
}) | null | undefined;

View File

@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWithLoc = exports.lastIndexOf = exports.indexOf = void 0;
/** indexOf */
function indexOf(str, search, start, end) {
const endIndex = end !== null && end !== void 0 ? end : str.length;
for (let index = start; index < endIndex; index++) {
const c = str[index];
if (search(c, index)) {
return index;
}
}
return -1;
}
exports.indexOf = indexOf;
/** lastIndexOf */
function lastIndexOf(str, search, end) {
for (let index = end; index >= 0; index--) {
const c = str[index];
if (search(c, index)) {
return index;
}
}
return -1;
}
exports.lastIndexOf = lastIndexOf;
/** Get node with location */
function getWithLoc(node) {
return node;
}
exports.getWithLoc = getWithLoc;

View File

@ -0,0 +1,5 @@
import type { SvelteConstTag } from "../../ast";
import type { Context } from "../../context";
import type * as SvAST from "../svelte-ast-types";
/** Convert for ConstTag */
export declare function convertConstTag(node: SvAST.ConstTag, parent: SvelteConstTag["parent"], ctx: Context): SvelteConstTag;

View File

@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertConstTag = void 0;
/** Convert for ConstTag */
function convertConstTag(node, parent, ctx) {
const mustache = Object.assign({ type: "SvelteConstTag", declaration: null, parent }, ctx.getConvertLocation(node));
ctx.scriptLet.addVariableDeclarator(node.expression, mustache, (declaration) => {
mustache.declaration = declaration;
});
const atConstStart = ctx.code.indexOf("@const", mustache.range[0]);
ctx.addToken("MustacheKeyword", {
start: atConstStart,
end: atConstStart + 6,
});
return mustache;
}
exports.convertConstTag = convertConstTag;

View File

@ -0,0 +1,15 @@
import type { SvelteAwaitBlock, SvelteAwaitCatchBlock, SvelteAwaitPendingBlock, SvelteAwaitThenBlock, SvelteConstTag, SvelteDebugTag, SvelteEachBlock, SvelteElement, SvelteElseBlockAlone, SvelteHTMLComment, SvelteIfBlock, SvelteIfBlockAlone, SvelteKeyBlock, SvelteMustacheTag, SvelteProgram, SvelteScriptElement, SvelteStyleElement, SvelteText } from "../../ast";
import type { Context } from "../../context";
import type * as SvAST from "../svelte-ast-types";
/** Convert for Fragment or Element or ... */
export declare function convertChildren(fragment: {
children: SvAST.TemplateNode[];
}, parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock, ctx: Context): IterableIterator<SvelteText | SvelteElement | SvelteMustacheTag | SvelteDebugTag | SvelteConstTag | SvelteIfBlockAlone | SvelteEachBlock | SvelteAwaitBlock | SvelteKeyBlock | SvelteHTMLComment>;
/** Extract element tag and tokens */
export declare function extractElementTags<E extends SvelteScriptElement | SvelteElement | SvelteStyleElement>(element: E, ctx: Context, options: {
buildNameNode: (openTokenRange: {
start: number;
end: number;
}) => E["name"];
extractAttribute?: boolean;
}): void;

View File

@ -0,0 +1,522 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractElementTags = exports.convertChildren = void 0;
const block_1 = require("./block");
const common_1 = require("./common");
const mustache_1 = require("./mustache");
const text_1 = require("./text");
const attr_1 = require("./attr");
const const_1 = require("./const");
const sort_1 = require("../sort");
const __1 = require("../..");
/* eslint-disable complexity -- X */
/** Convert for Fragment or Element or ... */
function* convertChildren(
/* eslint-enable complexity -- X */
fragment, parent, ctx) {
for (const child of fragment.children) {
if (child.type === "Comment") {
yield convertComment(child, parent, ctx);
continue;
}
if (child.type === "Text") {
if (!child.data && child.start === child.end) {
continue;
}
yield (0, text_1.convertText)(child, parent, ctx);
continue;
}
if (child.type === "Element") {
if (child.name.includes(":")) {
yield convertSpecialElement(child, parent, ctx);
}
else {
yield convertHTMLElement(child, parent, ctx);
}
continue;
}
if (child.type === "InlineComponent") {
if (child.name.includes(":")) {
yield convertSpecialElement(child, parent, ctx);
}
else {
yield convertComponentElement(child, parent, ctx);
}
continue;
}
if (child.type === "Slot") {
yield convertSlotElement(child, parent, ctx);
continue;
}
if (child.type === "MustacheTag") {
yield (0, mustache_1.convertMustacheTag)(child, parent, ctx);
continue;
}
if (child.type === "RawMustacheTag") {
yield (0, mustache_1.convertRawMustacheTag)(child, parent, ctx);
continue;
}
if (child.type === "IfBlock") {
// {#if expr} {/if}
yield (0, block_1.convertIfBlock)(child, parent, ctx);
continue;
}
if (child.type === "EachBlock") {
// {#each expr as item, index (key)} {/each}
yield (0, block_1.convertEachBlock)(child, parent, ctx);
continue;
}
if (child.type === "AwaitBlock") {
// {#await promise} {:then number} {:catch error} {/await}
yield (0, block_1.convertAwaitBlock)(child, parent, ctx);
continue;
}
if (child.type === "KeyBlock") {
// {#key expression}...{/key}
yield (0, block_1.convertKeyBlock)(child, parent, ctx);
continue;
}
if (child.type === "Window") {
yield convertWindowElement(child, parent, ctx);
continue;
}
if (child.type === "Body") {
yield convertBodyElement(child, parent, ctx);
continue;
}
if (child.type === "Head") {
yield convertHeadElement(child, parent, ctx);
continue;
}
if (child.type === "Title") {
yield convertTitleElement(child, parent, ctx);
continue;
}
if (child.type === "Options") {
yield convertOptionsElement(child, parent, ctx);
continue;
}
if (child.type === "SlotTemplate") {
yield convertSlotTemplateElement(child, parent, ctx);
continue;
}
if (child.type === "DebugTag") {
yield (0, mustache_1.convertDebugTag)(child, parent, ctx);
continue;
}
if (child.type === "ConstTag") {
yield (0, const_1.convertConstTag)(child, parent, ctx);
continue;
}
if (child.type === "Document") {
yield convertDocumentElement(child, parent, ctx);
continue;
}
throw new Error(`Unknown type:${child.type}`);
}
}
exports.convertChildren = convertChildren;
/** Extract `let:` directives. */
function extractLetDirectives(fragment) {
const letDirectives = [];
const attributes = [];
for (const attr of fragment.attributes) {
if (attr.type === "Let") {
letDirectives.push(attr);
}
else {
attributes.push(attr);
}
}
return { letDirectives, attributes };
}
/** Check if children needs a scope. */
function needScopeByChildren(fragment) {
for (const child of fragment.children) {
if (child.type === "ConstTag") {
return true;
}
}
return false;
}
/** Convert for HTML Comment */
function convertComment(node, parent, ctx) {
const comment = Object.assign({ type: "SvelteHTMLComment", value: node.data, parent }, ctx.getConvertLocation(node));
ctx.addToken("HTMLComment", node);
return comment;
}
/** Convert for HTMLElement */
function convertHTMLElement(node, parent, ctx) {
var _a, _b;
const locs = ctx.getConvertLocation(node);
const element = Object.assign({ type: "SvelteElement", kind: "html", name: null, startTag: {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: null,
range: [locs.range[0], null],
loc: {
start: {
line: locs.loc.start.line,
column: locs.loc.start.column,
},
end: null,
},
}, children: [], endTag: null, parent }, locs);
ctx.elements.set(element, node);
element.startTag.parent = element;
const elementName = node.name;
const { letDirectives, attributes } = extractLetDirectives(node);
const letParams = [];
if (letDirectives.length) {
ctx.letDirCollections.beginExtract();
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(letDirectives, element.startTag, ctx));
letParams.push(...ctx.letDirCollections.extract().getLetParams());
}
if (!letParams.length && !needScopeByChildren(node)) {
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(attributes, element.startTag, ctx));
element.children.push(...convertChildren(node, element, ctx));
}
else {
ctx.scriptLet.nestBlock(element, letParams);
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(attributes, element.startTag, ctx));
(0, sort_1.sortNodes)(element.startTag.attributes);
element.children.push(...convertChildren(node, element, ctx));
ctx.scriptLet.closeScope();
}
extractElementTags(element, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = Object.assign({ type: "SvelteName", name: elementName, parent: element }, ctx.getConvertLocation(openTokenRange));
return name;
},
});
if (element.name.name === "script" ||
element.name.name === "style" ||
(element.name.name === "template" && ctx.findBlock(element))) {
// Restore the block-like element.
for (const child of element.children) {
if (child.type === "SvelteText") {
child.value = ctx.code.slice(...child.range);
}
}
if (element.name.name === "script") {
ctx.stripScriptCode(element.startTag.range[1], (_b = (_a = element.endTag) === null || _a === void 0 ? void 0 : _a.range[0]) !== null && _b !== void 0 ? _b : element.range[1]);
}
}
if (element.startTag.selfClosing && element.name.name.endsWith("-")) {
// Restore the self-closing block.
const selfClosingBlock = /^[a-z]-+$/iu.test(element.name.name) &&
ctx.findSelfClosingBlock(element);
if (selfClosingBlock) {
element.name.name = selfClosingBlock.originalTag;
}
}
return element;
}
/** Convert for Special element. e.g. <svelte:self> */
function convertSpecialElement(node, parent, ctx) {
const locs = ctx.getConvertLocation(node);
const element = Object.assign({ type: "SvelteElement", kind: "special", name: null, startTag: {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: null,
range: [locs.range[0], null],
loc: {
start: {
line: locs.loc.start.line,
column: locs.loc.start.column,
},
end: null,
},
}, children: [], endTag: null, parent }, locs);
ctx.elements.set(element, node);
element.startTag.parent = element;
const elementName = node.name;
const { letDirectives, attributes } = extractLetDirectives(node);
const letParams = [];
if (letDirectives.length) {
ctx.letDirCollections.beginExtract();
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(letDirectives, element.startTag, ctx));
letParams.push(...ctx.letDirCollections.extract().getLetParams());
}
if (!letParams.length && !needScopeByChildren(node)) {
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(attributes, element.startTag, ctx));
element.children.push(...convertChildren(node, element, ctx));
}
else {
ctx.scriptLet.nestBlock(element, letParams);
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(attributes, element.startTag, ctx));
(0, sort_1.sortNodes)(element.startTag.attributes);
element.children.push(...convertChildren(node, element, ctx));
ctx.scriptLet.closeScope();
}
const thisExpression = (node.type === "InlineComponent" &&
elementName === "svelte:component" &&
node.expression) ||
(node.type === "Element" && elementName === "svelte:element" && node.tag);
if (thisExpression) {
processThisAttribute(node, thisExpression, element, ctx);
}
extractElementTags(element, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = Object.assign({ type: "SvelteName", name: elementName, parent: element }, ctx.getConvertLocation(openTokenRange));
return name;
},
});
return element;
}
/** process `this=` */
function processThisAttribute(node, thisValue, element, ctx) {
let thisNode;
if (typeof thisValue === "string") {
// this="..."
const startIndex = findStartIndexOfThis(node, ctx);
const eqIndex = ctx.code.indexOf("=", startIndex + 4 /* t,h,i,s */);
const valueStartIndex = (0, common_1.indexOf)(ctx.code, (c) => Boolean(c.trim()), eqIndex + 1);
const quote = ctx.code.startsWith(thisValue, valueStartIndex)
? null
: ctx.code[valueStartIndex];
const literalStartIndex = quote
? valueStartIndex + quote.length
: valueStartIndex;
const literalEndIndex = literalStartIndex + thisValue.length;
const endIndex = quote ? literalEndIndex + quote.length : literalEndIndex;
const thisAttr = Object.assign({ type: "SvelteAttribute", key: null, boolean: false, value: [], parent: element.startTag }, ctx.getConvertLocation({ start: startIndex, end: endIndex }));
thisAttr.key = Object.assign({ type: "SvelteName", name: "this", parent: thisAttr }, ctx.getConvertLocation({ start: startIndex, end: eqIndex }));
thisAttr.value.push(Object.assign({ type: "SvelteLiteral", value: thisValue, parent: thisAttr }, ctx.getConvertLocation({
start: literalStartIndex,
end: literalEndIndex,
})));
// this
ctx.addToken("HTMLIdentifier", {
start: startIndex,
end: startIndex + 4,
});
// =
ctx.addToken("Punctuator", {
start: eqIndex,
end: eqIndex + 1,
});
if (quote) {
// "
ctx.addToken("Punctuator", {
start: valueStartIndex,
end: literalStartIndex,
});
}
ctx.addToken("HTMLText", {
start: literalStartIndex,
end: literalEndIndex,
});
if (quote) {
// "
ctx.addToken("Punctuator", {
start: literalEndIndex,
end: endIndex,
});
}
thisNode = thisAttr;
}
else {
// this={...}
const eqIndex = ctx.code.lastIndexOf("=", (0, common_1.getWithLoc)(thisValue).start);
const startIndex = ctx.code.lastIndexOf("this", eqIndex);
const closeIndex = ctx.code.indexOf("}", (0, common_1.getWithLoc)(thisValue).end);
const endIndex = (0, common_1.indexOf)(ctx.code, (c) => c === ">" || !c.trim(), closeIndex);
const thisDir = Object.assign({ type: "SvelteSpecialDirective", kind: "this", key: null, expression: null, parent: element.startTag }, ctx.getConvertLocation({ start: startIndex, end: endIndex }));
thisDir.key = Object.assign({ type: "SvelteSpecialDirectiveKey", parent: thisDir }, ctx.getConvertLocation({ start: startIndex, end: eqIndex }));
// this
ctx.addToken("HTMLIdentifier", {
start: startIndex,
end: startIndex + 4,
});
// =
ctx.addToken("Punctuator", {
start: eqIndex,
end: eqIndex + 1,
});
ctx.scriptLet.addExpression(thisValue, thisDir, null, (es) => {
thisDir.expression = es;
});
thisNode = thisDir;
}
const targetIndex = element.startTag.attributes.findIndex((attr) => thisNode.range[1] <= attr.range[0]);
if (targetIndex === -1) {
element.startTag.attributes.push(thisNode);
}
else {
element.startTag.attributes.splice(targetIndex, 0, thisNode);
}
}
/** Find the start index of `this` */
function findStartIndexOfThis(node, ctx) {
var _a, _b, _d, _e;
// Get the end index of `svelte:element`
const startIndex = ctx.code.indexOf(node.name, node.start) + node.name.length;
const sortedAttrs = [...node.attributes].sort((a, b) => a.start - b.start);
// Find the start index of `this` from the end index of `svelte:element`.
// However, it only seeks to the start index of the first attribute (or the end index of element node).
let thisIndex = (0, common_1.indexOf)(ctx.code, (_c, index) => ctx.code.startsWith("this", index), startIndex, (_b = (_a = sortedAttrs[0]) === null || _a === void 0 ? void 0 : _a.start) !== null && _b !== void 0 ? _b : node.end);
while (thisIndex < 0) {
if (sortedAttrs.length === 0)
throw new __1.ParseError("Cannot resolved `this` attribute.", thisIndex, ctx);
// Step3: Find the start index of `this` from the end index of attribute.
// However, it only seeks to the start index of the first attribute (or the end index of element node).
const nextStartIndex = sortedAttrs.shift().end;
thisIndex = (0, common_1.indexOf)(ctx.code, (_c, index) => ctx.code.startsWith("this", index), nextStartIndex, (_e = (_d = sortedAttrs[0]) === null || _d === void 0 ? void 0 : _d.start) !== null && _e !== void 0 ? _e : node.end);
}
return thisIndex;
}
/** Convert for ComponentElement */
function convertComponentElement(node, parent, ctx) {
const locs = ctx.getConvertLocation(node);
const element = Object.assign({ type: "SvelteElement", kind: "component", name: null, startTag: {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: null,
range: [locs.range[0], null],
loc: {
start: {
line: locs.loc.start.line,
column: locs.loc.start.column,
},
end: null,
},
}, children: [], endTag: null, parent }, locs);
ctx.elements.set(element, node);
element.startTag.parent = element;
const elementName = node.name;
const { letDirectives, attributes } = extractLetDirectives(node);
const letParams = [];
if (letDirectives.length) {
ctx.letDirCollections.beginExtract();
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(letDirectives, element.startTag, ctx));
letParams.push(...ctx.letDirCollections.extract().getLetParams());
}
if (!letParams.length && !needScopeByChildren(node)) {
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(attributes, element.startTag, ctx));
element.children.push(...convertChildren(node, element, ctx));
}
else {
ctx.scriptLet.nestBlock(element, letParams);
element.startTag.attributes.push(...(0, attr_1.convertAttributes)(attributes, element.startTag, ctx));
(0, sort_1.sortNodes)(element.startTag.attributes);
element.children.push(...convertChildren(node, element, ctx));
ctx.scriptLet.closeScope();
}
extractElementTags(element, ctx, {
buildNameNode: (openTokenRange) => {
const chains = elementName.split(".");
const id = chains.shift();
const idRange = {
start: openTokenRange.start,
end: openTokenRange.start + id.length,
};
// ctx.addToken("Identifier", idRange)
const identifier = Object.assign({ type: "Identifier", name: id,
// @ts-expect-error -- ignore
parent: element }, ctx.getConvertLocation(idRange));
let object = identifier;
// eslint-disable-next-line func-style -- var
let esCallback = (es) => {
element.name = es;
};
let start = idRange.end + 1;
for (const name of chains) {
const range = { start, end: start + name.length };
ctx.addToken("HTMLIdentifier", range);
const mem = Object.assign({ type: "SvelteMemberExpressionName", object, property: Object.assign({ type: "SvelteName", name, parent: null }, ctx.getConvertLocation(range)), parent: element }, ctx.getConvertLocation({
start: openTokenRange.start,
end: range.end,
}));
mem.property.parent = mem;
object.parent = mem;
object = mem;
start = range.end + 1;
if (mem.object === identifier) {
esCallback = (es) => {
mem.object = es;
};
}
}
ctx.scriptLet.addExpression(identifier, identifier.parent, null, esCallback);
return object;
},
});
return element;
}
/** Convert for Slot */
function convertSlotElement(node, parent, ctx) {
// Slot translates to SvelteHTMLElement.
const element = convertHTMLElement(node, parent, ctx);
ctx.slots.add(element);
return element;
}
/** Convert for window element. e.g. <svelte:window> */
function convertWindowElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for document element. e.g. <svelte:document> */
function convertDocumentElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for body element. e.g. <svelte:body> */
function convertBodyElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for head element. e.g. <svelte:head> */
function convertHeadElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for title element. e.g. <title> */
function convertTitleElement(node, parent, ctx) {
return convertHTMLElement(node, parent, ctx);
}
/** Convert for options element. e.g. <svelte:options> */
function convertOptionsElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Convert for <svelte:fragment> element. */
function convertSlotTemplateElement(node, parent, ctx) {
return convertSpecialElement(node, parent, ctx);
}
/** Extract element tag and tokens */
function extractElementTags(element, ctx, options) {
var _a, _b;
const startTagNameEnd = (0, common_1.indexOf)(ctx.code, (c) => c === "/" || c === ">" || !c.trim(), element.range[0] + 1);
const openTokenRange = {
start: element.range[0] + 1,
end: startTagNameEnd,
};
element.name = options.buildNameNode(openTokenRange);
const startTagEnd = ctx.code.indexOf(">", (_b = (_a = element.startTag.attributes[element.startTag.attributes.length - 1]) === null || _a === void 0 ? void 0 : _a.range[1]) !== null && _b !== void 0 ? _b : openTokenRange.end) + 1;
element.startTag.range[1] = startTagEnd;
element.startTag.loc.end = ctx.getLocFromIndex(startTagEnd);
if (ctx.code[element.range[1] - 1] !== ">") {
// Have not end tag
return;
}
if (ctx.code[element.range[1] - 2] === "/") {
// self close
element.startTag.selfClosing = true;
return;
}
const endTagOpen = ctx.code.lastIndexOf("<", element.range[1] - 1);
if (endTagOpen <= startTagEnd - 1) {
// void element
return;
}
const endTagNameStart = endTagOpen + 2;
const endTagNameEnd = (0, common_1.indexOf)(ctx.code, (c) => c === ">" || !c.trim(), endTagNameStart);
const endTagClose = ctx.code.indexOf(">", endTagNameEnd);
element.endTag = Object.assign({ type: "SvelteEndTag", parent: element }, ctx.getConvertLocation({ start: endTagOpen, end: endTagClose + 1 }));
ctx.addToken("HTMLIdentifier", {
start: endTagNameStart,
end: endTagNameEnd,
});
}
exports.extractElementTags = extractElementTags;

View File

@ -0,0 +1 @@
export { convertSvelteRoot } from "./root";

View File

@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertSvelteRoot = void 0;
var root_1 = require("./root");
Object.defineProperty(exports, "convertSvelteRoot", { enumerable: true, get: function () { return root_1.convertSvelteRoot; } });

View File

@ -0,0 +1,9 @@
import type { SvelteDebugTag, SvelteMustacheTag, SvelteMustacheTagRaw, SvelteMustacheTagText } from "../../ast";
import type { Context } from "../../context";
import type * as SvAST from "../svelte-ast-types";
/** Convert for MustacheTag */
export declare function convertMustacheTag(node: SvAST.MustacheTag, parent: SvelteMustacheTag["parent"], ctx: Context): SvelteMustacheTagText;
/** Convert for MustacheTag */
export declare function convertRawMustacheTag(node: SvAST.RawMustacheTag, parent: SvelteMustacheTag["parent"], ctx: Context): SvelteMustacheTagRaw;
/** Convert for DebugTag */
export declare function convertDebugTag(node: SvAST.DebugTag, parent: SvelteDebugTag["parent"], ctx: Context): SvelteDebugTag;

View File

@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertDebugTag = exports.convertRawMustacheTag = exports.convertMustacheTag = void 0;
/** Convert for MustacheTag */
function convertMustacheTag(node, parent, ctx) {
return convertMustacheTag0(node, "text", parent, ctx);
}
exports.convertMustacheTag = convertMustacheTag;
/** Convert for MustacheTag */
function convertRawMustacheTag(node, parent, ctx) {
const mustache = convertMustacheTag0(node, "raw", parent, ctx);
const atHtmlStart = ctx.code.indexOf("@html", mustache.range[0]);
ctx.addToken("MustacheKeyword", {
start: atHtmlStart,
end: atHtmlStart + 5,
});
return mustache;
}
exports.convertRawMustacheTag = convertRawMustacheTag;
/** Convert for DebugTag */
function convertDebugTag(node, parent, ctx) {
const mustache = Object.assign({ type: "SvelteDebugTag", identifiers: [], parent }, ctx.getConvertLocation(node));
for (const id of node.identifiers) {
ctx.scriptLet.addExpression(id, mustache, null, (es) => {
mustache.identifiers.push(es);
});
}
const atDebugStart = ctx.code.indexOf("@debug", mustache.range[0]);
ctx.addToken("MustacheKeyword", {
start: atDebugStart,
end: atDebugStart + 6,
});
return mustache;
}
exports.convertDebugTag = convertDebugTag;
/** Convert to MustacheTag */
function convertMustacheTag0(node, kind, parent, ctx) {
const mustache = Object.assign({ type: "SvelteMustacheTag", kind, expression: null, parent }, ctx.getConvertLocation(node));
ctx.scriptLet.addExpression(node.expression, mustache, null, (es) => {
mustache.expression = es;
});
return mustache;
}

View File

@ -0,0 +1,7 @@
import type * as SvAST from "../svelte-ast-types";
import type { SvelteProgram } from "../../ast";
import type { Context } from "../../context";
/**
* Convert root
*/
export declare function convertSvelteRoot(svelteAst: SvAST.Ast, ctx: Context): SvelteProgram;

View File

@ -0,0 +1,103 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertSvelteRoot = void 0;
const element_1 = require("./element");
const attr_1 = require("./attr");
/**
* Convert root
*/
function convertSvelteRoot(svelteAst, ctx) {
const ast = Object.assign({ type: "Program", body: [], comments: ctx.comments, sourceType: "module", tokens: ctx.tokens, parent: null }, ctx.getConvertLocation({ start: 0, end: ctx.code.length }));
const body = ast.body;
if (svelteAst.html) {
const fragment = svelteAst.html;
body.push(...(0, element_1.convertChildren)(fragment, ast, ctx));
}
if (svelteAst.instance) {
const instance = svelteAst.instance;
const script = Object.assign({ type: "SvelteScriptElement", name: null, startTag: null, body: [], endTag: null, parent: ast }, ctx.getConvertLocation(instance));
extractAttributes(script, ctx);
(0, element_1.extractElementTags)(script, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = Object.assign({ type: "SvelteName", name: "script", parent: script }, ctx.getConvertLocation(openTokenRange));
return name;
},
});
body.push(script);
}
if (svelteAst.module) {
const module = svelteAst.module;
const script = Object.assign({ type: "SvelteScriptElement", name: null, startTag: null, body: [], endTag: null, parent: ast }, ctx.getConvertLocation(module));
extractAttributes(script, ctx);
(0, element_1.extractElementTags)(script, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = Object.assign({ type: "SvelteName", name: "script", parent: script }, ctx.getConvertLocation(openTokenRange));
return name;
},
});
body.push(script);
}
if (svelteAst.css) {
const style = Object.assign({ type: "SvelteStyleElement", name: null, startTag: null, children: [], endTag: null, parent: ast }, ctx.getConvertLocation(svelteAst.css));
extractAttributes(style, ctx);
(0, element_1.extractElementTags)(style, ctx, {
buildNameNode: (openTokenRange) => {
ctx.addToken("HTMLIdentifier", openTokenRange);
const name = Object.assign({ type: "SvelteName", name: "style", parent: style }, ctx.getConvertLocation(openTokenRange));
return name;
},
});
if (style.endTag && style.startTag.range[1] < style.endTag.range[0]) {
const contentRange = {
start: style.startTag.range[1],
end: style.endTag.range[0],
};
ctx.addToken("HTMLText", contentRange);
style.children = [
Object.assign({ type: "SvelteText", value: ctx.code.slice(contentRange.start, contentRange.end), parent: style }, ctx.getConvertLocation(contentRange)),
];
}
body.push(style);
}
// Set the scope of the Program node.
ctx.scriptLet.addProgramRestore((node, _tokens, _comments, { scopeManager, registerNodeToScope, addPostProcess }) => {
const scopes = [];
for (const scope of scopeManager.scopes) {
if (scope.block === node) {
registerNodeToScope(ast, scope);
scopes.push(scope);
}
}
addPostProcess(() => {
// Reverts the node indicated by `block` to the original Program node.
// This state is incorrect, but `eslint-utils`'s `referenceTracker.iterateEsmReferences()` tracks import statements
// from Program nodes set to `block` in global scope. This can only be handled by the original Program node.
scopeManager.globalScope.block = node;
});
});
return ast;
}
exports.convertSvelteRoot = convertSvelteRoot;
/** Extract attrs */
function extractAttributes(element, ctx) {
element.startTag = {
type: "SvelteStartTag",
attributes: [],
selfClosing: false,
parent: element,
range: [element.range[0], null],
loc: {
start: {
line: element.loc.start.line,
column: element.loc.start.column,
},
end: null,
},
};
const block = ctx.findBlock(element);
if (block) {
element.startTag.attributes.push(...(0, attr_1.convertAttributeTokens)(block.attrs, element.startTag, ctx));
}
}

View File

@ -0,0 +1,10 @@
import type { SvelteLiteral, SvelteText } from "../../ast";
import type { Context } from "../../context";
import type { AttributeValueToken } from "../html";
import type * as SvAST from "../svelte-ast-types";
/** Convert for Text */
export declare function convertText(node: SvAST.Text, parent: SvelteText["parent"], ctx: Context): SvelteText;
/** Convert for Text to Literal */
export declare function convertTextToLiteral(node: SvAST.Text, parent: SvelteLiteral["parent"], ctx: Context): SvelteLiteral;
/** Convert for AttributeValueToken to Literal */
export declare function convertAttributeValueTokenToLiteral(node: AttributeValueToken, parent: SvelteLiteral["parent"], ctx: Context): SvelteLiteral;

View File

@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertAttributeValueTokenToLiteral = exports.convertTextToLiteral = exports.convertText = void 0;
/** Convert for Text */
function convertText(node, parent, ctx) {
const text = Object.assign({ type: "SvelteText", value: node.data, parent }, ctx.getConvertLocation(node));
extractTextTokens(node, ctx);
return text;
}
exports.convertText = convertText;
/** Convert for Text to Literal */
function convertTextToLiteral(node, parent, ctx) {
const text = Object.assign({ type: "SvelteLiteral", value: node.data, parent }, ctx.getConvertLocation(node));
extractTextTokens(node, ctx);
return text;
}
exports.convertTextToLiteral = convertTextToLiteral;
/** Convert for AttributeValueToken to Literal */
function convertAttributeValueTokenToLiteral(node, parent, ctx) {
const valueLoc = node.quote
? { start: node.start + 1, end: node.end - 1 }
: node;
const text = Object.assign({ type: "SvelteLiteral", value: node.value, parent }, ctx.getConvertLocation(valueLoc));
extractTextTokens(valueLoc, ctx);
return text;
}
exports.convertAttributeValueTokenToLiteral = convertAttributeValueTokenToLiteral;
/** Extract tokens */
function extractTextTokens(node, ctx) {
const loc = node;
let start = loc.start;
let word = false;
for (let index = loc.start; index < loc.end; index++) {
if (word !== Boolean(ctx.code[index].trim())) {
if (start < index) {
ctx.addToken("HTMLText", { start, end: index });
}
word = !word;
start = index;
}
}
if (start < loc.end) {
ctx.addToken("HTMLText", { start, end: loc.end });
}
}

View File

@ -0,0 +1,6 @@
import type { BasicParserObject } from "./parser-object";
/**
* Load `espree` from the loaded ESLint.
* If the loaded ESLint was not found, just returns `require("espree")`.
*/
export declare function getEspree(): BasicParserObject;

56
node_modules/svelte-eslint-parser/lib/parser/espree.js generated vendored Normal file
View File

@ -0,0 +1,56 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEspree = void 0;
const module_1 = __importDefault(require("module"));
const path_1 = __importDefault(require("path"));
const createRequire =
// Added in v12.2.0
module_1.default.createRequire ||
// Added in v10.12.0, but deprecated in v12.2.0.
// @ts-expect-error -- old type
module_1.default.createRequireFromPath ||
// Polyfill - This is not executed on the tests on node@>=10.
/* istanbul ignore next */
((modName) => {
const mod = new module_1.default(modName);
mod.filename = modName;
mod.paths = module_1.default._nodeModulePaths(path_1.default.dirname(modName));
mod._compile("module.exports = require;", modName);
return mod.exports;
});
let espreeCache = null;
/** Checks if given path is linter path */
function isLinterPath(p) {
return (
// ESLint 6 and above
p.includes(`eslint${path_1.default.sep}lib${path_1.default.sep}linter${path_1.default.sep}linter.js`) ||
// ESLint 5
p.includes(`eslint${path_1.default.sep}lib${path_1.default.sep}linter.js`));
}
/**
* Load `espree` from the loaded ESLint.
* If the loaded ESLint was not found, just returns `require("espree")`.
*/
function getEspree() {
if (!espreeCache) {
// Lookup the loaded eslint
const linterPath = Object.keys(require.cache || {}).find(isLinterPath);
if (linterPath) {
try {
espreeCache = createRequire(linterPath)("espree");
}
catch (_a) {
// ignore
}
}
if (!espreeCache) {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- ignore
espreeCache = require("espree");
}
}
return espreeCache;
}
exports.getEspree = getEspree;

20
node_modules/svelte-eslint-parser/lib/parser/html.d.ts generated vendored Normal file
View File

@ -0,0 +1,20 @@
export type AttributeToken = {
key: AttributeKeyToken;
value: AttributeValueToken | null;
};
export type AttributeKeyToken = {
name: string;
start: number;
end: number;
};
export type AttributeValueToken = {
value: string;
quote: '"' | "'" | null;
start: number;
end: number;
};
/** Parse HTML attributes */
export declare function parseAttributes(code: string, startIndex: number): {
attributes: AttributeToken[];
index: number;
};

168
node_modules/svelte-eslint-parser/lib/parser/html.js generated vendored Normal file
View File

@ -0,0 +1,168 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseAttributes = void 0;
const spacePattern = /\s/;
/** Parse HTML attributes */
function parseAttributes(code, startIndex) {
const attributes = [];
let index = startIndex;
while (index < code.length) {
const char = code[index];
if (spacePattern.test(char)) {
index++;
continue;
}
if (char === ">" || (char === "/" && code[index + 1] === ">"))
break;
const attrData = parseAttribute(code, index);
attributes.push(attrData.attribute);
index = attrData.index;
}
return { attributes, index };
}
exports.parseAttributes = parseAttributes;
/** Parse HTML attribute */
function parseAttribute(code, startIndex) {
// parse key
const keyData = parseAttributeKey(code, startIndex);
const key = keyData.key;
let index = keyData.index;
if (code[index] !== "=") {
return {
attribute: {
key,
value: null,
},
index,
};
}
index++;
// skip spaces
while (index < code.length) {
const char = code[index];
if (spacePattern.test(char)) {
index++;
continue;
}
break;
}
// parse value
const valueData = parseAttributeValue(code, index);
return {
attribute: {
key,
value: valueData.value,
},
index: valueData.index,
};
}
/** Parse HTML attribute key */
function parseAttributeKey(code, startIndex) {
const key = {
name: code[startIndex],
start: startIndex,
end: startIndex + 1,
};
let index = key.end;
while (index < code.length) {
const char = code[index];
if (char === "=" ||
char === ">" ||
(char === "/" && code[index + 1] === ">")) {
break;
}
if (spacePattern.test(char)) {
for (let i = index; i < code.length; i++) {
const c = code[i];
if (c === "=") {
return {
key,
index: i,
};
}
if (spacePattern.test(c)) {
continue;
}
return {
key,
index,
};
}
break;
}
key.name += char;
index++;
key.end = index;
}
return {
key,
index,
};
}
/** Parse HTML attribute value */
function parseAttributeValue(code, startIndex) {
let index = startIndex;
const maybeQuote = code[index];
if (maybeQuote == null) {
return {
value: null,
index,
};
}
const quote = maybeQuote === '"' || maybeQuote === "'" ? maybeQuote : null;
if (quote) {
index++;
}
const valueFirstChar = code[index];
if (valueFirstChar == null) {
return {
value: {
value: maybeQuote,
quote: null,
start: startIndex,
end: index,
},
index,
};
}
if (valueFirstChar === quote) {
return {
value: {
value: "",
quote,
start: startIndex,
end: index + 1,
},
index: index + 1,
};
}
const value = {
value: valueFirstChar,
quote,
start: startIndex,
end: index + 1,
};
index = value.end;
while (index < code.length) {
const char = code[index];
if (quote) {
if (quote === char) {
index++;
value.end = index;
break;
}
}
else if (spacePattern.test(char) ||
char === ">" ||
(char === "/" && code[index + 1] === ">")) {
break;
}
value.value += char;
index++;
value.end = index;
}
return {
value,
index,
};
}

View File

@ -0,0 +1,37 @@
import type { Comment, SvelteProgram, Token } from "../ast";
import type { Program } from "estree";
import type { ScopeManager } from "eslint-scope";
import type * as SvAST from "./svelte-ast-types";
import { type StyleContext, type StyleContextNoStyleElement, type StyleContextParseError, type StyleContextSuccess, type StyleContextUnknownLang } from "./style-context";
export { StyleContext, StyleContextNoStyleElement, StyleContextParseError, StyleContextSuccess, StyleContextUnknownLang, };
export interface ESLintProgram extends Program {
comments: Comment[];
tokens: Token[];
}
/**
* The parsing result of ESLint custom parsers.
*/
export interface ESLintExtendedProgram {
ast: ESLintProgram;
services?: Record<string, any>;
visitorKeys?: {
[type: string]: string[];
};
scopeManager?: ScopeManager;
_virtualScriptCode?: string;
}
/**
* Parse source code
*/
export declare function parseForESLint(code: string, options?: any): {
ast: SvelteProgram;
services: Record<string, any> & {
isSvelte: true;
getSvelteHtmlAst: () => SvAST.Fragment;
getStyleContext: () => StyleContext;
};
visitorKeys: {
[type: string]: string[];
};
scopeManager: ScopeManager;
};

139
node_modules/svelte-eslint-parser/lib/parser/index.js generated vendored Normal file
View File

@ -0,0 +1,139 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseForESLint = void 0;
const visitor_keys_1 = require("../visitor-keys");
const context_1 = require("../context");
const eslint_scope_1 = require("eslint-scope");
const script_1 = require("./script");
const sort_1 = require("./sort");
const template_1 = require("./template");
const analyze_scope_1 = require("./analyze-scope");
const errors_1 = require("../errors");
const typescript_1 = require("./typescript");
const scope_1 = require("../scope");
const style_context_1 = require("./style-context");
/**
* Parse source code
*/
function parseForESLint(code, options) {
const parserOptions = Object.assign({ ecmaVersion: 2020, sourceType: "module", loc: true, range: true, raw: true, tokens: true, comment: true, eslintVisitorKeys: true, eslintScopeManager: true }, (options || {}));
parserOptions.sourceType = "module";
if (parserOptions.ecmaVersion <= 5 || parserOptions.ecmaVersion == null) {
parserOptions.ecmaVersion = 2015;
}
const ctx = new context_1.Context(code, parserOptions);
const resultTemplate = (0, template_1.parseTemplate)(ctx.sourceCode.template, ctx, parserOptions);
const scripts = ctx.sourceCode.scripts;
const resultScript = ctx.isTypeScript()
? (0, typescript_1.parseTypeScript)(scripts.getCurrentVirtualCodeInfo(), scripts.attrs, parserOptions, { slots: ctx.slots })
: (0, script_1.parseScript)(scripts.getCurrentVirtualCode(), scripts.attrs, parserOptions);
ctx.scriptLet.restore(resultScript);
ctx.tokens.push(...resultScript.ast.tokens);
ctx.comments.push(...resultScript.ast.comments);
(0, sort_1.sortNodes)(ctx.comments);
(0, sort_1.sortNodes)(ctx.tokens);
extractTokens(ctx);
(0, analyze_scope_1.analyzeStoreScope)(resultScript.scopeManager);
(0, analyze_scope_1.analyzeReactiveScope)(resultScript.scopeManager);
(0, analyze_scope_1.analyzeStoreScope)(resultScript.scopeManager); // for reactive vars
// Add $$xxx variable
for (const $$name of ["$$slots", "$$props", "$$restProps"]) {
const globalScope = resultScript.scopeManager.globalScope;
const variable = new eslint_scope_1.Variable();
variable.name = $$name;
variable.scope = globalScope;
globalScope.variables.push(variable);
globalScope.set.set($$name, variable);
globalScope.through = globalScope.through.filter((reference) => {
if (reference.identifier.name === $$name) {
// Links the variable and the reference.
// And this reference is removed from `Scope#through`.
reference.resolved = variable;
(0, scope_1.addReference)(variable.references, reference);
return false;
}
return true;
});
}
const ast = resultTemplate.ast;
const statements = [...resultScript.ast.body];
ast.sourceType = resultScript.ast.sourceType;
const scriptElements = ast.body.filter((b) => b.type === "SvelteScriptElement");
for (let index = 0; index < scriptElements.length; index++) {
const body = scriptElements[index];
let statement = statements[0];
while (statement &&
body.range[0] <= statement.range[0] &&
(statement.range[1] <= body.range[1] ||
index === scriptElements.length - 1)) {
statement.parent = body;
body.body.push(statement);
statements.shift();
statement = statements[0];
}
if (!body.startTag.attributes.some((attr) => attr.type === "SvelteAttribute" &&
attr.key.name === "context" &&
attr.value.length === 1 &&
attr.value[0].type === "SvelteLiteral" &&
attr.value[0].value === "module")) {
(0, analyze_scope_1.analyzePropsScope)(body, resultScript.scopeManager);
}
}
if (statements.length) {
throw new errors_1.ParseError("The script is unterminated", statements[0].range[1], ctx);
}
const styleElement = ast.body.find((b) => b.type === "SvelteStyleElement");
let styleContext = null;
resultScript.ast = ast;
resultScript.services = Object.assign(resultScript.services || {}, {
isSvelte: true,
getSvelteHtmlAst() {
return resultTemplate.svelteAst.html;
},
getStyleContext() {
if (styleContext === null) {
styleContext = (0, style_context_1.parseStyleContext)(styleElement, ctx);
}
return styleContext;
},
styleNodeLoc: style_context_1.styleNodeLoc,
styleNodeRange: style_context_1.styleNodeRange,
});
resultScript.visitorKeys = Object.assign({}, visitor_keys_1.KEYS, resultScript.visitorKeys);
return resultScript;
}
exports.parseForESLint = parseForESLint;
/** Extract tokens */
function extractTokens(ctx) {
const useRanges = (0, sort_1.sortNodes)([...ctx.tokens, ...ctx.comments]).map((t) => t.range);
let range = useRanges.shift();
for (let index = 0; index < ctx.sourceCode.template.length; index++) {
while (range && range[1] <= index) {
range = useRanges.shift();
}
if (range && range[0] <= index) {
index = range[1] - 1;
continue;
}
const c = ctx.sourceCode.template[index];
if (!c.trim()) {
continue;
}
if (isPunctuator(c)) {
ctx.addToken("Punctuator", { start: index, end: index + 1 });
}
else {
// unknown
// It is may be a bug.
ctx.addToken("Identifier", { start: index, end: index + 1 });
}
}
(0, sort_1.sortNodes)(ctx.comments);
(0, sort_1.sortNodes)(ctx.tokens);
/**
* Checks if the given char is punctuator
*/
function isPunctuator(c) {
return /^[^\w$]$/iu.test(c);
}
}

View File

@ -0,0 +1,34 @@
import type { ESLintExtendedProgram, ESLintProgram } from ".";
import type * as tsESLintParser from "@typescript-eslint/parser";
type TSESLintParser = typeof tsESLintParser;
/**
* The type of basic ESLint custom parser.
* e.g. espree
*/
export type BasicParserObject = {
parse(code: string, options: any): ESLintProgram;
parseForESLint: undefined;
};
/**
* The type of ESLint custom parser enhanced for ESLint.
* e.g. @babel/eslint-parser, @typescript-eslint/parser
*/
export type EnhancedParserObject = {
parseForESLint(code: string, options: any): ESLintExtendedProgram;
parse: undefined;
};
/**
* The type of ESLint (custom) parsers.
*/
export type ParserObject = EnhancedParserObject | BasicParserObject;
/** Checks whether given object is ParserObject */
export declare function isParserObject(value: unknown): value is ParserObject;
/** Checks whether given object is EnhancedParserObject */
export declare function isEnhancedParserObject(value: unknown): value is EnhancedParserObject;
/** Checks whether given object is BasicParserObject */
export declare function isBasicParserObject(value: unknown): value is BasicParserObject;
/** Checks whether given object maybe "@typescript-eslint/parser" */
export declare function maybeTSESLintParserObject(value: unknown): value is TSESLintParser;
/** Checks whether given object is "@typescript-eslint/parser" */
export declare function isTSESLintParserObject(value: unknown): value is TSESLintParser;
export {};

View File

@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTSESLintParserObject = exports.maybeTSESLintParserObject = exports.isBasicParserObject = exports.isEnhancedParserObject = exports.isParserObject = void 0;
/** Checks whether given object is ParserObject */
function isParserObject(value) {
return isEnhancedParserObject(value) || isBasicParserObject(value);
}
exports.isParserObject = isParserObject;
/** Checks whether given object is EnhancedParserObject */
function isEnhancedParserObject(value) {
return Boolean(value && typeof value.parseForESLint === "function");
}
exports.isEnhancedParserObject = isEnhancedParserObject;
/** Checks whether given object is BasicParserObject */
function isBasicParserObject(value) {
return Boolean(value && typeof value.parse === "function");
}
exports.isBasicParserObject = isBasicParserObject;
/** Checks whether given object maybe "@typescript-eslint/parser" */
function maybeTSESLintParserObject(value) {
return (isEnhancedParserObject(value) &&
isBasicParserObject(value) &&
typeof value.createProgram === "function" &&
typeof value.clearCaches === "function" &&
typeof value.version === "string");
}
exports.maybeTSESLintParserObject = maybeTSESLintParserObject;
/** Checks whether given object is "@typescript-eslint/parser" */
function isTSESLintParserObject(value) {
if (!isEnhancedParserObject(value))
return false;
try {
const result = value.parseForESLint("", {});
const services = result.services;
return Boolean(services &&
services.esTreeNodeToTSNodeMap &&
services.tsNodeToESTreeNodeMap);
}
catch (_a) {
return false;
}
}
exports.isTSESLintParserObject = isTSESLintParserObject;

View File

@ -0,0 +1,7 @@
import type { ParserObject } from "./parser-object";
type UserOptionParser = string | ParserObject | Record<string, string | ParserObject | undefined> | undefined;
/** Get parser for script lang */
export declare function getParserForLang(attrs: Record<string, string | undefined>, parser: UserOptionParser): string | ParserObject;
/** Get parser */
export declare function getParser(attrs: Record<string, string | undefined>, parser: UserOptionParser): ParserObject;
export {};

View File

@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getParser = exports.getParserForLang = void 0;
const espree_1 = require("./espree");
const parser_object_1 = require("./parser-object");
/** Get parser for script lang */
function getParserForLang(attrs, parser) {
if (parser) {
if (typeof parser === "string" || (0, parser_object_1.isParserObject)(parser)) {
return parser;
}
if (typeof parser === "object") {
const value = parser[attrs.lang || "js"];
if (typeof value === "string" || (0, parser_object_1.isParserObject)(value)) {
return value;
}
}
}
return "espree";
}
exports.getParserForLang = getParserForLang;
/** Get parser */
function getParser(attrs, parser) {
const parserValue = getParserForLang(attrs, parser);
if ((0, parser_object_1.isParserObject)(parserValue)) {
return parserValue;
}
if (parserValue !== "espree") {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- ignore
return require(parserValue);
}
return (0, espree_1.getEspree)();
}
exports.getParser = getParser;

View File

@ -0,0 +1,9 @@
import type { ESLintExtendedProgram } from ".";
/**
* Parse for script
*/
export declare function parseScript(code: string, attrs: Record<string, string | undefined>, parserOptions?: any): ESLintExtendedProgram;
/**
* Parse for script without analyze scope
*/
export declare function parseScriptWithoutAnalyzeScope(code: string, attrs: Record<string, string | undefined>, options: any): ESLintExtendedProgram;

56
node_modules/svelte-eslint-parser/lib/parser/script.js generated vendored Normal file
View File

@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseScriptWithoutAnalyzeScope = exports.parseScript = void 0;
const analyze_scope_1 = require("./analyze-scope");
const traverse_1 = require("../traverse");
const resolve_parser_1 = require("./resolve-parser");
const parser_object_1 = require("./parser-object");
/**
* Parse for script
*/
function parseScript(code, attrs, parserOptions = {}) {
const result = parseScriptWithoutAnalyzeScopeFromVCode(code, attrs, parserOptions);
if (!result.scopeManager) {
const scopeManager = (0, analyze_scope_1.analyzeScope)(result.ast, parserOptions);
result.scopeManager = scopeManager;
}
(0, traverse_1.traverseNodes)(result.ast, {
visitorKeys: result.visitorKeys,
enterNode(node, parent) {
node.parent = parent;
if (node.type === "LabeledStatement" && node.label.name === "$") {
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "Program") {
// Transform node type
node.type = "SvelteReactiveStatement";
}
}
},
leaveNode() {
//
},
});
return result;
}
exports.parseScript = parseScript;
/**
* Parse for script without analyze scope
*/
function parseScriptWithoutAnalyzeScope(code, attrs, options) {
const parser = (0, resolve_parser_1.getParser)(attrs, options.parser);
const result = (0, parser_object_1.isEnhancedParserObject)(parser)
? parser.parseForESLint(code, options)
: parser.parse(code, options);
if ("ast" in result && result.ast != null) {
return result;
}
return { ast: result };
}
exports.parseScriptWithoutAnalyzeScope = parseScriptWithoutAnalyzeScope;
/**
* Parse for script without analyze scope
*/
function parseScriptWithoutAnalyzeScopeFromVCode(code, attrs, options) {
const result = parseScriptWithoutAnalyzeScope(code, attrs, options);
result._virtualScriptCode = code;
return result;
}

View File

@ -0,0 +1,6 @@
/**
* Sort tokens
*/
export declare function sortNodes<T extends {
range: [number, number];
}>(tokens: T[] | null | undefined): T[];

18
node_modules/svelte-eslint-parser/lib/parser/sort.js generated vendored Normal file
View File

@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sortNodes = void 0;
/**
* Sort tokens
*/
function sortNodes(tokens) {
if (!tokens) {
return [];
}
return tokens.sort((a, b) => {
if (a.range[0] !== b.range[0]) {
return a.range[0] - b.range[0];
}
return a.range[1] - b.range[1];
});
}
exports.sortNodes = sortNodes;

View File

@ -0,0 +1,33 @@
import type { Node, Root } from "postcss";
import type { Context } from "../context";
import type { SourceLocation, SvelteStyleElement } from "../ast";
export type StyleContext = StyleContextNoStyleElement | StyleContextParseError | StyleContextSuccess | StyleContextUnknownLang;
export interface StyleContextNoStyleElement {
status: "no-style-element";
}
export interface StyleContextParseError {
status: "parse-error";
sourceLang: string;
error: any;
}
export interface StyleContextSuccess {
status: "success";
sourceLang: string;
sourceAst: Root;
}
export interface StyleContextUnknownLang {
status: "unknown-lang";
sourceLang: string;
}
/**
* Extracts style source from a SvelteStyleElement and parses it into a PostCSS AST.
*/
export declare function parseStyleContext(styleElement: SvelteStyleElement | undefined, ctx: Context): StyleContext;
/**
* Extracts a node location (like that of any ESLint node) from a parsed svelte style node.
*/
export declare function styleNodeLoc(node: Node): Partial<SourceLocation>;
/**
* Extracts a node range (like that of any ESLint node) from a parsed svelte style node.
*/
export declare function styleNodeRange(node: Node): [number | undefined, number | undefined];

View File

@ -0,0 +1,109 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.styleNodeRange = exports.styleNodeLoc = exports.parseStyleContext = void 0;
const postcss_1 = __importDefault(require("postcss"));
const postcss_scss_1 = require("postcss-scss");
/**
* Extracts style source from a SvelteStyleElement and parses it into a PostCSS AST.
*/
function parseStyleContext(styleElement, ctx) {
if (!styleElement || !styleElement.endTag) {
return { status: "no-style-element" };
}
let sourceLang = "css";
for (const attribute of styleElement.startTag.attributes) {
if (attribute.type === "SvelteAttribute" &&
attribute.key.name === "lang" &&
attribute.value.length > 0 &&
attribute.value[0].type === "SvelteLiteral") {
sourceLang = attribute.value[0].value;
}
}
let parseFn, sourceAst;
switch (sourceLang) {
case "css":
parseFn = postcss_1.default.parse;
break;
case "scss":
parseFn = postcss_scss_1.parse;
break;
default:
return { status: "unknown-lang", sourceLang };
}
const styleCode = ctx.code.slice(styleElement.startTag.range[1], styleElement.endTag.range[0]);
try {
sourceAst = parseFn(styleCode, {
from: ctx.parserOptions.filePath,
});
}
catch (error) {
return { status: "parse-error", sourceLang, error };
}
fixPostCSSNodeLocation(sourceAst, styleElement);
sourceAst.walk((node) => fixPostCSSNodeLocation(node, styleElement));
return { status: "success", sourceLang, sourceAst };
}
exports.parseStyleContext = parseStyleContext;
/**
* Extracts a node location (like that of any ESLint node) from a parsed svelte style node.
*/
function styleNodeLoc(node) {
if (node.source === undefined) {
return {};
}
return {
start: node.source.start !== undefined
? {
line: node.source.start.line,
column: node.source.start.column - 1,
}
: undefined,
end: node.source.end !== undefined
? {
line: node.source.end.line,
column: node.source.end.column,
}
: undefined,
};
}
exports.styleNodeLoc = styleNodeLoc;
/**
* Extracts a node range (like that of any ESLint node) from a parsed svelte style node.
*/
function styleNodeRange(node) {
if (node.source === undefined) {
return [undefined, undefined];
}
return [
node.source.start !== undefined ? node.source.start.offset : undefined,
node.source.end !== undefined ? node.source.end.offset + 1 : undefined,
];
}
exports.styleNodeRange = styleNodeRange;
/**
* Fixes PostCSS AST locations to be relative to the whole file instead of relative to the <style> element.
*/
function fixPostCSSNodeLocation(node, styleElement) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
if (((_b = (_a = node.source) === null || _a === void 0 ? void 0 : _a.start) === null || _b === void 0 ? void 0 : _b.offset) !== undefined) {
node.source.start.offset += styleElement.startTag.range[1];
}
if (((_d = (_c = node.source) === null || _c === void 0 ? void 0 : _c.start) === null || _d === void 0 ? void 0 : _d.line) !== undefined) {
node.source.start.line += styleElement.loc.start.line - 1;
}
if (((_f = (_e = node.source) === null || _e === void 0 ? void 0 : _e.end) === null || _f === void 0 ? void 0 : _f.offset) !== undefined) {
node.source.end.offset += styleElement.startTag.range[1];
}
if (((_h = (_g = node.source) === null || _g === void 0 ? void 0 : _g.end) === null || _h === void 0 ? void 0 : _h.line) !== undefined) {
node.source.end.line += styleElement.loc.start.line - 1;
}
if (((_k = (_j = node.source) === null || _j === void 0 ? void 0 : _j.start) === null || _k === void 0 ? void 0 : _k.line) === styleElement.loc.start.line) {
node.source.start.column += styleElement.startTag.loc.end.column;
}
if (((_m = (_l = node.source) === null || _l === void 0 ? void 0 : _l.end) === null || _m === void 0 ? void 0 : _m.line) === styleElement.loc.start.line) {
node.source.end.column += styleElement.startTag.loc.end.column;
}
}

View File

@ -0,0 +1,213 @@
import type ESTree from "estree";
interface BaseNode {
start: number;
end: number;
}
export interface Ast {
html: Fragment;
css: Style;
instance: Script;
module: Script;
}
export declare type TemplateNode = Text | MustacheTag | RawMustacheTag | DebugTag | ConstTag | Directive | StyleDirective | Element | InlineComponent | Window | Document | Body | Head | Title | Options | SlotTemplate | Slot | Comment | IfBlock | EachBlock | AwaitBlock | KeyBlock;
export interface Fragment extends BaseNode {
type: "Fragment";
children: TemplateNode[];
}
export interface Text extends BaseNode {
type: "Text";
data: string;
}
export interface MustacheTag extends BaseNode {
type: "MustacheTag";
expression: ESTree.Expression;
}
export interface RawMustacheTag extends BaseNode {
type: "RawMustacheTag";
expression: ESTree.Expression;
}
export interface DebugTag extends BaseNode {
type: "DebugTag";
identifiers: ESTree.Identifier[];
}
export interface ConstTag extends BaseNode {
type: "ConstTag";
expression: ESTree.AssignmentExpression;
}
export interface IfBlock extends BaseNode {
type: "IfBlock";
expression: ESTree.Expression;
children: TemplateNode[];
else: ElseBlock | undefined;
elseif: true | undefined;
}
export interface ElseBlock extends BaseNode {
type: "ElseBlock";
children: TemplateNode[] | [IfBlock & {
elseif: true;
}];
}
export interface EachBlock extends BaseNode {
type: "EachBlock";
expression: ESTree.Expression;
context: ESTree.Pattern;
index?: string;
key: ESTree.Expression | undefined;
children: TemplateNode[];
else: ElseBlock | undefined;
}
export interface AwaitBlock extends BaseNode {
type: "AwaitBlock";
expression: ESTree.Expression;
pending: PendingBlock;
value: ESTree.Pattern | null;
then: ThenBlock;
error: ESTree.Pattern | null;
catch: CatchBlock;
}
export interface PendingBlock extends BaseNode {
type: "PendingBlock";
skip: boolean;
children: TemplateNode[];
}
export interface ThenBlock extends BaseNode {
type: "ThenBlock";
skip: boolean;
children: TemplateNode[];
}
export interface CatchBlock extends BaseNode {
type: "CatchBlock";
skip: boolean;
children: TemplateNode[];
}
export interface KeyBlock extends BaseNode {
type: "KeyBlock";
expression: ESTree.Expression;
children: TemplateNode[];
}
export interface BaseElement extends BaseNode {
type: "Element";
name: string;
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface BasicElement extends BaseElement {
tag?: undefined;
}
export interface SvelteElement extends BaseElement {
name: "svelte:element";
tag: ESTree.Expression | string;
}
export type Element = BasicElement | SvelteElement;
export interface BaseInlineComponent extends BaseNode {
type: "InlineComponent";
name: string;
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Window extends BaseNode {
type: "Window";
name: "svelte:window";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Document extends BaseNode {
type: "Document";
name: "svelte:document";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Body extends BaseNode {
type: "Body";
name: "svelte:body";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Head extends BaseNode {
type: "Head";
name: "svelte:head";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Title extends BaseNode {
type: "Title";
name: "title";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Options extends BaseNode {
type: "Options";
name: "svelte:options";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface SlotTemplate extends BaseNode {
type: "SlotTemplate";
name: "svelte:fragment";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface BasicInlineComponent extends BaseInlineComponent {
expression?: undefined;
}
export interface InlineSvelteComponent extends BaseInlineComponent {
name: "svelte:component";
expression: ESTree.Expression;
}
export type InlineComponent = BasicInlineComponent | InlineSvelteComponent;
export interface Slot extends BaseNode {
type: "Slot";
name: "slot";
children: TemplateNode[];
attributes: AttributeOrDirective[];
}
export interface Comment extends BaseNode {
type: "Comment";
data: string;
}
export interface Attribute extends BaseNode {
type: "Attribute";
name: string;
value: (Text | AttributeShorthand | MustacheTag)[] | true;
}
export interface Spread extends BaseNode {
type: "Spread";
expression: ESTree.Expression;
}
export interface AttributeShorthand extends BaseNode {
type: "AttributeShorthand";
expression: ESTree.Identifier;
}
export type AttributeOrDirective = Attribute | Spread | Directive | StyleDirective;
interface BaseDirective extends BaseNode {
name: string;
modifiers: string[];
}
export interface DirectiveForExpression extends BaseDirective {
type: "Action" | "Animation" | "Binding" | "Class" | "EventHandler" | "Ref";
expression: null | ESTree.Expression;
}
export interface LetDirective extends BaseDirective {
type: "Let";
expression: null | ESTree.Pattern;
}
export interface TransitionDirective extends BaseDirective {
type: "Transition";
intro: boolean;
outro: boolean;
expression: null | ESTree.Expression;
}
export interface StyleDirective extends BaseDirective {
type: "StyleDirective";
value: (Text | MustacheTag)[] | true;
}
export type Directive = DirectiveForExpression | TransitionDirective | LetDirective;
export interface Script extends BaseNode {
type: "Script";
context: string;
children: TemplateNode[];
}
export interface Style extends BaseNode {
type: "Style";
}
export {};

View File

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@ -0,0 +1,10 @@
import type * as SvAST from "./svelte-ast-types";
import type { Context } from "../context";
import type { SvelteProgram } from "../ast";
/**
* Parse for template
*/
export declare function parseTemplate(code: string, ctx: Context, parserOptions?: any): {
ast: SvelteProgram;
svelteAst: SvAST.Ast;
};

View File

@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTemplate = void 0;
const compiler_1 = require("svelte/compiler");
const index_1 = require("./converts/index");
const sort_1 = require("./sort");
const __1 = require("..");
/**
* Parse for template
*/
function parseTemplate(code, ctx, parserOptions = {}) {
try {
const svelteAst = (0, compiler_1.parse)(code, {
filename: parserOptions.filePath,
});
const ast = (0, index_1.convertSvelteRoot)(svelteAst, ctx);
(0, sort_1.sortNodes)(ast.body);
return {
ast,
svelteAst,
};
}
catch (e) {
if (typeof e.pos === "number") {
const err = new __1.ParseError(e.message, e.pos, ctx);
err.svelteCompilerError = e;
throw err;
}
throw e;
}
}
exports.parseTemplate = parseTemplate;

View File

@ -0,0 +1,14 @@
import { VirtualTypeScriptContext } from "../context";
import type { SvelteHTMLElement } from "../../../ast";
export type AnalyzeTypeScriptContext = {
slots: Set<SvelteHTMLElement>;
};
/**
* Analyze TypeScript source code.
* Generate virtual code to provide correct type information for Svelte store reference namess and scopes.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export declare function analyzeTypeScript(code: {
script: string;
render: string;
}, attrs: Record<string, string | undefined>, parserOptions: any, context: AnalyzeTypeScriptContext): VirtualTypeScriptContext;

View File

@ -0,0 +1,463 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.analyzeTypeScript = void 0;
const scope_1 = require("../../../scope");
const utils_1 = require("../../../utils");
const script_1 = require("../../script");
const context_1 = require("../context");
const RESERVED_NAMES = new Set(["$$props", "$$restProps", "$$slots"]);
/**
* Analyze TypeScript source code.
* Generate virtual code to provide correct type information for Svelte store reference namess and scopes.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
function analyzeTypeScript(code, attrs, parserOptions, context) {
const ctx = new context_1.VirtualTypeScriptContext(code.script + code.render);
ctx.appendOriginal(/^\s*/u.exec(code.script)[0].length);
const result = (0, script_1.parseScriptWithoutAnalyzeScope)(code.script + code.render, attrs, Object.assign(Object.assign({}, parserOptions), {
// Without typings
project: null }));
ctx._beforeResult = result;
analyzeStoreReferenceNames(result, ctx);
analyzeDollarDollarVariables(result, ctx, context.slots);
analyzeReactiveScopes(result, ctx);
analyzeRenderScopes(code, ctx);
return ctx;
}
exports.analyzeTypeScript = analyzeTypeScript;
/**
* Analyze the store reference names.
* Insert type definitions code to provide correct type information for variables that begin with `$`.
*/
function analyzeStoreReferenceNames(result, ctx) {
const scopeManager = result.scopeManager;
const programScope = (0, scope_1.getProgramScope)(scopeManager);
const maybeStoreRefNames = new Set();
for (const reference of scopeManager.globalScope.through) {
if (
// Begin with `$`.
reference.identifier.name.startsWith("$") &&
// Ignore it is a reserved variable.
!RESERVED_NAMES.has(reference.identifier.name) &&
// Ignore if it is already defined.
!programScope.set.has(reference.identifier.name)) {
maybeStoreRefNames.add(reference.identifier.name);
}
}
if (maybeStoreRefNames.size) {
const storeValueTypeName = ctx.generateUniqueId("StoreValueType");
ctx.appendVirtualScript(`type ${storeValueTypeName}<T> = T extends null | undefined
? T
: T extends object & { subscribe(run: infer F, ...args: any): any }
? F extends (value: infer V, ...args: any) => any
? V
: never
: T;`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "TSTypeAliasDeclaration" ||
node.id.name !== storeValueTypeName) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `type` scope
(0, scope_1.removeAllScopeAndVariableAndReference)(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
for (const nm of maybeStoreRefNames) {
const realName = nm.slice(1);
ctx.appendVirtualScript(`declare let ${nm}: ${storeValueTypeName}<typeof ${realName}>;`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "VariableDeclaration" ||
!node.declare ||
node.declarations.length !== 1 ||
node.declarations[0].id.type !== "Identifier" ||
node.declarations[0].id.name !== nm) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `declare` variable
(0, scope_1.removeAllScopeAndVariableAndReference)(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
}
}
}
/**
* Analyze `$$slots`, `$$props`, and `$$restProps` .
* Insert type definitions code to provide correct type information for `$$slots`, `$$props`, and `$$restProps`.
*/
function analyzeDollarDollarVariables(result, ctx, slots) {
const scopeManager = result.scopeManager;
if (scopeManager.globalScope.through.some((reference) => reference.identifier.name === "$$props")) {
appendDeclareVirtualScript("$$props", `{ [index: string]: any }`);
}
if (scopeManager.globalScope.through.some((reference) => reference.identifier.name === "$$restProps")) {
appendDeclareVirtualScript("$$restProps", `{ [index: string]: any }`);
}
if (scopeManager.globalScope.through.some((reference) => reference.identifier.name === "$$slots")) {
const nameTypes = new Set();
for (const slot of slots) {
const nameAttr = slot.startTag.attributes.find((attr) => attr.type === "SvelteAttribute" && attr.key.name === "name");
if (!nameAttr || nameAttr.value.length === 0) {
nameTypes.add('"default"');
continue;
}
if (nameAttr.value.length === 1) {
const value = nameAttr.value[0];
if (value.type === "SvelteLiteral") {
nameTypes.add(JSON.stringify(value.value));
}
else {
nameTypes.add("string");
}
continue;
}
nameTypes.add(`\`${nameAttr.value
.map((value) => value.type === "SvelteLiteral"
? value.value.replace(/([$`])/gu, "\\$1")
: "${string}")
.join("")}\``);
}
appendDeclareVirtualScript("$$slots", `Record<${nameTypes.size > 0 ? [...nameTypes].join(" | ") : "any"}, boolean>`);
}
/** Append declare virtual script */
function appendDeclareVirtualScript(name, type) {
ctx.appendVirtualScript(`declare let ${name}: ${type};`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "VariableDeclaration" ||
!node.declare ||
node.declarations.length !== 1 ||
node.declarations[0].id.type !== "Identifier" ||
node.declarations[0].id.name !== name) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1);
const scopeManager = result.scopeManager;
// Remove `declare` variable
(0, scope_1.removeAllScopeAndVariableAndReference)(node, {
visitorKeys: result.visitorKeys,
scopeManager,
});
return true;
});
}
}
/**
* Analyze the reactive scopes.
* Transform source code to provide the correct type information in the `$:` statements.
*/
function analyzeReactiveScopes(result, ctx) {
const scopeManager = result.scopeManager;
const throughIds = scopeManager.globalScope.through.map((reference) => reference.identifier);
for (const statement of result.ast.body) {
if (statement.type === "LabeledStatement" && statement.label.name === "$") {
if (statement.body.type === "ExpressionStatement" &&
statement.body.expression.type === "AssignmentExpression" &&
statement.body.expression.operator === "=" &&
// Must be a pattern that can be used in the LHS of variable declarations.
// https://github.com/sveltejs/svelte-eslint-parser/issues/213
(statement.body.expression.left.type === "Identifier" ||
statement.body.expression.left.type === "ArrayPattern" ||
statement.body.expression.left.type === "ObjectPattern")) {
const left = statement.body.expression.left;
if (throughIds.some((id) => left.range[0] <= id.range[0] && id.range[1] <= left.range[1])) {
transformForDeclareReactiveVar(statement, statement.body.expression.left, statement.body.expression, result.ast.tokens, ctx);
continue;
}
}
transformForReactiveStatement(statement, ctx);
}
}
}
/**
* Analyze the render scopes.
* Transform source code to provide the correct type information in the HTML templates.
*/
function analyzeRenderScopes(code, ctx) {
ctx.appendOriginal(code.script.length);
const renderFunctionName = ctx.generateUniqueId("render");
ctx.appendVirtualScript(`function ${renderFunctionName}(){`);
ctx.appendOriginalToEnd();
ctx.appendVirtualScript(`}`);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "FunctionDeclaration" ||
node.id.name !== renderFunctionName) {
return false;
}
const program = result.ast;
program.body.splice(program.body.indexOf(node), 1, ...node.body.body);
for (const body of node.body.body) {
body.parent = program;
}
const scopeManager = result.scopeManager;
removeFunctionScope(node, scopeManager);
return true;
});
}
/**
* Transform for `$: id = ...` to `$: let id = ...`
*/
function transformForDeclareReactiveVar(statement, id, expression, tokens, ctx) {
// e.g.
// From:
// $: id = x + y;
//
// To:
// $: let id = fn()
// function fn () { let tmp; return (tmp = x + y); }
//
//
// From:
// $: ({id} = foo);
//
// To:
// $: let {id} = fn()
// function fn () { let tmp; return (tmp = foo); }
/**
* The opening paren tokens for
* `$: ({id} = foo);`
* ^
*/
const openParens = [];
/**
* The equal token for
* `$: ({id} = foo);`
* ^
*/
let eq = null;
/**
* The closing paren tokens for
* `$: ({id} = foo);`
* ^
*/
const closeParens = [];
/**
* The closing paren token for
* `$: id = (foo);`
* ^
*/
let expressionCloseParen = null;
const startIndex = (0, utils_1.sortedLastIndex)(tokens, (target) => target.range[0] - statement.range[0]);
for (let index = startIndex; index < tokens.length; index++) {
const token = tokens[index];
if (statement.range[1] <= token.range[0]) {
break;
}
if (token.range[1] <= statement.range[0]) {
continue;
}
if (token.value === "(" && token.range[1] <= expression.range[0]) {
openParens.push(token);
}
if (token.value === "=" &&
expression.left.range[1] <= token.range[0] &&
token.range[1] <= expression.right.range[0]) {
eq = token;
}
if (token.value === ")") {
if (expression.range[1] <= token.range[0]) {
closeParens.push(token);
}
else if (expression.right.range[1] <= token.range[0]) {
expressionCloseParen = token;
}
}
}
const functionId = ctx.generateUniqueId("reactiveVariableScopeFunction");
const tmpVarId = ctx.generateUniqueId("tmpVar");
for (const token of openParens) {
ctx.appendOriginal(token.range[0]);
ctx.skipOriginalOffset(token.range[1] - token.range[0]);
}
ctx.appendOriginal(expression.range[0]);
ctx.skipUntilOriginalOffset(id.range[0]);
ctx.appendVirtualScript("let ");
ctx.appendOriginal(eq ? eq.range[1] : expression.right.range[0]);
ctx.appendVirtualScript(`${functionId}();\nfunction ${functionId}(){let ${tmpVarId};return (${tmpVarId} = `);
ctx.appendOriginal(expression.right.range[1]);
ctx.appendVirtualScript(`)`);
for (const token of closeParens) {
ctx.appendOriginal(token.range[0]);
ctx.skipOriginalOffset(token.range[1] - token.range[0]);
}
ctx.appendOriginal(statement.range[1]);
ctx.appendVirtualScript(`}`);
// eslint-disable-next-line complexity -- ignore X(
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
var _a;
if (node.type !== "SvelteReactiveStatement") {
return false;
}
const reactiveStatement = node;
if (reactiveStatement.body.type !== "VariableDeclaration" ||
reactiveStatement.body.kind !== "let" ||
reactiveStatement.body.declarations.length !== 1) {
return false;
}
const [idDecl] = reactiveStatement.body.declarations;
if (idDecl.type !== "VariableDeclarator" ||
idDecl.id.type !== id.type ||
((_a = idDecl.init) === null || _a === void 0 ? void 0 : _a.type) !== "CallExpression" ||
idDecl.init.callee.type !== "Identifier" ||
idDecl.init.callee.name !== functionId) {
return false;
}
const program = result.ast;
const nextIndex = program.body.indexOf(node) + 1;
const fnDecl = program.body[nextIndex];
if (!fnDecl ||
fnDecl.type !== "FunctionDeclaration" ||
fnDecl.id.name !== functionId ||
fnDecl.body.body.length !== 2 ||
fnDecl.body.body[0].type !== "VariableDeclaration" ||
fnDecl.body.body[1].type !== "ReturnStatement") {
return false;
}
const tmpVarDeclaration = fnDecl.body.body[0];
if (tmpVarDeclaration.declarations.length !== 1 ||
tmpVarDeclaration.declarations[0].type !== "VariableDeclarator") {
return false;
}
const tempVarDeclId = tmpVarDeclaration.declarations[0].id;
if (tempVarDeclId.type !== "Identifier" ||
tempVarDeclId.name !== tmpVarId) {
return false;
}
const returnStatement = fnDecl.body.body[1];
const assignment = returnStatement.argument;
if ((assignment === null || assignment === void 0 ? void 0 : assignment.type) !== "AssignmentExpression" ||
assignment.left.type !== "Identifier" ||
assignment.right.type !== expression.right.type) {
return false;
}
const tempLeft = assignment.left;
// Remove function declaration
program.body.splice(nextIndex, 1);
// Restore expression statement
assignment.left = idDecl.id;
assignment.loc = {
start: idDecl.id.loc.start,
end: expressionCloseParen
? expressionCloseParen.loc.end
: assignment.right.loc.end,
};
assignment.range = [
idDecl.id.range[0],
expressionCloseParen
? expressionCloseParen.range[1]
: assignment.right.range[1],
];
idDecl.id.parent = assignment;
const newBody = {
type: "ExpressionStatement",
expression: assignment,
directive: undefined,
loc: statement.body.loc,
range: statement.body.range,
parent: reactiveStatement,
};
assignment.parent = newBody;
reactiveStatement.body = newBody;
// Restore statement end location
reactiveStatement.range[1] = returnStatement.range[1];
reactiveStatement.loc.end.line = returnStatement.loc.end.line;
reactiveStatement.loc.end.column = returnStatement.loc.end.column;
// Restore tokens
(0, utils_1.addElementsToSortedArray)(program.tokens, [...openParens, ...closeParens], (a, b) => a.range[0] - b.range[0]);
const scopeManager = result.scopeManager;
(0, scope_1.removeAllScopeAndVariableAndReference)(tmpVarDeclaration, {
visitorKeys: result.visitorKeys,
scopeManager,
});
removeFunctionScope(fnDecl, scopeManager);
const scope = (0, scope_1.getProgramScope)(scopeManager);
for (const reference of (0, scope_1.getAllReferences)(idDecl.id, scope)) {
reference.writeExpr = assignment.right;
}
(0, scope_1.removeIdentifierReference)(tempLeft, scope);
(0, scope_1.removeIdentifierVariable)(tempVarDeclId, scope);
(0, scope_1.removeIdentifierReference)(idDecl.init.callee, scope);
(0, scope_1.removeIdentifierVariable)(idDecl.id, scope);
return true;
});
}
/**
* Transform for `$: ...` to `$: function foo(){...}`
*/
function transformForReactiveStatement(statement, ctx) {
const functionId = ctx.generateUniqueId("reactiveStatementScopeFunction");
const originalBody = statement.body;
ctx.appendOriginal(originalBody.range[0]);
ctx.appendVirtualScript(`function ${functionId}(){`);
ctx.appendOriginal(originalBody.range[1]);
ctx.appendVirtualScript(`}`);
ctx.appendOriginal(statement.range[1]);
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
if (node.type !== "SvelteReactiveStatement") {
return false;
}
const reactiveStatement = node;
const body = reactiveStatement.body;
if (body.type !== "FunctionDeclaration" || body.id.name !== functionId) {
return false;
}
reactiveStatement.body = body.body.body[0];
reactiveStatement.body.parent = reactiveStatement;
const scopeManager = result.scopeManager;
removeFunctionScope(body, scopeManager);
return true;
});
}
/** Remove function scope and marge child scopes to upper scope */
function removeFunctionScope(node, scopeManager) {
const scope = scopeManager.acquire(node);
const upper = scope.upper;
// Remove render function variable
if (node.id) {
(0, scope_1.removeIdentifierVariable)(node.id, upper);
(0, scope_1.removeIdentifierReference)(node.id, upper);
}
(0, scope_1.replaceScope)(scopeManager, scope, scope.childScopes);
// Marge scope
// * marge variables
for (const variable of scope.variables) {
if (variable.name === "arguments" && variable.defs.length === 0) {
continue;
}
const upperVariable = upper.set.get(variable.name);
if (upperVariable) {
(0, utils_1.addElementsToSortedArray)(upperVariable.identifiers, variable.identifiers, (a, b) => a.range[0] - b.range[0]);
(0, utils_1.addElementsToSortedArray)(upperVariable.defs, variable.defs, (a, b) => a.node.range[0] - b.node.range[0]);
(0, scope_1.addAllReferences)(upperVariable.references, variable.references);
}
else {
upper.set.set(variable.name, variable);
(0, scope_1.addVariable)(upper.variables, variable);
variable.scope = upper;
}
for (const reference of variable.references) {
if (reference.from === scope) {
reference.from = upper;
}
reference.resolved = upperVariable || variable;
}
}
// * marge references
(0, scope_1.addAllReferences)(upper.references, scope.references);
for (const reference of scope.references) {
if (reference.from === scope) {
reference.from = upper;
}
}
}

View File

@ -0,0 +1,21 @@
import { RestoreContext } from "./restore";
import type { TSESParseForESLintResult } from "./types";
/**
* Context for virtual TypeScript code.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
export declare class VirtualTypeScriptContext {
private readonly originalCode;
readonly restoreContext: RestoreContext;
script: string;
private consumedIndex;
private readonly unique;
_beforeResult: TSESParseForESLintResult | null;
constructor(code: string);
skipOriginalOffset(offset: number): void;
skipUntilOriginalOffset(offset: number): void;
appendOriginalToEnd(): void;
appendOriginal(index: number): void;
appendVirtualScript(virtualFragment: string): void;
generateUniqueId(base: string): string;
}

View File

@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VirtualTypeScriptContext = void 0;
const unique_1 = require("../../context/unique");
const restore_1 = require("./restore");
/**
* Context for virtual TypeScript code.
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
*/
class VirtualTypeScriptContext {
constructor(code) {
this.script = "";
this.consumedIndex = 0;
this.unique = new unique_1.UniqueIdGenerator();
this._beforeResult = null;
this.originalCode = code;
this.restoreContext = new restore_1.RestoreContext(code);
}
skipOriginalOffset(offset) {
this.consumedIndex += offset;
}
skipUntilOriginalOffset(offset) {
this.consumedIndex = Math.max(offset, this.consumedIndex);
}
appendOriginalToEnd() {
this.appendOriginal(this.originalCode.length);
}
appendOriginal(index) {
if (this.consumedIndex >= index) {
return;
}
this.restoreContext.addOffset({
original: this.consumedIndex,
dist: this.script.length,
});
this.script += this.originalCode.slice(this.consumedIndex, index);
this.consumedIndex = index;
}
appendVirtualScript(virtualFragment) {
const start = this.script.length;
this.script += virtualFragment;
this.restoreContext.addVirtualFragmentRange(start, this.script.length);
}
generateUniqueId(base) {
return this.unique.generate(base, this.originalCode, this.script);
}
}
exports.VirtualTypeScriptContext = VirtualTypeScriptContext;

View File

@ -0,0 +1,9 @@
import type { ESLintExtendedProgram } from "..";
import type { AnalyzeTypeScriptContext } from "./analyze";
/**
* Parse for type script
*/
export declare function parseTypeScript(code: {
script: string;
render: string;
}, attrs: Record<string, string | undefined>, parserOptions: unknown, context: AnalyzeTypeScriptContext): ESLintExtendedProgram;

View File

@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTypeScript = void 0;
const script_1 = require("../script");
const analyze_1 = require("./analyze");
/**
* Parse for type script
*/
function parseTypeScript(code, attrs, parserOptions, context) {
const tsCtx = (0, analyze_1.analyzeTypeScript)(code, attrs, parserOptions, context);
const result = (0, script_1.parseScript)(tsCtx.script, attrs, parserOptions);
tsCtx.restoreContext.restore(result);
return result;
}
exports.parseTypeScript = parseTypeScript;

View File

@ -0,0 +1,33 @@
import type { TSESTree } from "@typescript-eslint/types";
import type { TSESParseForESLintResult } from "./types";
/**
* A function that restores the statement.
* @param node The node to restore.
* @param result The result of parsing.
* @returns
* If `false`, it indicates that the specified node was not processed.
*
* If `true`, it indicates that the specified node was processed for processing.
* This process will no longer be called.
*/
type RestoreStatementProcess = (node: TSESTree.Statement, result: TSESParseForESLintResult) => boolean;
export declare class RestoreContext {
private readonly originalLocs;
private readonly offsets;
private readonly virtualFragments;
private readonly restoreStatementProcesses;
constructor(code: string);
addRestoreStatementProcess(process: RestoreStatementProcess): void;
addOffset(offset: {
original: number;
dist: number;
}): void;
addVirtualFragmentRange(start: number, end: number): void;
/**
* Restore AST nodes
*/
restore(result: TSESParseForESLintResult): void;
private remapLocation;
private getRemapRange;
}
export {};

View File

@ -0,0 +1,140 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestoreContext = void 0;
const traverse_1 = require("../../traverse");
const context_1 = require("../../context");
class RestoreContext {
constructor(code) {
this.offsets = [];
this.virtualFragments = [];
this.restoreStatementProcesses = [];
this.originalLocs = new context_1.LinesAndColumns(code);
}
addRestoreStatementProcess(process) {
this.restoreStatementProcesses.push(process);
}
addOffset(offset) {
this.offsets.push(offset);
}
addVirtualFragmentRange(start, end) {
const peek = this.virtualFragments[this.virtualFragments.length - 1];
if (peek && peek.end === start) {
peek.end = end;
return;
}
this.virtualFragments.push({ start, end });
}
/**
* Restore AST nodes
*/
restore(result) {
var _a, _b;
remapLocations(result, {
remapLocation: (n) => this.remapLocation(n),
removeToken: (token) => this.virtualFragments.some((f) => f.start <= token.range[0] && token.range[1] <= f.end),
});
restoreStatements(result, this.restoreStatementProcesses);
// Adjust program node location
const firstOffset = Math.min(...[result.ast.body[0], (_a = result.ast.tokens) === null || _a === void 0 ? void 0 : _a[0], (_b = result.ast.comments) === null || _b === void 0 ? void 0 : _b[0]]
.filter((t) => Boolean(t))
.map((t) => t.range[0]));
if (firstOffset < result.ast.range[0]) {
result.ast.range[0] = firstOffset;
result.ast.loc.start = this.originalLocs.getLocFromIndex(firstOffset);
}
}
remapLocation(node) {
let [start, end] = node.range;
const startFragment = this.virtualFragments.find((f) => f.start <= start && start < f.end);
if (startFragment) {
start = startFragment.end;
}
const endFragment = this.virtualFragments.find((f) => f.start < end && end <= f.end);
if (endFragment) {
end = endFragment.start;
if (startFragment === endFragment) {
start = startFragment.start;
}
}
if (end < start) {
const w = start;
start = end;
end = w;
}
const locs = this.originalLocs.getLocations(...this.getRemapRange(start, end));
node.loc = locs.loc;
node.range = locs.range;
if (node.start != null) {
delete node.start;
}
if (node.end != null) {
delete node.end;
}
}
getRemapRange(start, end) {
if (!this.offsets.length) {
return [start, end];
}
let lastStart = this.offsets[0];
let lastEnd = this.offsets[0];
for (const offset of this.offsets) {
if (offset.dist <= start) {
lastStart = offset;
}
if (offset.dist < end) {
lastEnd = offset;
}
else {
break;
}
}
const remapStart = lastStart.original + (start - lastStart.dist);
const remapEnd = lastEnd.original + (end - lastEnd.dist);
return [remapStart, remapEnd];
}
}
exports.RestoreContext = RestoreContext;
/** Restore locations */
function remapLocations(result, { remapLocation, removeToken, }) {
const traversed = new Map();
// remap locations
(0, traverse_1.traverseNodes)(result.ast, {
visitorKeys: result.visitorKeys,
enterNode: (node, p) => {
if (!traversed.has(node)) {
traversed.set(node, p);
remapLocation(node);
}
},
leaveNode: (_node) => {
// noop
},
});
const tokens = [];
for (const token of result.ast.tokens || []) {
if (removeToken(token)) {
continue;
}
remapLocation(token);
tokens.push(token);
}
result.ast.tokens = tokens;
for (const token of result.ast.comments || []) {
remapLocation(token);
}
}
/** Restore statement nodes */
function restoreStatements(result, restoreStatementProcesses) {
const restoreStatementProcessesSet = new Set(restoreStatementProcesses);
for (const node of [...result.ast.body]) {
if (!restoreStatementProcessesSet.size) {
break;
}
for (const proc of restoreStatementProcessesSet) {
if (proc(node, result)) {
restoreStatementProcessesSet.delete(proc);
break;
}
}
}
}

View File

@ -0,0 +1,2 @@
import type { parseForESLint } from "@typescript-eslint/parser";
export type TSESParseForESLintResult = ReturnType<typeof parseForESLint>;

View File

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });