Skip to content

Better Typescript transpilation #392

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Sep 4, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
Prev Previous commit
Next Next commit
fix: handle sourcemaps in typescript transformer
- introduce two deps: magic-string, sorcery
- produce a source map on each step of the process
- store all source maps in a chain
- refactor transformer to increase readability
  • Loading branch information
SomaticIT committed Apr 15, 2021
commit 8c973415357af9529df0eb7235041c5fca355880
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@
"@types/pug": "^2.0.4",
"@types/sass": "^1.16.0",
"detect-indent": "^6.0.0",
"magic-string": "^0.25.7",
"sorcery": "^0.10.0",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorcery was not supported for a long time and adds a few unnecessary dependencies.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got a good alternative to achieve source map concatenation?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could bump sorcery to node 10 or 12 and get rid from "sander" package. Though I see svelte-preprocess still supports node 9. Do you plan major bump in near future?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this mean you have write access to the repo? I only see Rich having contributed to that repository. Can't speak for how soon @kaisermann plans on bumping, but if a little cleanup can be done I have nothing against that. Not pressing for me since the solution seems to work so far.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't yet but I can ask Rich

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could bump sorcery to node 10 or 12 and get rid from "sander" package. Though I see svelte-preprocess still supports node 9. Do you plan major bump in near future?

Yeah, I've been wanting to remove the deprecated things and do a little cleanup.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we're already here, I've started a discussion about one of the things on my mind for the next major: #424

"strip-indent": "^3.0.0"
},
"peerDependencies": {
Expand Down
299 changes: 231 additions & 68 deletions src/transformers/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,24 @@ import { dirname, isAbsolute, join } from 'path';

import ts from 'typescript';
import { compile } from 'svelte/compiler';
import MagicString from 'magic-string';
import sorcery from 'sorcery';

import { throwTypescriptError } from '../modules/errors';
import { createTagRegex, parseAttributes, stripTags } from '../modules/markup';
import type { Transformer, Options } from '../types';

type CompilerOptions = Options.Typescript['compilerOptions'];
type CompilerOptions = ts.CompilerOptions;

type SourceMapChain = {
content: Record<string, string>;
sourcemaps: Record<string, object>;
};

function createFormatDiagnosticsHost(cwd: string): ts.FormatDiagnosticsHost {
return {
getCanonicalFileName: (fileName: string) => fileName,
getCanonicalFileName: (fileName: string) =>
fileName.replace('.injected.ts', ''),
getCurrentDirectory: () => cwd,
getNewLine: () => ts.sys.newLine,
};
Expand Down Expand Up @@ -70,16 +78,37 @@ function getComponentScriptContent(markup: string): string {
return '';
}

function createSourceMapChain({
filename,
content,
compilerOptions,
}: {
filename: string;
content: string;
compilerOptions: CompilerOptions;
}): SourceMapChain | undefined {
if (compilerOptions.sourceMap) {
return {
content: {
[filename]: content,
},
sourcemaps: {},
};
}
}

function injectVarsToCode({
content,
markup,
filename,
attributes,
sourceMapChain,
}: {
content: string;
markup?: string;
filename?: string;
filename: string;
attributes?: Record<string, any>;
sourceMapChain?: SourceMapChain;
}): string {
if (!markup) return content;

Expand All @@ -93,90 +122,103 @@ function injectVarsToCode({
const sep = '\nconst $$$$$$$$ = null;\n';
const varsValues = vars.map((v) => v.name).join(',');
const injectedVars = `const $$vars$$ = [${varsValues}];`;
const injectedCode =
attributes?.context === 'module'
? `${sep}${getComponentScriptContent(markup)}\n${injectedVars}`
: `${sep}${injectedVars}`;

if (sourceMapChain) {
const s = new MagicString(content);

if (attributes?.context === 'module') {
const componentScript = getComponentScriptContent(markup);
s.append(injectedCode);

return `${content}${sep}${componentScript}\n${injectedVars}`;
const fname = `${filename}.injected.ts`;
const code = s.toString();
const map = s.generateMap({
source: filename,
file: fname,
});

sourceMapChain.content[fname] = code;
sourceMapChain.sourcemaps[fname] = map;

return code;
}

return `${content}${sep}${injectedVars}`;
return `${content}${injectedCode}`;
}

function stripInjectedCode({
compiledCode,
transpiledCode,
markup,
filename,
sourceMapChain,
}: {
compiledCode: string;
transpiledCode: string;
markup?: string;
filename: string;
sourceMapChain?: SourceMapChain;
}): string {
return markup
? compiledCode.slice(0, compiledCode.indexOf('const $$$$$$$$ = null;'))
: compiledCode;
}
if (!markup) return transpiledCode;

export function loadTsconfig(
compilerOptionsJSON: any,
filename: string,
tsOptions: Options.Typescript,
) {
if (typeof tsOptions.tsconfigFile === 'boolean') {
return { errors: [], options: compilerOptionsJSON };
}
const injectedCodeStart = transpiledCode.indexOf('const $$$$$$$$ = null;');

let basePath = process.cwd();
if (sourceMapChain) {
const s = new MagicString(transpiledCode);
const st = s.snip(0, injectedCodeStart);

const fileDirectory = (tsOptions.tsconfigDirectory ||
dirname(filename)) as string;
const source = `${filename}.transpiled.js`;
const file = `${filename}.js`;
const code = st.toString();
const map = st.generateMap({
source,
file,
});

let tsconfigFile =
tsOptions.tsconfigFile ||
ts.findConfigFile(fileDirectory, ts.sys.fileExists);
sourceMapChain.content[file] = code;
sourceMapChain.sourcemaps[file] = map;

tsconfigFile = isAbsolute(tsconfigFile)
? tsconfigFile
: join(basePath, tsconfigFile);
return code;
}

basePath = dirname(tsconfigFile);
return transpiledCode.slice(0, injectedCodeStart);
}

const { error, config } = ts.readConfigFile(tsconfigFile, ts.sys.readFile);
async function concatSourceMaps({
filename,
markup,
sourceMapChain,
}: {
filename: string;
markup?: string;
sourceMapChain?: SourceMapChain;
}): Promise<string | object | undefined> {
if (!sourceMapChain) return;

if (error) {
throw new Error(formatDiagnostics(error, basePath));
if (!markup) {
return sourceMapChain.sourcemaps[`${filename}.js`];
}

// Do this so TS will not search for initial files which might take a while
config.include = [];

let { errors, options } = ts.parseJsonConfigFileContent(
config,
ts.sys,
basePath,
compilerOptionsJSON,
tsconfigFile,
);

// Filter out "no files found error"
errors = errors.filter((d) => d.code !== 18003);
const chain = await sorcery.load(`${filename}.js`, sourceMapChain);

return { errors, options };
return chain.apply();
}

const transformer: Transformer<Options.Typescript> = ({
content,
function getCompilerOptions({
filename,
markup,
options = {},
attributes,
}) => {
options,
basePath,
}: {
filename: string;
options: Options.Typescript;
basePath: string;
}): CompilerOptions {
// default options
const compilerOptionsJSON = {
moduleResolution: 'node',
target: 'es6',
};

const basePath = process.cwd();

Object.assign(compilerOptionsJSON, options.compilerOptions);

const { errors, options: convertedCompilerOptions } =
Expand All @@ -203,19 +245,38 @@ const transformer: Transformer<Options.Typescript> = ({
);
}

return compilerOptions;
}

function transpileTs({
code,
markup,
filename,
basePath,
options,
compilerOptions,
sourceMapChain,
}: {
code: string;
markup: string;
filename: string;
basePath: string;
options: Options.Typescript;
compilerOptions: CompilerOptions;
sourceMapChain: SourceMapChain;
}): { transpiledCode: string; diagnostics: ts.Diagnostic[] } {
const fileName = markup ? `${filename}.injected.ts` : filename;

const {
outputText: compiledCode,
sourceMapText: map,
outputText: transpiledCode,
sourceMapText,
diagnostics,
} = ts.transpileModule(
injectVarsToCode({ content, markup, filename, attributes }),
{
fileName: filename,
compilerOptions,
reportDiagnostics: options.reportDiagnostics !== false,
transformers: markup ? {} : { before: [importTransformer] },
},
);
} = ts.transpileModule(code, {
fileName,
compilerOptions,
reportDiagnostics: options.reportDiagnostics !== false,
transformers: markup ? {} : { before: [importTransformer] },
});

if (diagnostics.length > 0) {
// could this be handled elsewhere?
Expand All @@ -232,7 +293,109 @@ const transformer: Transformer<Options.Typescript> = ({
}
}

const code = stripInjectedCode({ compiledCode, markup });
if (sourceMapChain) {
const fname = markup ? `${filename}.transpiled.js` : `${filename}.js`;

sourceMapChain.content[fname] = transpiledCode;
sourceMapChain.sourcemaps[fname] = JSON.parse(sourceMapText);
}

return { transpiledCode, diagnostics };
}

export function loadTsconfig(
compilerOptionsJSON: any,
filename: string,
tsOptions: Options.Typescript,
) {
if (typeof tsOptions.tsconfigFile === 'boolean') {
return { errors: [], options: compilerOptionsJSON };
}

let basePath = process.cwd();

const fileDirectory = (tsOptions.tsconfigDirectory ||
dirname(filename)) as string;

let tsconfigFile =
tsOptions.tsconfigFile ||
ts.findConfigFile(fileDirectory, ts.sys.fileExists);

tsconfigFile = isAbsolute(tsconfigFile)
? tsconfigFile
: join(basePath, tsconfigFile);

basePath = dirname(tsconfigFile);

const { error, config } = ts.readConfigFile(tsconfigFile, ts.sys.readFile);

if (error) {
throw new Error(formatDiagnostics(error, basePath));
}

// Do this so TS will not search for initial files which might take a while
config.include = [];

let { errors, options } = ts.parseJsonConfigFileContent(
config,
ts.sys,
basePath,
compilerOptionsJSON,
tsconfigFile,
);

// Filter out "no files found error"
errors = errors.filter((d) => d.code !== 18003);

return { errors, options };
}

const transformer: Transformer<Options.Typescript> = async ({
content,
filename = 'source.svelte',
markup,
options = {},
attributes,
}) => {
const basePath = process.cwd();
const compilerOptions = getCompilerOptions({ filename, options, basePath });

const sourceMapChain = createSourceMapChain({
filename,
content,
compilerOptions,
});

const injectedCode = injectVarsToCode({
content,
markup,
filename,
attributes,
sourceMapChain,
});

const { transpiledCode, diagnostics } = transpileTs({
code: injectedCode,
markup,
filename,
basePath,
options,
compilerOptions,
sourceMapChain,
});

const code = stripInjectedCode({
transpiledCode,
markup,
filename,
sourceMapChain,
});

const map = await concatSourceMaps({
filename,
markup,
sourceMapChain,
});

return {
code,
Expand Down
Loading