Skip to content
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

Fix support for gts extensions remaining in emitted declarations #648

Closed
Show file tree
Hide file tree
Changes from 2 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
32 changes: 32 additions & 0 deletions packages/core/__tests__/cli/custom-extensions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ describe('CLI: custom extensions', () => {
'Greeting.gts': stripIndent`
<template>Hello!</template>
`,
're-export.gts': stripIndent`
export { default as Greeting } from './Greeting.gts';
`,
});
});

Expand All @@ -147,6 +150,11 @@ describe('CLI: custom extensions', () => {

1 import Greeting from './Greeting.gts';
~~~~~~~~~~~~~~~~

re-export.gts:1:37 - error TS2307: Cannot find module './Greeting.gts' or its corresponding type declarations.

1 export { default as Greeting } from './Greeting.gts';
~~~~~~~~~~~~~~~~
"
`);
});
Expand All @@ -165,5 +173,29 @@ describe('CLI: custom extensions', () => {
expect(result.stderr).toBe('');
}
);

test.runIf(semver.gte(typescript.version, '5.0.0'))(
'declarations work with `allowImportingTsExtensions: true`',
NullVoxPopuli marked this conversation as resolved.
Show resolved Hide resolved
async () => {
project.updateTsconfig((config) => {
config.compilerOptions ??= {};
config.compilerOptions['allowImportingTsExtensions'] = true;
});

let emitResult = await project.check({ flags: ['--declaration'] });

expect(emitResult.exitCode).toBe(0);

expect(project.read('re-export.d.ts')).toMatchInlineSnapshot(`
"export { default as Greeting } from './Greeting';
"
`);
expect(project.read('./Greeting.d.ts')).toMatchInlineSnapshot(`
"declare const _default: import(\\"@ember/component/template-only\\").TemplateOnlyComponent<never> & (abstract new () => import(\\"@glint/template/-private/integration\\").InvokableInstance<() => import(\\"@glint/template/-private/integration\\").ComponentReturn<{}>> & import(\\"@glint/template/-private/integration\\").HasContext<import(\\"@glint/template/-private/integration\\").TemplateContext<void, {}, {}, void>>);
export default _default;
"
`);
}
);
});
});
17 changes: 13 additions & 4 deletions packages/core/__tests__/transform/offset-mapping.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { rewriteModule, TransformedModule, rewriteDiagnostic } from '../../src/transform/index.js';
import { stripIndent } from 'common-tags';
import { describe, test, expect } from 'vitest';
import { describe, test, expect, beforeEach } from 'vitest';
import { Range, SourceFile } from '../../src/transform/template/transformed-module.js';
import * as ts from 'typescript';
import { assert } from '../../src/transform/util.js';
Expand Down Expand Up @@ -464,7 +464,12 @@ describe('Transform: Source-to-source offset mapping', () => {
`,
};

const rewritten = rewriteModule(ts, { script: source }, glimmerxEnvironment)!;
let rewritten;

beforeEach(() => {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

without these changes, debugging was super troll time

rewritten = rewriteModule(ts, { script: source }, glimmerxEnvironment)!;
});


test('bounds that cross a rewritten span', () => {
let originalStart = source.contents.indexOf('// start');
Expand Down Expand Up @@ -524,8 +529,12 @@ describe('Diagnostic offset mapping', () => {
`,
};

const transformedModule = rewriteModule(ts, { script: source }, glimmerxEnvironment);
assert(transformedModule);
let transformedModule;

beforeEach(() => {
transformedModule = rewriteModule(ts, { script: source }, glimmerxEnvironment);
assert(transformedModule);
});

test('without related information', () => {
let category = ts.DiagnosticCategory.Error;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/common/document-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,4 +197,4 @@ const SCRIPT_EXTENSION_REGEX = /\.(ts|js)$/;

export function templatePathForSynthesizedModule(path: string): string {
return path.replace(SCRIPT_EXTENSION_REGEX, '.hbs');
}
}
14 changes: 14 additions & 0 deletions packages/core/src/common/transform-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,10 +438,24 @@ export default class TransformManager {
};

transformedModule = rewriteModule(this.ts, { script, template }, glintConfig.environment);
} else {
let candidates = documents.getCandidateDocumentPaths(filename);
for (let candidate of candidates) {
if (documents.documentExists(candidate)) {
let contents = documents.getDocumentContents(filename, encoding);
let canonicalPath = documents.getCanonicalDocumentPath(filename);
let script = { filename: canonicalPath, contents };
let template = undefined;

transformedModule = rewriteModule(this.ts, { script, template }, environment);
}
}

}
}
}


let transformedFileName = glintConfig.getSynthesizedScriptPathForTS(filename);
let cacheEntry = { version, transformedFileName, transformedModule };
this.transformCache.set(documentID, cacheEntry);
Expand Down
52 changes: 52 additions & 0 deletions packages/core/src/transform/template/rewrite-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ function parseScript(ts: TSLib, script: SourceFile, environment: GlintEnvironmen
true // setParentNodes
);

// transformations from environment plugins
if (transform) {
let { transformed } = ts.transform(ast, [
(context) => transform!(preprocessed.data, { ts, context, setEmitMetadata }),
Expand All @@ -133,9 +134,60 @@ function parseScript(ts: TSLib, script: SourceFile, environment: GlintEnvironmen
ast = transformed[0];
}

ast = removeExtensions(ts, ast);

return { ast, emitMetadata };
}

// transformations to handle extensions present in import specifiers
// because we drop the extensions elsewhere so that plain .d.ts files are emitted.
//
// Note that these examples do not guarantee that transpilation would succeed.
// This transform is purely concerned about resolving type declarations.
//
// import { X } from 'foo.gts';
// => implies a foo.d.ts exists, rather than foo.gts.d.ts, as Svelte does
// as Svelte would (tho, they have only one file type for both js and ts
// (foo.svelte => foo.svelte.d.ts))
// import { X } from 'foo.gjs';
// => implies a foo.d.ts exists, rather than foo.gjs.d.ts,
// as Svelte would (tho, they have only one file type for both js and ts
// (foo.svelte => foo.svelte.d.ts))
// import { X } from 'foo';
// => no change, this is default behavior, implies a foo.d.ts exists
// import { X } from 'foo.js';
// => no change, this is default behavior, implies a foo.d.ts exists
// import { X } from 'foo.ts';
// => no change, this is default behavior, implies a foo.d.ts exists
function removeExtensions(ts: TSLib, ast: ts.SourceFile): ts.SourceFile {
let { transformed } = ts.transform(ast, [
(context) =>
function visit<T extends ts.Node>(node: T): T {
if (ts.isImportDeclaration(node)) {

// types are missing
let specifier: any = node.moduleSpecifier;
let _ts: any = ts;
if (_ts.isModuleSpecifierLike) {
if (_ts.isModuleSpecifierLike(specifier) && specifier.text.endsWith('.gts')) {
return _ts.factory.createImportDeclaration(
node.modifiers,
node.importClause,
_ts.factory.createStringLiteral(specifier.text.replace(/\.gts$/, ''))
);
}
}
}

return ts.visitEachChild(node, child => visit(child), context);
}
]);

ast = transformed[0];

return ast;
}

/**
* Given a sparse `CorrelatedSpan` array and the original source for a module,
* returns the resulting full transformed source string for that module, as
Expand Down
Loading