From 3ef1b01e145aa4b29db5d8eadeeec68a36bc2d2e Mon Sep 17 00:00:00 2001 From: Drew Powers <1369770+drwpow@users.noreply.github.com> Date: Wed, 12 May 2021 12:06:16 -0600 Subject: [PATCH] [wip] Fix CI (#202) * Yarn format * Fix changeset --since * Fix Windows tests --- .github/workflows/changelog.yml | 20 +- .github/workflows/changeset.yml | 26 --- .github/workflows/format.yml | 4 +- .github/workflows/nodejs.yml | 39 +++- package.json | 6 +- packages/astro-prism/CHANGELOG.md | 1 + .../astro/src/compiler/codegen/content.ts | 7 +- packages/astro/test/astro-basic.test.js | 2 +- packages/astro/test/astro-children.test.js | 6 +- packages/astro/test/astro-collection.test.js | 2 + .../astro/test/astro-css-bundling.test.js | 10 +- packages/astro/test/astro-doctype.test.js | 6 +- packages/astro/test/astro-dynamic.test.js | 3 +- packages/astro/test/astro-expr.test.js | 12 +- packages/astro/test/astro-fallback.test.js | 3 +- packages/astro/test/astro-global.test.js | 6 +- packages/astro/test/astro-markdown.test.js | 4 +- packages/astro/test/react-component.test.js | 6 +- scripts/cmd/build.js | 5 +- tools/astro-languageserver/bin/server.js | 2 +- tools/astro-languageserver/src/index.ts | 2 +- .../features/CompletionsProvider.ts | 13 +- .../src/plugins/typescript/languageService.ts | 2 +- .../src/plugins/typescript/module-loader.ts | 182 ++++++++---------- .../src/plugins/typescript/utils.ts | 22 +-- tools/astro-vscode/contributing.md | 2 +- tools/astro-vscode/src/index.ts | 23 ++- yarn.lock | 4 +- 28 files changed, 196 insertions(+), 224 deletions(-) delete mode 100644 .github/workflows/changeset.yml diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index a4bb5d2db..fb3c480c8 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -9,31 +9,29 @@ on: - 'examples/**' - 'www/**' branches: - - main - + - main jobs: release: name: Changelog runs-on: ubuntu-latest steps: - - name: Checkout Repo - uses: actions/checkout@master + - name: Check out branch + uses: actions/checkout@v2 with: - # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits - fetch-depth: 0 + fetch-depth: 0 # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits - - name: Setup Node.js 14.x - uses: actions/setup-node@master + - name: Set up Node.js 14.x + uses: actions/setup-node@v2 with: node-version: 14.x - - name: Install Dependencies - run: yarn --frozen-lockfile + - name: Install dependencies + run: yarn --frozen-lockfile --ignore-engines env: CI: true - - name: Create Release Pull Request + - name: Create release PR uses: changesets/action@master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/changeset.yml b/.github/workflows/changeset.yml deleted file mode 100644 index 43ae0e8c8..000000000 --- a/.github/workflows/changeset.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Changeset - -on: - pull_request: - branches: - - main - -jobs: - release: - name: Ensure changeset - runs-on: ubuntu-latest - steps: - - name: Checkout Repo - uses: actions/checkout@master - - - name: Setup Node.js 14.x - uses: actions/setup-node@master - with: - node-version: 14.x - - - name: Install Dependencies - run: yarn --frozen-lockfile - env: - CI: true - - - run: yarn changeset status --since=main diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index 6a35a8d58..f7b5cf21a 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -15,10 +15,10 @@ jobs: - uses: actions/checkout@v2 with: ref: ${{ github.head_ref }} - - uses: actions/setup-node@v1 + - uses: actions/setup-node@v2 with: node-version: ${{ env.node_version }} - - run: yarn --frozen-lockfile + - run: yarn --frozen-lockfile --ignore-engines env: CI: true - run: yarn format diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index a16e9e9e2..7d6b31cf2 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -9,7 +9,7 @@ on: - main jobs: - skip_test: + skip_run: continue-on-error: true runs-on: ubuntu-latest outputs: @@ -23,21 +23,46 @@ jobs: skip_after_successful_duplicate: 'true' paths_ignore: '["**/README.md", "**/docs/**"]' do_not_skip: '["pull_request", "workflow_dispatch", "schedule"]' + changeset: + needs: skip_run # allow skip_run to cancel this job if it’s not needed + if: ${{ needs.skip_run.outputs.should_skip != 'true' }} + name: Ensure changeset + runs-on: ubuntu-latest + steps: + - name: Check out PR branch + uses: actions/checkout@v2 + + - name: Check out main branch + uses: actions/checkout@v2 + with: + ref: main + + - name: Set up Node.js 14.x + uses: actions/setup-node@v2 + with: + node-version: 14.x + + - name: Install dependencies + run: yarn --frozen-lockfile --ignore-engines + env: + CI: true + + - run: yarn changeset status --since=main test: - needs: skip_test # allow skip_test to cancel this job if it’s not needed - if: ${{ needs.skip_test.outputs.should_skip != 'true' }} + needs: skip_run # allow skip_run to cancel this job if it’s not needed + if: ${{ needs.skip_run.outputs.should_skip != 'true' }} runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest] - node-version: [14.x, 15.x] + node-version: [14.x, 16.x] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v1 + uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} - - run: yarn --frozen-lockfile + - run: yarn --frozen-lockfile --ignore-engines env: CI: true - run: yarn build diff --git a/package.json b/package.json index 9ad0ee961..889d9791e 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,9 @@ "npm": "7.11.2", "yarn": "1.22.10" }, + "dependencies": { + "@changesets/cli": "^2.16.0" + }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^4.22.0", "@typescript-eslint/parser": "^4.18.0", @@ -46,8 +49,5 @@ "tiny-glob": "^0.2.8", "typescript": "^4.2.4", "uvu": "^0.5.1" - }, - "dependencies": { - "@changesets/cli": "^2.16.0" } } diff --git a/packages/astro-prism/CHANGELOG.md b/packages/astro-prism/CHANGELOG.md index 4172efab3..0b0ba60b9 100644 --- a/packages/astro-prism/CHANGELOG.md +++ b/packages/astro-prism/CHANGELOG.md @@ -1,6 +1,7 @@ # astro-prism ## 0.0.2 + ### Patch Changes - d924fcb: Fix issue with Prism component missing dependency diff --git a/packages/astro/src/compiler/codegen/content.ts b/packages/astro/src/compiler/codegen/content.ts index 4c542671b..1b630c912 100644 --- a/packages/astro/src/compiler/codegen/content.ts +++ b/packages/astro/src/compiler/codegen/content.ts @@ -42,14 +42,11 @@ function globSearch(spec: string, { filename }: { filename: string }): string[] } const cwd = path.join(path.dirname(filename), globDir.replace(/\//g, path.sep)); // this must match OS (could be '/' or '\') - let found = crawler - .glob(glob) - .crawlWithOptions(cwd, { includeBasePath: true }) - .sync() as PathsOutput; + let found = crawler.glob(glob).crawlWithOptions(cwd, { includeBasePath: true }).sync() as PathsOutput; if (!found.length) { throw new Error(`No files matched "${spec}" from ${filename}`); } - return found.map(importPath => { + return found.map((importPath) => { if (importPath.startsWith('http') || importPath.startsWith('.')) return importPath; return './' + path.posix.join(globDir, path.posix.relative(slash(cwd), importPath)); }); diff --git a/packages/astro/test/astro-basic.test.js b/packages/astro/test/astro-basic.test.js index 89dcf3553..ce9f1cded 100644 --- a/packages/astro/test/astro-basic.test.js +++ b/packages/astro/test/astro-basic.test.js @@ -9,8 +9,8 @@ setup(Basics, './fixtures/astro-basic'); Basics('Can load page', async ({ runtime }) => { const result = await runtime.load('/'); + if (result.error) throw new Error(result.error); - assert.equal(result.statusCode, 200); const $ = doc(result.contents); assert.equal($('h1').text(), 'Hello world!'); diff --git a/packages/astro/test/astro-children.test.js b/packages/astro/test/astro-children.test.js index 368cfc9f9..f44e1f377 100644 --- a/packages/astro/test/astro-children.test.js +++ b/packages/astro/test/astro-children.test.js @@ -10,8 +10,8 @@ setupBuild(ComponentChildren, './fixtures/astro-children'); ComponentChildren('Passes string children to framework components', async ({ runtime }) => { let result = await runtime.load('/strings'); + if (result.error) throw new Error(result.error); - assert.equal(result.statusCode, 200); const $ = doc(result.contents); const $preact = $('#preact'); @@ -26,8 +26,8 @@ ComponentChildren('Passes string children to framework components', async ({ run ComponentChildren('Passes markup children to framework components', async ({ runtime }) => { let result = await runtime.load('/markup'); + if (result.error) throw new Error(result.error); - assert.equal(result.statusCode, 200); const $ = doc(result.contents); const $preact = $('#preact > h1'); @@ -42,8 +42,8 @@ ComponentChildren('Passes markup children to framework components', async ({ run ComponentChildren('Passes multiple children to framework components', async ({ runtime }) => { let result = await runtime.load('/multiple'); + if (result.error) throw new Error(result.error); - assert.equal(result.statusCode, 200); const $ = doc(result.contents); const $preact = $('#preact'); diff --git a/packages/astro/test/astro-collection.test.js b/packages/astro/test/astro-collection.test.js index 72d4f2314..e424d3871 100644 --- a/packages/astro/test/astro-collection.test.js +++ b/packages/astro/test/astro-collection.test.js @@ -9,6 +9,7 @@ setup(Collections, './fixtures/astro-collection'); Collections('generates list & sorts successfully', async ({ runtime }) => { const result = await runtime.load('/posts'); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); const urls = [ ...$('#posts a').map(function () { @@ -20,6 +21,7 @@ Collections('generates list & sorts successfully', async ({ runtime }) => { Collections('generates pagination successfully', async ({ runtime }) => { const result = await runtime.load('/posts'); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); const prev = $('#prev-page'); const next = $('#next-page'); diff --git a/packages/astro/test/astro-css-bundling.test.js b/packages/astro/test/astro-css-bundling.test.js index fe8d82c98..7b00c233c 100644 --- a/packages/astro/test/astro-css-bundling.test.js +++ b/packages/astro/test/astro-css-bundling.test.js @@ -10,9 +10,9 @@ setupBuild(CSSBundling, './fixtures/astro-css-bundling'); // note: the hashes should be deterministic, but updating the file contents will change hashes // be careful not to test that the HTML simply contains CSS, because it always will! filename and quanity matter here (bundling). const EXPECTED_CSS = { - '/index.html': ['/_astro/common-ZVuUT3.css', '/_astro/index-Z2jH7pc.css'], - '/one/index.html': ['/_astro/common-ZVuUT3.css', '/_astro/one/index-2qFtfN.css'], - '/two/index.html': ['/_astro/common-ZVuUT3.css', '/_astro/two/index-2jKE68.css'], + '/index.html': ['/_astro/common-', '/_astro/index-'], // don’t match hashes, which change based on content + '/one/index.html': ['/_astro/common-', '/_astro/one/index-'], + '/two/index.html': ['/_astro/common-', '/_astro/two/index-'], }; const UNEXPECTED_CSS = ['/_astro/components/nav.css', '../css/typography.css', '../css/colors.css', '../css/page-index.css', '../css/page-one.css', '../css/page-two.css']; @@ -28,9 +28,9 @@ CSSBundling('Bundles CSS', async (context) => { // test 1: assert new bundled CSS is present for (const href of css) { - builtCSS.add(href); - const link = $(`link[href="${href}"]`); + const link = $(`link[href^="${href}"]`); assert.equal(link.length, 1); + builtCSS.add(link.attr('href')); } // test 2: assert old CSS was removed diff --git a/packages/astro/test/astro-doctype.test.js b/packages/astro/test/astro-doctype.test.js index c1b94908b..d0d0db105 100644 --- a/packages/astro/test/astro-doctype.test.js +++ b/packages/astro/test/astro-doctype.test.js @@ -34,8 +34,7 @@ DType('No errors creating a runtime', () => { DType('Automatically prepends the standards mode doctype', async () => { const result = await runtime.load('/prepend'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const html = result.contents.toString('utf-8'); assert.ok(html.startsWith(''), 'Doctype always included'); @@ -43,8 +42,7 @@ DType('Automatically prepends the standards mode doctype', async () => { DType.skip('Preserves user provided doctype', async () => { const result = await runtime.load('/preserve'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const html = result.contents.toString('utf-8'); assert.ok(html.startsWith(''), 'Doctype included was preserved'); diff --git a/packages/astro/test/astro-dynamic.test.js b/packages/astro/test/astro-dynamic.test.js index 0bf25df8a..8ef6895f6 100644 --- a/packages/astro/test/astro-dynamic.test.js +++ b/packages/astro/test/astro-dynamic.test.js @@ -9,8 +9,7 @@ setupBuild(DynamicComponents, './fixtures/astro-dynamic'); DynamicComponents('Loads client-only packages', async ({ runtime }) => { let result = await runtime.load('/'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); // Grab the react-dom import const exp = /import\("(.+?)"\)/g; diff --git a/packages/astro/test/astro-expr.test.js b/packages/astro/test/astro-expr.test.js index c3c985712..c424c3863 100644 --- a/packages/astro/test/astro-expr.test.js +++ b/packages/astro/test/astro-expr.test.js @@ -9,8 +9,7 @@ setup(Expressions, './fixtures/astro-expr'); Expressions('Can load page', async ({ runtime }) => { const result = await runtime.load('/'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); @@ -21,8 +20,7 @@ Expressions('Can load page', async ({ runtime }) => { Expressions('Ignores characters inside of strings', async ({ runtime }) => { const result = await runtime.load('/strings'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); @@ -33,7 +31,7 @@ Expressions('Ignores characters inside of strings', async ({ runtime }) => { Expressions('Ignores characters inside of line comments', async ({ runtime }) => { const result = await runtime.load('/line-comments'); - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); @@ -44,7 +42,7 @@ Expressions('Ignores characters inside of line comments', async ({ runtime }) => Expressions('Ignores characters inside of multiline comments', async ({ runtime }) => { const result = await runtime.load('/multiline-comments'); - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); @@ -55,7 +53,7 @@ Expressions('Ignores characters inside of multiline comments', async ({ runtime Expressions('Allows multiple JSX children in mustache', async ({ runtime }) => { const result = await runtime.load('/multiple-children'); - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); assert.ok(result.contents.includes('#f') && !result.contents.includes('#t')); }); diff --git a/packages/astro/test/astro-fallback.test.js b/packages/astro/test/astro-fallback.test.js index 2acf29f8e..a4edec371 100644 --- a/packages/astro/test/astro-fallback.test.js +++ b/packages/astro/test/astro-fallback.test.js @@ -9,8 +9,7 @@ setup(Fallback, './fixtures/astro-fallback'); Fallback('Shows static content', async (context) => { const result = await context.runtime.load('/'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.equal($('#fallback').text(), 'static'); diff --git a/packages/astro/test/astro-global.test.js b/packages/astro/test/astro-global.test.js index 891e1cfb2..5ea5c46f9 100644 --- a/packages/astro/test/astro-global.test.js +++ b/packages/astro/test/astro-global.test.js @@ -9,8 +9,7 @@ setup(Global, './fixtures/astro-global'); Global('Astro.request.url', async (context) => { const result = await context.runtime.load('/'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.equal($('#pathname').text(), '/'); @@ -35,8 +34,7 @@ Global('Astro.request.canonicalURL', async (context) => { Global('Astro.site', async (context) => { const result = await context.runtime.load('/'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.equal($('#site').attr('href'), 'https://mysite.dev'); diff --git a/packages/astro/test/astro-markdown.test.js b/packages/astro/test/astro-markdown.test.js index ba0197e5f..8c467bf9d 100644 --- a/packages/astro/test/astro-markdown.test.js +++ b/packages/astro/test/astro-markdown.test.js @@ -43,8 +43,7 @@ Markdown('No errors creating a runtime', () => { Markdown('Can load markdown pages with hmx', async () => { const result = await runtime.load('/post'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.ok($('#first').length, 'There is a div added in markdown'); @@ -53,6 +52,7 @@ Markdown('Can load markdown pages with hmx', async () => { Markdown('Can load more complex jsxy stuff', async () => { const result = await runtime.load('/complex'); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); const $el = $('#test'); diff --git a/packages/astro/test/react-component.test.js b/packages/astro/test/react-component.test.js index d7442bc98..10b44120c 100644 --- a/packages/astro/test/react-component.test.js +++ b/packages/astro/test/react-component.test.js @@ -35,8 +35,7 @@ React('No error creating the runtime', () => { React('Can load React', async () => { const result = await runtime.load('/'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.equal($('#react-h2').text(), 'Hello world!'); @@ -44,8 +43,7 @@ React('Can load React', async () => { React('Can load Vue', async () => { const result = await runtime.load('/'); - - assert.equal(result.statusCode, 200); + if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.equal($('#vue-h2').text(), 'Hasta la vista, baby'); diff --git a/scripts/cmd/build.js b/scripts/cmd/build.js index 250bb1efd..b46c8e61c 100644 --- a/scripts/cmd/build.js +++ b/scripts/cmd/build.js @@ -20,7 +20,10 @@ const defaultConfig = { export default async function build(...args) { const config = Object.assign({}, defaultConfig); const isDev = args.slice(-1)[0] === 'IS_DEV'; - let entryPoints = [].concat(...(await Promise.all(args.map((pattern) => glob(pattern, { filesOnly: true, absolute: true }))))); + const patterns = args + .filter((f) => !!f) // remove empty args + .map((f) => f.replace(/^'/, '').replace(/'$/, '')); // Needed for Windows: glob strings contain surrounding string chars??? remove these + let entryPoints = [].concat(...(await Promise.all(patterns.map((pattern) => glob(pattern, { filesOnly: true, absolute: true }))))); const { type = 'module', dependencies = {} } = await fs.readFile('./package.json').then((res) => JSON.parse(res.toString())); const format = type === 'module' ? 'esm' : 'cjs'; diff --git a/tools/astro-languageserver/bin/server.js b/tools/astro-languageserver/bin/server.js index 1967fff94..7d3814ebc 100644 --- a/tools/astro-languageserver/bin/server.js +++ b/tools/astro-languageserver/bin/server.js @@ -3,4 +3,4 @@ // eslint-disable-next-line @typescript-eslint/no-var-requires const { startServer } = require('../dist/index'); -startServer(); \ No newline at end of file +startServer(); diff --git a/tools/astro-languageserver/src/index.ts b/tools/astro-languageserver/src/index.ts index 41f04d11a..bc25f9475 100644 --- a/tools/astro-languageserver/src/index.ts +++ b/tools/astro-languageserver/src/index.ts @@ -71,7 +71,7 @@ export function startServer() { connection.onDidCloseTextDocument((evt) => docManager.closeDocument(evt.textDocument.uri)); connection.onDidChangeTextDocument((evt) => { - docManager.updateDocument(evt.textDocument.uri, evt.contentChanges) + docManager.updateDocument(evt.textDocument.uri, evt.contentChanges); }); connection.onDidChangeWatchedFiles((evt) => { diff --git a/tools/astro-languageserver/src/plugins/typescript/features/CompletionsProvider.ts b/tools/astro-languageserver/src/plugins/typescript/features/CompletionsProvider.ts index e56902e6e..cb4826af2 100644 --- a/tools/astro-languageserver/src/plugins/typescript/features/CompletionsProvider.ts +++ b/tools/astro-languageserver/src/plugins/typescript/features/CompletionsProvider.ts @@ -26,11 +26,12 @@ export class CompletionsProviderImpl implements CompletionsProvider this.toCompletionItem(fragment, entry, document.uri, position, new Set())) @@ -49,7 +50,7 @@ export class CompletionsProviderImpl implements CompletionsProvider(); + private cache = new Map(); - /** - * Tries to get a cached module. - */ - get(moduleName: string, containingFile: string): ts.ResolvedModule | undefined { - return this.cache.get(this.getKey(moduleName, containingFile)); - } + /** + * Tries to get a cached module. + */ + get(moduleName: string, containingFile: string): ts.ResolvedModule | undefined { + return this.cache.get(this.getKey(moduleName, containingFile)); + } - /** - * Caches resolved module, if it is not undefined. - */ - set(moduleName: string, containingFile: string, resolvedModule: ts.ResolvedModule | undefined) { - if (!resolvedModule) { - return; - } - this.cache.set(this.getKey(moduleName, containingFile), resolvedModule); + /** + * Caches resolved module, if it is not undefined. + */ + set(moduleName: string, containingFile: string, resolvedModule: ts.ResolvedModule | undefined) { + if (!resolvedModule) { + return; } + this.cache.set(this.getKey(moduleName, containingFile), resolvedModule); + } - /** - * Deletes module from cache. Call this if a file was deleted. - * @param resolvedModuleName full path of the module - */ - delete(resolvedModuleName: string): void { - this.cache.forEach((val, key) => { - if (val.resolvedFileName === resolvedModuleName) { - this.cache.delete(key); - } - }); - } + /** + * Deletes module from cache. Call this if a file was deleted. + * @param resolvedModuleName full path of the module + */ + delete(resolvedModuleName: string): void { + this.cache.forEach((val, key) => { + if (val.resolvedFileName === resolvedModuleName) { + this.cache.delete(key); + } + }); + } - private getKey(moduleName: string, containingFile: string) { - return containingFile + ':::' + ensureRealAstroFilePath(moduleName); - } + private getKey(moduleName: string, containingFile: string) { + return containingFile + ':::' + ensureRealAstroFilePath(moduleName); + } } /** @@ -59,74 +55,56 @@ class ModuleResolutionCache { * @param getSnapshot A function which returns a (in case of astro file fully preprocessed) typescript/javascript snapshot * @param compilerOptions The typescript compiler options */ -export function createAstroModuleLoader( - getSnapshot: (fileName: string) => DocumentSnapshot, - compilerOptions: ts.CompilerOptions -) { - const astroSys = createAstroSys(getSnapshot); - const moduleCache = new ModuleResolutionCache(); +export function createAstroModuleLoader(getSnapshot: (fileName: string) => DocumentSnapshot, compilerOptions: ts.CompilerOptions) { + const astroSys = createAstroSys(getSnapshot); + const moduleCache = new ModuleResolutionCache(); - return { - fileExists: astroSys.fileExists, - readFile: astroSys.readFile, - writeFile: astroSys.writeFile, - readDirectory: astroSys.readDirectory, - directoryExists: astroSys.directoryExists, - getDirectories: astroSys.getDirectories, - realpath: astroSys.realpath, - deleteFromModuleCache: (path: string) => moduleCache.delete(path), - resolveModuleNames + return { + fileExists: astroSys.fileExists, + readFile: astroSys.readFile, + writeFile: astroSys.writeFile, + readDirectory: astroSys.readDirectory, + directoryExists: astroSys.directoryExists, + getDirectories: astroSys.getDirectories, + realpath: astroSys.realpath, + deleteFromModuleCache: (path: string) => moduleCache.delete(path), + resolveModuleNames, + }; + + function resolveModuleNames(moduleNames: string[], containingFile: string): Array { + return moduleNames.map((moduleName) => { + const cachedModule = moduleCache.get(moduleName, containingFile); + if (cachedModule) { + return cachedModule; + } + + const resolvedModule = resolveModuleName(moduleName, containingFile); + moduleCache.set(moduleName, containingFile, resolvedModule); + return resolvedModule; + }); + } + + function resolveModuleName(name: string, containingFile: string): ts.ResolvedModule | undefined { + // Delegate to the TS resolver first. + // If that does not bring up anything, try the Astro Module loader + // which is able to deal with .astro files. + const tsResolvedModule = ts.resolveModuleName(name, containingFile, compilerOptions, ts.sys).resolvedModule; + if (tsResolvedModule && !isVirtualAstroFilePath(tsResolvedModule.resolvedFileName)) { + return tsResolvedModule; + } + + const astroResolvedModule = ts.resolveModuleName(name, containingFile, compilerOptions, astroSys).resolvedModule; + if (!astroResolvedModule || !isVirtualAstroFilePath(astroResolvedModule.resolvedFileName)) { + return astroResolvedModule; + } + + const resolvedFileName = ensureRealAstroFilePath(astroResolvedModule.resolvedFileName); + const snapshot = getSnapshot(resolvedFileName); + + const resolvedastroModule: ts.ResolvedModuleFull = { + extension: getExtensionFromScriptKind(snapshot && snapshot.scriptKind), + resolvedFileName, }; - - function resolveModuleNames( - moduleNames: string[], - containingFile: string - ): Array { - return moduleNames.map((moduleName) => { - const cachedModule = moduleCache.get(moduleName, containingFile); - if (cachedModule) { - return cachedModule; - } - - const resolvedModule = resolveModuleName(moduleName, containingFile); - moduleCache.set(moduleName, containingFile, resolvedModule); - return resolvedModule; - }); - } - - function resolveModuleName( - name: string, - containingFile: string - ): ts.ResolvedModule | undefined { - // Delegate to the TS resolver first. - // If that does not bring up anything, try the Astro Module loader - // which is able to deal with .astro files. - const tsResolvedModule = ts.resolveModuleName(name, containingFile, compilerOptions, ts.sys) - .resolvedModule; - if (tsResolvedModule && !isVirtualAstroFilePath(tsResolvedModule.resolvedFileName)) { - return tsResolvedModule; - } - - const astroResolvedModule = ts.resolveModuleName( - name, - containingFile, - compilerOptions, - astroSys - ).resolvedModule; - if ( - !astroResolvedModule || - !isVirtualAstroFilePath(astroResolvedModule.resolvedFileName) - ) { - return astroResolvedModule; - } - - const resolvedFileName = ensureRealAstroFilePath(astroResolvedModule.resolvedFileName); - const snapshot = getSnapshot(resolvedFileName); - - const resolvedastroModule: ts.ResolvedModuleFull = { - extension: getExtensionFromScriptKind(snapshot && snapshot.scriptKind), - resolvedFileName - }; - return resolvedastroModule; - } + return resolvedastroModule; + } } diff --git a/tools/astro-languageserver/src/plugins/typescript/utils.ts b/tools/astro-languageserver/src/plugins/typescript/utils.ts index 3c43e56d5..da4e37c84 100644 --- a/tools/astro-languageserver/src/plugins/typescript/utils.ts +++ b/tools/astro-languageserver/src/plugins/typescript/utils.ts @@ -113,17 +113,17 @@ export function getScriptKindFromFileName(fileName: string): ts.ScriptKind { export function getExtensionFromScriptKind(kind: ts.ScriptKind | undefined): ts.Extension { switch (kind) { - case ts.ScriptKind.JSX: - return ts.Extension.Jsx; - case ts.ScriptKind.TS: - return ts.Extension.Ts; - case ts.ScriptKind.TSX: - return ts.Extension.Tsx; - case ts.ScriptKind.JSON: - return ts.Extension.Json; - case ts.ScriptKind.JS: - default: - return ts.Extension.Js; + case ts.ScriptKind.JSX: + return ts.Extension.Jsx; + case ts.ScriptKind.TS: + return ts.Extension.Ts; + case ts.ScriptKind.TSX: + return ts.Extension.Tsx; + case ts.ScriptKind.JSON: + return ts.Extension.Json; + case ts.ScriptKind.JS: + default: + return ts.Extension.Js; } } diff --git a/tools/astro-vscode/contributing.md b/tools/astro-vscode/contributing.md index d9f1bd59e..9617233ff 100644 --- a/tools/astro-vscode/contributing.md +++ b/tools/astro-vscode/contributing.md @@ -15,6 +15,6 @@ To start the development server run: yarn dev:vscode ``` -Then in the __Debug__ panel select __Launch Extension__ from the dropdown and click the run button. +Then in the **Debug** panel select **Launch Extension** from the dropdown and click the run button. Screen Shot 2021-05-07 at 8 51 37 AM diff --git a/tools/astro-vscode/src/index.ts b/tools/astro-vscode/src/index.ts index d48f2723c..86c3d0783 100644 --- a/tools/astro-vscode/src/index.ts +++ b/tools/astro-vscode/src/index.ts @@ -53,16 +53,19 @@ function createLanguageService(context: vscode.ExtensionContext, mode: 'doc', id context.subscriptions.push(client.start()); - client.onReady().then(() => { - const tagRequestor = (document: vscode.TextDocument, position: vscode.Position) => { - const param = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position); - return client.sendRequest(TagCloseRequest, param); - }; - const disposable = activateTagClosing(tagRequestor, { astro: true }, 'html.autoClosingTags'); - context.subscriptions.push(disposable); - }).catch(err => { - console.error('Astro, unable to load language server.', err); - }); + client + .onReady() + .then(() => { + const tagRequestor = (document: vscode.TextDocument, position: vscode.Position) => { + const param = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position); + return client.sendRequest(TagCloseRequest, param); + }; + const disposable = activateTagClosing(tagRequestor, { astro: true }, 'html.autoClosingTags'); + context.subscriptions.push(disposable); + }) + .catch((err) => { + console.error('Astro, unable to load language server.', err); + }); return client; } diff --git a/yarn.lock b/yarn.lock index 96abd37a8..698023d28 100644 --- a/yarn.lock +++ b/yarn.lock @@ -300,7 +300,7 @@ "@changesets/cli@^2.16.0": version "2.16.0" - resolved "https://registry.npmjs.org/@changesets/cli/-/cli-2.16.0.tgz" + resolved "https://registry.yarnpkg.com/@changesets/cli/-/cli-2.16.0.tgz#9f794005d0503efba5e348b929821a1732fd0f0d" integrity sha512-VFkXSyyk/WRjjUoBI7g7cDy09qBjPbBQOloPMEshTzMo/NY9muWHl2yB/FSSkV/6PxGimPtJ7aEJPYfk8HCfXw== dependencies: "@babel/runtime" "^7.10.4" @@ -11402,7 +11402,7 @@ typedarray@^0.0.6: typescript@^4.2.4: version "4.2.4" - resolved "https://registry.npmjs.org/typescript/-/typescript-4.2.4.tgz" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.2.4.tgz#8610b59747de028fda898a8aef0e103f156d0961" integrity sha512-V+evlYHZnQkaz8TRBuxTA92yZBPotr5H+WhQ7bD3hZUndx5tGOa1fuCgeSjxAzM1RiN5IzvadIXTVefuuwZCRg== ua-parser-js@^0.7.18: