Skip to content

Commit

Permalink
fix(typegen): fixes a bug where we imported the wrong relative path (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
sgulseth authored and rexxars committed Apr 26, 2024
1 parent 9af065a commit e1bd1f0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import path from 'node:path'

import {describe, expect, test} from '@jest/globals'

import {findQueriesInSource} from '../findQueriesInSource'
Expand Down Expand Up @@ -81,18 +79,19 @@ describe('findQueries', () => {
const postQuery = groq\`*[_type == "\${foo}"]\`
const res = sanity.fetch(postQueryResult);
`
const queries = findQueriesInSource(source, __filename, undefined)
expect(queries.length).toBe(1)
expect(queries[0].result).toBe('*[_type == "foo"]')
})

const resolver: NodeJS.RequireResolve = (id) => {
if (id === 'foo') {
return path.resolve(__dirname, 'fixtures', 'exportVar')
}
return require.resolve(id)
}
resolver.paths = (request: string): string[] | null => {
return require.resolve.paths(request)
}

const queries = findQueriesInSource(source, 'test.ts', undefined, resolver)
test('should import, subdirectory', () => {
const source = `
import { groq } from "groq";
import {foo} from "../__tests__/fixtures/exportVar";
const postQuery = groq\`*[_type == "\${foo}"]\`
const res = sanity.fetch(postQueryResult);
`
const queries = findQueriesInSource(source, __filename, undefined)
expect(queries.length).toBe(1)
expect(queries[0].result).toBe('*[_type == "foo"]')
})
Expand Down
14 changes: 8 additions & 6 deletions packages/@sanity/codegen/src/typescript/expressionResolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,12 +323,14 @@ function resolveImportSpecifier({
throw new Error(`Could not find import declaration for ${node.local.name}`)
}

const importName = node.local.name
const importFileName = importDeclaration.source.value
// const importPath = path.resolve(path.dirname(filename), importFileName);
const importPath = importName.startsWith('./')
? path.resolve(path.dirname(filename), importFileName)
: importFileName
const importName = node.local.name // the name of the variable to import
const importFileName = importDeclaration.source.value // the file to import from

const importPath =
importFileName.startsWith('./') || importFileName.startsWith('../')
? path.resolve(path.dirname(filename), importFileName)
: importFileName

const resolvedFile = resolver(importPath)
const source = fs.readFileSync(resolvedFile)
const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)
Expand Down

0 comments on commit e1bd1f0

Please sign in to comment.