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 tsc/internal/packagejson/jsonvalue.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (v *JSONValue) IsFalsy() bool {
case JSONValueTypeString:
return v.Value == ""
case JSONValueTypeNumber:
return v.Value == 0
return v.Value == float64(0)
case JSONValueTypeBoolean:
return !v.Value.(bool)
default:
Expand Down
28 changes: 28 additions & 0 deletions tsc/internal/packagejson/jsonvalue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,34 @@ func TestJSONValue(t *testing.T) {
})
}

func TestJSONValueIsFalsy(t *testing.T) {
t.Parallel()

for _, test := range []struct {
text string
falsy bool
}{
{"0", true},
{"-0", true},
{"0.0", true},
{"1", false},
{"-0.5", false},
{"null", true},
{"false", true},
{`""`, true},
{`"0"`, false},
{"[]", false},
{"{}", false},
} {
t.Run(test.text, func(t *testing.T) {
t.Parallel()
var value packagejson.JSONValue
assert.NilError(t, json.Unmarshal([]byte(test.text), &value))
assert.Equal(t, value.IsFalsy(), test.falsy)
})
}
}

func testJSONValue(t *testing.T, unmarshal func([]byte, any) error) {
type packageJson struct {
Private packagejson.JSONValue `json:"private"`
Expand Down
53 changes: 53 additions & 0 deletions tsc/internal/tsoptions/parsinghelpers_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,67 @@
package tsoptions

import (
"fmt"
"math"
"reflect"
"strings"
"testing"

"github.com/microsoft/TypeScript/tsc/internal/collections"
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/diagnostics"
"github.com/microsoft/TypeScript/tsc/internal/tspath"
"github.com/microsoft/TypeScript/tsc/internal/vfs/vfstest"
"gotest.tools/v3/assert"
)

func TestConvertJsonOptionNumericList(t *testing.T) { //nolint:paralleltest // Modifies the element declaration map.
const name = "testNumericList"
commandLineOptionElements[name] = &CommandLineOption{Name: name, Kind: CommandLineOptionTypeNumber}
t.Cleanup(func() { delete(commandLineOptionElements, name) })

for _, preserve := range []bool{false, true} {
option := &CommandLineOption{Name: name, Kind: CommandLineOptionTypeList, listPreserveFalsyValues: preserve}
values := []any{float64(0), float64(1), float64(-1), math.Copysign(0, -1), nil}
got, errors := convertJsonOptionOfListType(option, values, "/project", nil, nil, nil)
assert.Equal(t, len(errors), 0)
expected := []any{float64(1), float64(-1)}
if preserve {
expected = values
}
assert.DeepEqual(t, got, expected)
}
}

func TestParseConfigCircularityPreservesRaw(t *testing.T) {
t.Parallel()
const fileName tspath.RootedFilePath = "/project/tsconfig.json"
const path tspath.PathKey = "/project/tsconfig.json"
fs := vfstest.FromMap(map[string]string{}, tspath.CaseSensitive)
for _, text := range []string{`{}`, `{"customSetting":true,"files":["index.ts"]}`} {
for _, fromSource := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/source=%v", text, fromSource), func(t *testing.T) {
t.Parallel()
value, errors := ParseConfigFileTextToJson(fileName, path, text)
assert.Equal(t, len(errors), 0)
raw := value.(*collections.OrderedMap[string, any])
var source *TsConfigSourceFile
input := raw
if fromSource {
input = nil
source = NewTsconfigSourceFileFromFilePath(fileName, path, text)
}
got, errors := parseConfig(input, source, fs, "/project", fileName, []tspath.PathKey{path}, nil)
assert.Equal(t, len(errors), 1)
assert.Equal(t, errors[0].Code(), diagnostics.Circularity_detected_while_resolving_configuration_Colon_0.Code())
assert.DeepEqual(t, errors[0].MessageArgs(), []string{"/project/tsconfig.json -> /project/tsconfig.json"})
assert.Assert(t, got.raw != nil)
assert.Assert(t, reflect.DeepEqual(got.raw, raw))
})
}
}
}

func TestMergeCompilerOptions(t *testing.T) {
t.Parallel()

Expand Down
8 changes: 4 additions & 4 deletions tsc/internal/tsoptions/tsconfigparsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ func convertJsonOptionOfListType(
filteredValues := mappedValues
if !option.listPreserveFalsyValues {
filteredValues = core.Filter(mappedValues, func(v any) bool {
return (v != nil && v != false && v != 0 && v != "")
return (v != nil && v != false && v != float64(0) && v != "")
})
}
return filteredValues, errors
Expand Down Expand Up @@ -467,14 +467,14 @@ func getExtendsConfigPathOrArray(
if valueExpression != nil {
expression = valueExpression.Elements()[index]
}
if reflect.TypeOf(fileName).Kind() == reflect.String {
if isStringValue(fileName) {
val, err := getExtendsConfigPath(fileName.(string), fs, newBase, expression, sourceFile)
if val != "" {
extendedConfigPathArray = append(extendedConfigPathArray, val)
}
errors = append(errors, err...)
} else {
_, err := convertJsonOption(extendsOptionDeclaration.Elements(), value, basePath, propertyAssignment, expression, sourceFile)
_, err := convertJsonOption(extendsOptionDeclaration.Elements(), fileName, basePath, propertyAssignment, expression, sourceFile)
errors = append(errors, err...)
}
}
Expand Down Expand Up @@ -1019,7 +1019,7 @@ func parseConfig(
if slices.Contains(resolutionStack, resolvedPath) {
var result *parsedTsconfig
errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, strings.Join(append(core.Map(resolutionStack[slices.Index(resolutionStack, resolvedPath):], tspath.PathKey.AsString), resolvedPath.AsString()), " -> ")))
if json.Size() == 0 {
if json != nil {
result = &parsedTsconfig{raw: json}
} else {
rawResult, err := convertToObject(sourceFile.SourceFile)
Expand Down
38 changes: 37 additions & 1 deletion tsc/internal/tsoptions/tsconfigparsing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"maps"
"path/filepath"
"slices"
"strconv"
"strings"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -965,7 +966,7 @@ func TestParseJsonConfigFileContentHandlesNullArrayElements(t *testing.T) {
fs := tsoptionstest.NewVFS(map[string]string{
"/project/index.ts": "export {};",
}, tspath.CaseSensitive /*caseSensitivity*/)
for _, property := range []string{"files", "include", "exclude"} {
for _, property := range []string{"files", "include", "exclude", "extends"} {
t.Run(property, func(t *testing.T) {
t.Parallel()
parsed := tsoptions.ParseJsonConfigFileContent(
Expand Down Expand Up @@ -1002,6 +1003,41 @@ func TestParseJsonConfigFileContentDefaultsCompileOnSaveToFalse(t *testing.T) {
assert.Equal(t, *parsed.CompileOnSave, false)
}

func TestParseConfigExtendsInvalidArrayElements(t *testing.T) {
t.Parallel()
const text = `{"extends":["./base.json",42,false,{},["./base.json"]],"files":["index.ts"]}`
fs := tsoptionstest.NewVFS(map[string]string{
"/project/base.json": `{"compilerOptions":{"strict":true}}`,
"/project/index.ts": "export {};",
}, tspath.CaseSensitive)
for _, fromSource := range []bool{false, true} {
t.Run(strconv.FormatBool(fromSource), func(t *testing.T) {
t.Parallel()
config := testConfig{
jsonText: text,
configFileName: "/project/tsconfig.json",
}
var parsed *tsoptions.ParsedCommandLine
if fromSource {
parsed = getParsedWithJsonSourceFileApi(config, fs, "/project")
} else {
parsed = getParsedWithJsonApi(config, fs, "/project")
}
assert.Equal(t, len(parsed.Errors), 4)
for i, diagnostic := range parsed.Errors {
assert.Equal(t, diagnostic.Code(), diagnostics.Compiler_option_0_requires_a_value_of_type_1.Code())
assert.DeepEqual(t, diagnostic.MessageArgs(), []string{"extends", "string"})
if fromSource {
element := []string{"42", "false", "{}", `["./base.json"]`}[i]
assert.Equal(t, diagnostic.Pos(), strings.Index(text, element))
assert.Equal(t, diagnostic.Len(), len(element))
}
}
assert.Assert(t, parsed.CompilerOptions().Strict.IsTrue())
})
}
}

func getParsedWithJsonApi(config testConfig, fs vfs.FS, basePath tspath.RootedDirectoryPath) *tsoptions.ParsedCommandLine {
configFileName := tspath.ToRootedFilePath(config.configFileName, basePath)
path := fs.CaseSensitivity().PathKey(tspath.RootedPath(configFileName))
Expand Down
Loading