diff --git a/tsc/internal/packagejson/jsonvalue.go b/tsc/internal/packagejson/jsonvalue.go index ef88e9b07c426..62fc90010c0f5 100644 --- a/tsc/internal/packagejson/jsonvalue.go +++ b/tsc/internal/packagejson/jsonvalue.go @@ -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: diff --git a/tsc/internal/packagejson/jsonvalue_test.go b/tsc/internal/packagejson/jsonvalue_test.go index 81897f868a871..b6c259b4e0489 100644 --- a/tsc/internal/packagejson/jsonvalue_test.go +++ b/tsc/internal/packagejson/jsonvalue_test.go @@ -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"` diff --git a/tsc/internal/tsoptions/parsinghelpers_test.go b/tsc/internal/tsoptions/parsinghelpers_test.go index 87a2483ea988c..75dadb369bc3f 100644 --- a/tsc/internal/tsoptions/parsinghelpers_test.go +++ b/tsc/internal/tsoptions/parsinghelpers_test.go @@ -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() diff --git a/tsc/internal/tsoptions/tsconfigparsing.go b/tsc/internal/tsoptions/tsconfigparsing.go index 2b393fd79fab5..92ba6b48d09ad 100644 --- a/tsc/internal/tsoptions/tsconfigparsing.go +++ b/tsc/internal/tsoptions/tsconfigparsing.go @@ -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 @@ -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...) } } @@ -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) diff --git a/tsc/internal/tsoptions/tsconfigparsing_test.go b/tsc/internal/tsoptions/tsconfigparsing_test.go index 7d729db7aed6e..5c66aa449b4be 100644 --- a/tsc/internal/tsoptions/tsconfigparsing_test.go +++ b/tsc/internal/tsoptions/tsconfigparsing_test.go @@ -6,6 +6,7 @@ import ( "maps" "path/filepath" "slices" + "strconv" "strings" "sync/atomic" "testing" @@ -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( @@ -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))