Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module.exports = {
'import/no-unused-modules': 'off',
'import/no-deprecated': 'off',
// project-specific settings
'max-len': ['error', { code: 100, ignoreComments: true, ignoreStrings: true }],
'max-len': 'off', // handled by prettier
'no-trailing-spaces': 'error',
'one-var': ['error', 'never'],
'@typescript-eslint/no-unused-vars': ['error', { args: 'none' }],
Expand Down
2 changes: 1 addition & 1 deletion docs/internal/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ function render() {
return { props: { world }, slots: {}, events: {} };
}
// -- generate a class
export default class _World_ extends createSvelte2TsxComponent(__sveltets_partial(render)) {}
export default class _World_ extends createSvelte2TsxComponent(__sveltets_1_partial(render)) {}
```

3. Pass that result to the TypeScript language service
Expand Down
2 changes: 1 addition & 1 deletion packages/language-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"source-map": "^0.7.3",
"svelte": "~3.38.2",
"svelte-preprocess": "~4.7.3",
"svelte2tsx": "~0.2.0",
"svelte2tsx": "~0.3.0",
"typescript": "*",
"vscode-css-languageservice": "5.0.0",
"vscode-emmet-helper": "2.1.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RawSourceMap, SourceMapConsumer } from 'source-map';
import svelte2tsx, { IExportedNames } from 'svelte2tsx';
import { svelte2tsx, IExportedNames } from 'svelte2tsx';
import ts from 'typescript';
import { Position, Range, TextDocumentContentChangeEvent } from 'vscode-languageserver';
import {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@ export class LSAndTSDocResolver {
* @param docManager
* @param workspaceUris
* @param configManager
* @param isSvelteCheck True, if used in the context of svelte-check
* @param tsconfigPath This should only be set via svelte-check. Makes sure all documents are resolved to that tsconfig. Has to be absolute.
*/
constructor(
private readonly docManager: DocumentManager,
private readonly workspaceUris: string[],
private readonly configManager: LSConfigManager,
private readonly isSvelteCheck = false,
private readonly tsconfigPath?: string
) {
const handleDocumentChange = (document: Document) => {
Expand Down Expand Up @@ -64,8 +66,9 @@ export class LSAndTSDocResolver {

private get lsDocumentContext(): LanguageServiceDocumentContext {
return {
ambientTypesSource: this.isSvelteCheck ? 'svelte-check' : 'svelte2tsx',
createDocument: this.createDocument,
transformOnTemplateError: !this.tsconfigPath,
transformOnTemplateError: !this.isSvelteCheck,
globalSnapshotsManager: this.globalSnapshotsManager
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class HoverProviderImpl implements HoverProvider {
// show docs of $store instead of store if necessary
const is$store = fragment.text
.substring(0, info.textSpan.start)
.endsWith('(__sveltets_store_get(');
.endsWith('(__sveltets_1_store_get(');
if (is$store) {
const infoFor$store = lang.getQuickInfoAtPosition(
tsDoc.filePath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,13 +317,13 @@ export class RenameProviderImpl implements RenameProvider {

const content = snapshot.getText(0, snapshot.getLength());
// When the user renames a Svelte component, ts will also want to rename
// `__sveltets_instanceOf(TheComponentToRename)` or
// `__sveltets_ensureType(TheComponentToRename,..`. Prevent that.
// `__sveltets_1_instanceOf(TheComponentToRename)` or
// `__sveltets_1_ensureType(TheComponentToRename,..`. Prevent that.
// Additionally, we cannot rename the hidden variable containing the store value
return (
notPrecededBy('__sveltets_instanceOf(') &&
notPrecededBy('__sveltets_ensureType(') &&
notPrecededBy('= __sveltets_store_get(')
notPrecededBy('__sveltets_1_instanceOf(') &&
notPrecededBy('__sveltets_1_ensureType(') &&
notPrecededBy('= __sveltets_1_store_get(')
);

function notPrecededBy(str: string) {
Expand Down
7 changes: 4 additions & 3 deletions packages/language-server/src/plugins/typescript/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export interface LanguageServiceContainer {
const services = new Map<string, Promise<LanguageServiceContainer>>();

export interface LanguageServiceDocumentContext {
ambientTypesSource: string;
transformOnTemplateError: boolean;
createDocument: (fileName: string, content: string) => Document;
globalSnapshotsManager: GlobalSnapshotsManager;
Expand Down Expand Up @@ -110,10 +111,10 @@ async function createLanguageService(

let svelteTsPath: string;
try {
// For when svelte2tsx is part of node_modules, for example VS Code extension
svelteTsPath = dirname(require.resolve('svelte2tsx'));
// For when svelte2tsx/svelte-check is part of node_modules, for example VS Code extension
svelteTsPath = dirname(require.resolve(docContext.ambientTypesSource));
} catch (e) {
// Fall back to dirname, for example for svelte-check
// Fall back to dirname
svelteTsPath = __dirname;
}
const svelteTsxFiles = [
Expand Down
1 change: 1 addition & 0 deletions packages/language-server/src/svelte-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export class SvelteCheck {
this.docManager,
[pathToUrl(workspacePath)],
this.configManager,
true,
options.tsconfig
);
this.pluginHost.register(
Expand Down
4 changes: 2 additions & 2 deletions packages/svelte2tsx/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ function render() {
return { props: { world }, slots: {}, events: {} };
}

export default class _World_ extends createSvelte2TsxComponent(
__sveltets_partial(__sveltets_with_any_event(render))
export default class _World_ extends __sveltets_1_createSvelte2TsxComponent(
__sveltets_1_partial(__sveltets_1_with_any_event(render))
) {}
```

Expand Down
2 changes: 1 addition & 1 deletion packages/svelte2tsx/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export interface ComponentEvents {
getAll(): { name: string; type: string; doc?: string }[];
}

export default function svelte2tsx(
export function svelte2tsx(
svelte: string,
options?: {
/**
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte2tsx/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "svelte2tsx",
"version": "0.2.0",
"version": "0.3.0",
"description": "Convert Svelte components to TSX for type checking",
"author": "David Pershouse",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte2tsx/repl/debug.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs';
import svelte2tsx from '../src';
import { svelte2tsx } from '../src';
const content = fs.readFileSync(`${__dirname}/index.svelte`, 'utf-8');
svelte2tsx(content);
/**
Expand Down
8 changes: 4 additions & 4 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/action-directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,25 @@ import { isQuote } from '../utils/node-utils';
import { BaseDirective, BaseNode } from '../../interfaces';

/**
* use:xxx={params} ---> {...__sveltets_ensureAction(xxx(__sveltets_mapElementTag('ParentNodeName'),(params)))}
* use:xxx={params} ---> {...__sveltets_1_ensureAction(xxx(__sveltets_1_mapElementTag('ParentNodeName'),(params)))}
*/
export function handleActionDirective(
htmlx: string,
str: MagicString,
attr: BaseDirective,
parent: BaseNode
): void {
str.overwrite(attr.start, attr.start + 'use:'.length, '{...__sveltets_ensureAction(');
str.overwrite(attr.start, attr.start + 'use:'.length, '{...__sveltets_1_ensureAction(');

if (!attr.expression) {
str.appendLeft(attr.end, `(__sveltets_mapElementTag('${parent.name}')))}`);
str.appendLeft(attr.end, `(__sveltets_1_mapElementTag('${parent.name}')))}`);
return;
}

str.overwrite(
attr.start + `use:${attr.name}`.length,
attr.expression.start,
`(__sveltets_mapElementTag('${parent.name}'),(`
`(__sveltets_1_mapElementTag('${parent.name}'),(`
);
str.appendLeft(attr.expression.end, ')))');
const lastChar = htmlx[attr.end - 1];
Expand Down
10 changes: 5 additions & 5 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/animation-directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { isQuote } from '../utils/node-utils';
import { BaseDirective, BaseNode } from '../../interfaces';

/**
* animate:xxx(yyy) ---> {...__sveltets_ensureAnimation(xxx(__sveltets_mapElementTag('..'),__sveltets_AnimationMove,(yyy)))}
* animate:xxx(yyy) ---> {...__sveltets_1_ensureAnimation(xxx(__sveltets_1_mapElementTag('..'),__sveltets_1_AnimationMove,(yyy)))}
*/
export function handleAnimateDirective(
htmlx: string,
Expand All @@ -14,19 +14,19 @@ export function handleAnimateDirective(
str.overwrite(
attr.start,
htmlx.indexOf(':', attr.start) + 1,
'{...__sveltets_ensureAnimation('
'{...__sveltets_1_ensureAnimation('
);

const nodeType = `__sveltets_mapElementTag('${parent.name}')`;
const nodeType = `__sveltets_1_mapElementTag('${parent.name}')`;

if (!attr.expression) {
str.appendLeft(attr.end, `(${nodeType},__sveltets_AnimationMove,{}))}`);
str.appendLeft(attr.end, `(${nodeType},__sveltets_1_AnimationMove,{}))}`);
return;
}
str.overwrite(
htmlx.indexOf(':', attr.start) + 1 + `${attr.name}`.length,
attr.expression.start,
`(${nodeType},__sveltets_AnimationMove,(`
`(${nodeType},__sveltets_1_AnimationMove,(`
);
str.appendLeft(attr.expression.end, ')))');
if (isQuote(htmlx[attr.end - 1])) {
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte2tsx/src/htmlxtojsx/nodes/attribute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export function handleAttribute(

// Custom CSS property
if (parent.type === 'InlineComponent' && attr.name.startsWith('--') && attr.value !== true) {
str.prependRight(attr.start, '{...__sveltets_cssProp({"');
str.prependRight(attr.start, '{...__sveltets_1_cssProp({"');
buildTemplateString(attr, str, htmlx, '": `', '`})}');
return;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/await.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function handleAwaitPending(
return;
}
// no need to prepend ifcondition here as we know the then block is empty
str.appendLeft(pendingEnd, '__sveltets_awaitThen(_$$p, () => {<>');
str.appendLeft(pendingEnd, '__sveltets_1_awaitThen(_$$p, () => {<>');
}

export function handleAwaitThen(
Expand All @@ -71,7 +71,7 @@ export function handleAwaitThen(
}

// then value } | {:then value} | {await ..} .. {/await} ->
// __sveltets_awaitThen(_$$p, (value) => {(possibleIfCondition && )<>
// __sveltets_1_awaitThen(_$$p, (value) => {(possibleIfCondition && )<>
let thenStart: number;
let thenEnd: number;
// then value } | {:then value}
Expand All @@ -93,10 +93,10 @@ export function handleAwaitThen(
}

if (awaitBlock.value) {
str.overwrite(thenStart, awaitBlock.value.start, '__sveltets_awaitThen(_$$p, (');
str.overwrite(thenStart, awaitBlock.value.start, '__sveltets_1_awaitThen(_$$p, (');
str.overwrite(awaitBlock.value.end, thenEnd, `) => {${ifScope.addPossibleIfCondition()}<>`);
} else {
const awaitThenFn = `__sveltets_awaitThen(_$$p, () => {${ifScope.addPossibleIfCondition()}<>`; // eslint-disable-line
const awaitThenFn = `__sveltets_1_awaitThen(_$$p, () => {${ifScope.addPossibleIfCondition()}<>`; // eslint-disable-line
if (thenStart === thenEnd) {
str.appendLeft(thenStart, awaitThenFn);
} else {
Expand Down
10 changes: 5 additions & 5 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function handleBinding(
//bind group on input
if (attr.name == 'group' && el.name == 'input') {
str.remove(attr.start, attr.expression.start);
str.appendLeft(attr.expression.start, '{...__sveltets_empty(');
str.appendLeft(attr.expression.start, '{...__sveltets_1_empty(');

const endBrackets = ')}';
if (isShortHandAttribute(attr)) {
Expand All @@ -49,7 +49,7 @@ export function handleBinding(

if (thisType) {
str.remove(attr.start, attr.expression.start);
str.appendLeft(attr.expression.start, `{...__sveltets_ensureType(${thisType}, `);
str.appendLeft(attr.expression.start, `{...__sveltets_1_ensureType(${thisType}, `);
str.overwrite(attr.expression.end, attr.end, ')}');
return;
}
Expand All @@ -58,19 +58,19 @@ export function handleBinding(
//one way binding
if (oneWayBindingAttributes.has(attr.name) && el.type === 'Element') {
str.remove(attr.start, attr.expression.start);
str.appendLeft(attr.expression.start, '{...__sveltets_empty(');
str.appendLeft(attr.expression.start, '{...__sveltets_1_empty(');
if (isShortHandAttribute(attr)) {
// eslint-disable-next-line max-len
str.appendLeft(
attr.end,
`=__sveltets_instanceOf(${oneWayBindingAttributes.get(attr.name)}).${attr.name})}`
`=__sveltets_1_instanceOf(${oneWayBindingAttributes.get(attr.name)}).${attr.name})}`
);
} else {
// eslint-disable-next-line max-len
str.overwrite(
attr.expression.end,
attr.end,
`=__sveltets_instanceOf(${oneWayBindingAttributes.get(attr.name)}).${attr.name})}`
`=__sveltets_1_instanceOf(${oneWayBindingAttributes.get(attr.name)}).${attr.name})}`
);
}
return;
Expand Down
4 changes: 2 additions & 2 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/class-directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import MagicString from 'magic-string';
import { BaseDirective } from '../../interfaces';

/**
* class:xx={yyy} ---> {...__sveltets_ensureType(Boolean, !!(yyy))}
* class:xx={yyy} ---> {...__sveltets_1_ensureType(Boolean, !!(yyy))}
*/
export function handleClassDirective(str: MagicString, attr: BaseDirective): void {
str.overwrite(attr.start, attr.expression.start, '{...__sveltets_ensureType(Boolean, !!(');
str.overwrite(attr.start, attr.expression.start, '{...__sveltets_1_ensureType(Boolean, !!(');
const endBrackets = '))}';
if (attr.end !== attr.expression.end) {
str.overwrite(attr.expression.end, attr.end, endBrackets);
Expand Down
4 changes: 2 additions & 2 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/each.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ export function handleEach(
ifScope: IfScope
): void {
// {#each items as item,i (key)} ->
// {__sveltets_each(items, (item,i) => (key) && (possible if expression &&) <>
// {__sveltets_1_each(items, (item,i) => (key) && (possible if expression &&) <>
const constRedeclares = ifScope.getConstDeclaration();
const prefix = constRedeclares ? `{() => {${constRedeclares}() => ` : '';
str.overwrite(eachBlock.start, eachBlock.expression.start, `${prefix}{__sveltets_each(`);
str.overwrite(eachBlock.start, eachBlock.expression.start, `${prefix}{__sveltets_1_each(`);
str.overwrite(eachBlock.expression.end, eachBlock.context.start, ', (');

// {#each true, items as item}
Expand Down
4 changes: 2 additions & 2 deletions packages/svelte2tsx/src/htmlxtojsx/nodes/event-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { BaseDirective, BaseNode } from '../../interfaces';
/**
* Transform on:xxx={yyy}
* - For DOM elements: ---> onxxx={yyy}
* - For Svelte components/special elements: ---> {__sveltets_instanceOf(..ComponentType..).$on("xxx", yyy)}
* - For Svelte components/special elements: ---> {__sveltets_1_instanceOf(..ComponentType..).$on("xxx", yyy)}
*/
export function handleEventHandler(
htmlx: string,
Expand Down Expand Up @@ -35,7 +35,7 @@ export function handleEventHandler(
} else {
if (attr.expression) {
const on = 'on';
//for handler assignment, we change it to call to our __sveltets_ensureFunction
//for handler assignment, we change it to call to our __sveltets_1_ensureFunction
str.appendRight(attr.start, `{${getInstanceType(parent, str.original)}.$`);
const eventNameIndex = htmlx.indexOf(':', attr.start) + 1;
str.overwrite(htmlx.indexOf(on, attr.start) + on.length, eventNameIndex, "('");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { isQuote } from '../utils/node-utils';
import { BaseDirective, BaseNode } from '../../interfaces';

/**
* transition:xxx(yyy) ---> {...__sveltets_ensureTransition(xxx(__sveltets_mapElementTag('..'),(yyy)))}
* transition:xxx(yyy) ---> {...__sveltets_1_ensureTransition(xxx(__sveltets_1_mapElementTag('..'),(yyy)))}
*/
export function handleTransitionDirective(
htmlx: string,
Expand All @@ -14,15 +14,15 @@ export function handleTransitionDirective(
str.overwrite(
attr.start,
htmlx.indexOf(':', attr.start) + 1,
'{...__sveltets_ensureTransition('
'{...__sveltets_1_ensureTransition('
);

if (attr.modifiers.length) {
const local = htmlx.indexOf('|', attr.start);
str.remove(local, attr.expression ? attr.expression.start : attr.end);
}

const nodeType = `__sveltets_mapElementTag('${parent.name}')`;
const nodeType = `__sveltets_1_mapElementTag('${parent.name}')`;

if (!attr.expression) {
str.appendLeft(attr.end, `(${nodeType},{}))}`);
Expand Down
Loading