Skip to content

Commit

Permalink
chore(types): fix some strictNullChecks errors (#3932)
Browse files Browse the repository at this point in the history
This just fixes a few strictNullChecks errors, selected just by running
the TypeScript compiler with the option turned on and fixing a few
errors that popped up.
  • Loading branch information
alicewriteswrongs authored and rwaskiewicz committed Jan 25, 2023
1 parent 0e7a64d commit ee92c95
Show file tree
Hide file tree
Showing 16 changed files with 68 additions and 58 deletions.
7 changes: 5 additions & 2 deletions src/cli/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,17 @@ export const runTask = async (
sys?: d.CompilerSystem
): Promise<void> => {
const logger = config.logger ?? createLogger();
const rootDir = config.rootDir ?? '/';
const configSys = sys ?? config.sys ?? coreCompiler.createSystem({ logger });
const strictConfig: ValidatedConfig = {
...config,
flags: createConfigFlags(config.flags ?? { task }),
hydratedFlag: config.hydratedFlag ?? null,
logger,
outputTargets: config.outputTargets ?? [],
rootDir: config.rootDir ?? '/',
sys: sys ?? config.sys ?? coreCompiler.createSystem({ logger }),
packageJsonFilePath: configSys.platformPath.join(rootDir, 'package.json'),
rootDir,
sys: configSys,
testing: config.testing ?? {},
};

Expand Down
3 changes: 2 additions & 1 deletion src/compiler/build/build-stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@ export function generateBuildStats(
}
} catch (e: unknown) {
const diagnostic: d.Diagnostic = {
messageText: `Generate Build Stats Error: ` + e,
level: `error`,
lines: [],
messageText: `Generate Build Stats Error: ` + e,
type: `build`,
};
jsonData = {
Expand Down
1 change: 1 addition & 0 deletions src/compiler/build/test/build-stats.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ describe('generateBuildStats', () => {
level: 'error',
type: 'horrible',
messageText: 'the worst error _possible_ has just occurred',
lines: [],
};
buildCtx.buildResults.diagnostics = [diagnostic];
const result = generateBuildStats(config, buildCtx);
Expand Down
4 changes: 3 additions & 1 deletion src/compiler/config/test/load-config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,15 @@ describe('load config', () => {
expect<d.Diagnostic>(loadedConfig.diagnostics[0]).toEqual({
absFilePath: '/tsconfig.json',
code: '18003',
columnNumber: undefined,
header: 'TypeScript',
language: 'typescript',
level: 'warn',
lineNumber: undefined,
lines: [],
messageText:
"No inputs were found in config file '/tsconfig.json'. Specified 'include' paths were '[\"src\"]' and 'exclude' paths were '[]'.",
relFilePath: null,
relFilePath: undefined,
type: 'typescript',
});
});
Expand Down
9 changes: 5 additions & 4 deletions src/compiler/config/test/validate-service-worker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ describe('validateServiceWorker', () => {

beforeEach(() => {
config = {
fsNamespace: 'app',
rootDir: '/',
hydratedFlag: null,
sys: mockCompilerSystem(),
devMode: false,
flags: createConfigFlags(),
fsNamespace: 'app',
hydratedFlag: null,
logger: mockLogger(),
outputTargets: [],
packageJsonFilePath: '/package.json',
rootDir: '/',
sys: mockCompilerSystem(),
testing: {},
};
});
Expand Down
5 changes: 4 additions & 1 deletion src/compiler/config/validate-config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { buildError, isBoolean, isNumber, isString, sortBy } from '@utils';
import { join } from 'path';

import { ConfigBundle, Diagnostic, LoadConfigInit, UnvalidatedConfig, ValidatedConfig } from '../../declarations';
import { createLogger } from '../sys/logger/console-logger';
Expand Down Expand Up @@ -47,6 +48,7 @@ export const validateConfig = (
const diagnostics: Diagnostic[] = [];

const logger = bootstrapConfig.logger || config.logger || createLogger();
const rootDir = typeof config.rootDir === 'string' ? config.rootDir : '/';

const validatedConfig: ValidatedConfig = {
...config,
Expand All @@ -55,7 +57,8 @@ export const validateConfig = (
hydratedFlag: validateHydrated(config),
logger,
outputTargets: config.outputTargets ?? [],
rootDir: typeof config.rootDir === 'string' ? config.rootDir : '/',
packageJsonFilePath: join(rootDir, 'package.json'),
rootDir,
sys: config.sys ?? bootstrapConfig.sys ?? createSystem({ logger }),
testing: config.testing ?? {},
};
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/html/remove-unused-styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const removeUnusedStyleText = (
type: 'css',
header: 'CSS Stringify',
messageText: e,
lines: [],
});
}
} catch (e: any) {
Expand All @@ -58,6 +59,7 @@ const removeUnusedStyleText = (
type: 'css',
header: 'CSS Parse',
messageText: e,
lines: [],
});
}
};
2 changes: 2 additions & 0 deletions src/compiler/optimize/autoprefixer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const autoprefixCss = async (cssText: string, opts: boolean | null | d.Au
messageText: warning.text,
level: 'warn',
type: 'css',
lines: [],
});
});

Expand All @@ -48,6 +49,7 @@ export const autoprefixCss = async (cssText: string, opts: boolean | null | d.Au
messageText: `CSS Error` + e,
level: `error`,
type: `css`,
lines: [],
};

if (typeof e.name === 'string') {
Expand Down
1 change: 1 addition & 0 deletions src/compiler/output-targets/dist-custom-elements/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export const bundleCustomElements = async (
level: 'error',
type: 'build',
messageText: 'dist-custom-elements output target provided with no output target directory!',
lines: [],
});
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export * from '${USER_INDEX_ENTRY_ID}';
expect(buildCtx.diagnostics).toEqual([
{
level: 'error',
lines: [],
type: 'build',
messageText: 'dist-custom-elements output target provided with no output target directory!',
},
Expand Down
6 changes: 5 additions & 1 deletion src/compiler/sys/config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { join } from 'path';

import { createConfigFlags } from '../../cli/config-flags';
import type * as d from '../../declarations';
import { setPlatformPath } from '../sys/modules/path';
Expand All @@ -6,13 +8,15 @@ import { createSystem } from './stencil-sys';

export const getConfig = (userConfig: d.Config): d.ValidatedConfig => {
const logger = userConfig.logger ?? createLogger();
const rootDir = userConfig.rootDir ?? '/';
const config: d.ValidatedConfig = {
...userConfig,
flags: createConfigFlags(userConfig.flags ?? {}),
hydratedFlag: userConfig.hydratedFlag ?? null,
logger,
outputTargets: userConfig.outputTargets ?? [],
rootDir: userConfig.rootDir ?? '/',
packageJsonFilePath: join(rootDir, 'package.json'),
rootDir,
sys: userConfig.sys ?? createSystem({ logger }),
testing: userConfig ?? {},
};
Expand Down
36 changes: 19 additions & 17 deletions src/declarations/stencil-public-compiler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ConfigFlags } from '../cli/config-flags';
import type { PrerenderUrlResults } from '../internal';
import type { PrerenderUrlResults, PrintLine } from '../internal';
import type { JsonDocs } from './stencil-public-docs';

export * from './stencil-public-docs';
Expand Down Expand Up @@ -424,7 +424,15 @@ type RequireFields<T, K extends keyof T> = T & { [P in K]-?: T[P] };
/**
* Fields in {@link Config} to make required for {@link ValidatedConfig}
*/
type StrictConfigFields = 'flags' | 'hydratedFlag' | 'logger' | 'outputTargets' | 'rootDir' | 'sys' | 'testing';
type StrictConfigFields =
| 'flags'
| 'hydratedFlag'
| 'logger'
| 'outputTargets'
| 'packageJsonFilePath'
| 'rootDir'
| 'sys'
| 'testing';

/**
* A version of {@link Config} that makes certain fields required. This type represents a valid configuration entity.
Expand Down Expand Up @@ -2288,24 +2296,18 @@ export interface LoadConfigResults {
}

export interface Diagnostic {
level: 'error' | 'warn' | 'info' | 'log' | 'debug';
type: string;
absFilePath?: string | undefined;
code?: string;
columnNumber?: number | undefined;
debugText?: string;
header?: string;
language?: string;
level: 'error' | 'warn' | 'info' | 'log' | 'debug';
lineNumber?: number | undefined;
lines: PrintLine[];
messageText: string;
debugText?: string;
code?: string;
absFilePath?: string;
relFilePath?: string;
lineNumber?: number;
columnNumber?: number;
lines?: {
lineIndex: number;
lineNumber: number;
text?: string;
errorCharStart: number;
errorLength?: number;
}[];
relFilePath?: string | undefined;
type: string;
}

export interface CacheStorage {
Expand Down
7 changes: 4 additions & 3 deletions src/dev-server/ssr-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,16 @@ async function setupHydrateApp(devServerConfig: d.DevServerConfig, serverCtx: d.
}

if (!isString(buildResults.hydrateAppFilePath)) {
diagnostics.push({ messageText: `Missing hydrateAppFilePath`, level: `error`, type: `ssr` });
diagnostics.push({ messageText: `Missing hydrateAppFilePath`, level: `error`, type: `ssr`, lines: [] });
} else if (!isString(devServerConfig.srcIndexHtml)) {
diagnostics.push({ messageText: `Missing srcIndexHtml`, level: `error`, type: `ssr` });
diagnostics.push({ messageText: `Missing srcIndexHtml`, level: `error`, type: `ssr`, lines: [] });
} else {
srcIndexHtml = await serverCtx.sys.readFile(devServerConfig.srcIndexHtml);
if (!isString(srcIndexHtml)) {
diagnostics.push({
messageText: `Unable to load src index html: ${devServerConfig.srcIndexHtml}`,
level: `error`,
lines: [],
messageText: `Unable to load src index html: ${devServerConfig.srcIndexHtml}`,
type: `ssr`,
});
} else {
Expand Down
4 changes: 3 additions & 1 deletion src/testing/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,16 @@ import { createTestingSystem, TestingSystem } from './testing-sys';
*/
export function mockValidatedConfig(overrides: Partial<ValidatedConfig> = {}): ValidatedConfig {
const baseConfig = mockConfig(overrides);
const rootDir = path.resolve('/');

return {
...baseConfig,
flags: createConfigFlags(),
hydratedFlag: null,
logger: mockLogger(),
outputTargets: baseConfig.outputTargets ?? [],
rootDir: path.resolve('/'),
packageJsonFilePath: path.join(rootDir, 'package.json'),
rootDir,
sys: createTestingSystem(),
testing: {},
...overrides,
Expand Down
20 changes: 11 additions & 9 deletions src/utils/logger/logger-typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,22 +102,24 @@ export const loadTypeScriptDiagnostics = (tsDiagnostics: readonly Diagnostic[])
*/
export const loadTypeScriptDiagnostic = (tsDiagnostic: Diagnostic): d.Diagnostic => {
const d: d.Diagnostic = {
level: 'warn',
type: 'typescript',
language: 'typescript',
header: 'TypeScript',
absFilePath: undefined,
code: tsDiagnostic.code.toString(),
messageText: flattenDiagnosticMessageText(tsDiagnostic, tsDiagnostic.messageText),
relFilePath: null,
absFilePath: null,
columnNumber: undefined,
header: 'TypeScript',
language: 'typescript',
level: 'warn',
lineNumber: undefined,
lines: [],
messageText: flattenDiagnosticMessageText(tsDiagnostic, tsDiagnostic.messageText),
relFilePath: undefined,
type: 'typescript',
};

if (tsDiagnostic.category === 1) {
d.level = 'error';
}

if (tsDiagnostic.file) {
if (tsDiagnostic.file && typeof tsDiagnostic.start === 'number') {
d.absFilePath = tsDiagnostic.file.fileName;

const sourceText = tsDiagnostic.file.text;
Expand All @@ -130,7 +132,7 @@ export const loadTypeScriptDiagnostic = (tsDiagnostic: Diagnostic): d.Diagnostic
lineNumber: posData.line + 1,
text: srcLines[posData.line],
errorCharStart: posData.character,
errorLength: Math.max(tsDiagnostic.length, 1),
errorLength: Math.max(tsDiagnostic.length ?? 0, 1),
};

d.lineNumber = errorLine.lineNumber;
Expand Down
18 changes: 0 additions & 18 deletions src/utils/test/util.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,24 +170,6 @@ describe('util', () => {
});
});

it('returns a parse error if parsing cannot complete for undefined package path', () => {
// improperly formatted JSON - note the lack of ':'
const diagnostic = util.parsePackageJson('{ "someJson" "value"}', undefined);

const expectedDiagnostic: d.Diagnostic = stubDiagnostic({
absFilePath: undefined,
header: 'Error Parsing JSON',
messageText: 'Unexpected string in JSON at position 13', // due to missing colon in input
type: 'build',
});

expect(diagnostic).toEqual<util.ParsePackageJsonResult>({
diagnostic: expectedDiagnostic,
data: null,
filePath: undefined,
});
});

it('returns the parsed data from the provided json', () => {
const diagnostic = util.parsePackageJson('{ "someJson": "value"}', mockPackageJsonPath);

Expand Down

0 comments on commit ee92c95

Please sign in to comment.