Skip to content

Commit

Permalink
refactor: fix a lot of errors in type-aware linting (#7477)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena committed May 24, 2022
1 parent 222bf3c commit bf1513a
Show file tree
Hide file tree
Showing 120 changed files with 407 additions and 364 deletions.
20 changes: 9 additions & 11 deletions __tests__/validate-package-json.test.ts
Expand Up @@ -70,17 +70,15 @@ describe('packages', () => {
packageJsonFile.content.name?.startsWith('@'),
)
.forEach((packageJsonFile) => {
if (packageJsonFile) {
// Unfortunately jest custom message do not exist in loops,
// so using an exception instead to show failing package file
// (see https://github.com/facebook/jest/issues/3293)
// expect(packageJsonFile.content.publishConfig?.access)
// .toEqual('public');
if (packageJsonFile.content.publishConfig?.access !== 'public') {
throw new Error(
`Package ${packageJsonFile.file} does not have publishConfig.access: 'public'`,
);
}
// Unfortunately jest custom message do not exist in loops,
// so using an exception instead to show failing package file
// (see https://github.com/facebook/jest/issues/3293)
// expect(packageJsonFile.content.publishConfig?.access)
// .toEqual('public');
if (packageJsonFile.content.publishConfig?.access !== 'public') {
throw new Error(
`Package ${packageJsonFile.file} does not have publishConfig.access: 'public'`,
);
}
});
});
Expand Down
5 changes: 2 additions & 3 deletions admin/new.docusaurus.io/functions/codesandbox.ts
Expand Up @@ -8,6 +8,5 @@
import {createPlaygroundResponse} from '../functionUtils/playgroundUtils';
import type {Handler} from '@netlify/functions';

export const handler: Handler = async function handler() {
return createPlaygroundResponse('codesandbox');
};
export const handler: Handler = () =>
Promise.resolve(createPlaygroundResponse('codesandbox'));
5 changes: 2 additions & 3 deletions admin/new.docusaurus.io/functions/stackblitz.ts
Expand Up @@ -8,6 +8,5 @@
import {createPlaygroundResponse} from '../functionUtils/playgroundUtils';
import type {Handler} from '@netlify/functions';

export const handler: Handler = async function handler() {
return createPlaygroundResponse('stackblitz');
};
export const handler: Handler = () =>
Promise.resolve(createPlaygroundResponse('stackblitz'));
41 changes: 21 additions & 20 deletions packages/create-docusaurus/src/index.ts
Expand Up @@ -65,20 +65,22 @@ async function askForPackageManagerChoice(): Promise<PackageManager> {
.map((p) => ({title: p, value: p}));

return (
(await prompts(
{
type: 'select',
name: 'packageManager',
message: 'Select a package manager...',
choices,
},
{
onCancel() {
logger.info`Falling back to name=${defaultPackageManager}`;
(
(await prompts(
{
type: 'select',
name: 'packageManager',
message: 'Select a package manager...',
choices,
},
},
)) as {packageManager: PackageManager}
).packageManager;
{
onCancel() {
logger.info`Falling back to name=${defaultPackageManager}`;
},
},
)) as {packageManager: PackageManager}
).packageManager ?? defaultPackageManager
);
}

async function getPackageManager(
Expand All @@ -101,8 +103,7 @@ async function getPackageManager(
(await findPackageManagerFromLockFile('.')) ??
findPackageManagerFromUserAgent() ??
// This only happens if the user has a global installation in PATH
(skipInstall ? defaultPackageManager : askForPackageManagerChoice()) ??
defaultPackageManager
(skipInstall ? defaultPackageManager : askForPackageManagerChoice())
);
}

Expand Down Expand Up @@ -215,7 +216,7 @@ async function getGitCommand(gitStrategy: GitStrategy): Promise<string> {
logger.info`Falling back to code=${'git clone'}`;
},
},
)) as {command: string};
)) as {command?: string};
return command ?? 'git clone';
}
case 'deep':
Expand Down Expand Up @@ -362,7 +363,7 @@ async function getSource(
)) as {gitRepoUrl: string};
let strategy = cliOptions.gitStrategy;
if (!strategy) {
({strategy} = await prompts(
({strategy} = (await prompts(
{
type: 'select',
name: 'strategy',
Expand All @@ -385,7 +386,7 @@ async function getSource(
logger.info`Falling back to name=${'deep'}`;
},
},
));
)) as {strategy?: GitStrategy});
}
return {
type: 'git',
Expand Down Expand Up @@ -426,13 +427,13 @@ async function getSource(
}
let useTS = cliOptions.typescript;
if (!useTS && template.tsVariantPath) {
({useTS} = await prompts({
({useTS} = (await prompts({
type: 'confirm',
name: 'useTS',
message:
'This template is available in TypeScript. Do you want to use the TS variant?',
initial: false,
}));
})) as {useTS?: boolean});
}
return {
type: 'template',
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-logger/src/index.ts
Expand Up @@ -9,10 +9,10 @@ import chalk from 'chalk';

type InterpolatableValue = string | number | (string | number)[];

const path = (msg: unknown): string => chalk.cyan.underline(`"${msg}"`);
const path = (msg: unknown): string => chalk.cyan.underline(`"${String(msg)}"`);
const url = (msg: unknown): string => chalk.cyan.underline(msg);
const name = (msg: unknown): string => chalk.blue.bold(msg);
const code = (msg: unknown): string => chalk.cyan(`\`${msg}\``);
const code = (msg: unknown): string => chalk.cyan(`\`${String(msg)}\``);
const subdue = (msg: unknown): string => chalk.gray(msg);
const num = (msg: unknown): string => chalk.yellow(msg);

Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-mdx-loader/src/index.ts
Expand Up @@ -21,7 +21,7 @@ export type LoadedMDXContent<FrontMatter, Metadata, Assets = undefined> = {
/** As provided by the content plugin. */
readonly metadata: Metadata;
/** A list of TOC items (headings). */
readonly toc: readonly TOCItem[];
readonly toc?: readonly TOCItem[];
/** First h1 title before any content. */
readonly contentTitle: string | undefined;
/**
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-mdx-loader/src/loader.ts
Expand Up @@ -55,7 +55,7 @@ export type MDXOptions = {
beforeDefaultRehypePlugins: MDXPlugin[];
};

export type Options = MDXOptions & {
export type Options = Partial<MDXOptions> & {
staticDirs: string[];
siteDir: string;
isMDXPartial?: (filePath: string) => boolean;
Expand Down Expand Up @@ -138,7 +138,7 @@ export async function mdxLoader(
): Promise<void> {
const callback = this.async();
const filePath = this.resourcePath;
const reqOptions = this.getOptions() ?? {};
const reqOptions = this.getOptions();

const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);

Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-mdx-loader/src/remark/headings/index.ts
Expand Up @@ -17,7 +17,7 @@ export default function plugin(): Transformer {
return (root) => {
const slugs = createSlugger();
visit(root, 'heading', (headingNode: Heading) => {
const data = headingNode.data || (headingNode.data = {});
const data = headingNode.data ?? (headingNode.data = {});
const properties = (data.hProperties || (data.hProperties = {})) as {
id: string;
};
Expand All @@ -36,7 +36,7 @@ export default function plugin(): Transformer {
// Support explicit heading IDs
const parsedHeading = parseMarkdownHeadingId(heading);

id = parsedHeading.id || slugs.slug(heading);
id = parsedHeading.id ?? slugs.slug(heading);

if (parsedHeading.id) {
// When there's an id, it is always in the last child node
Expand Down
Expand Up @@ -110,8 +110,9 @@ async function processLinkNode(node: Link, context: Context) {
if (!node.url) {
// Try to improve error feedback
// see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
const title = node.title || (node.children[0] as Literal)?.value || '?';
const line = node?.position?.start?.line || '?';
const title =
node.title ?? (node.children[0] as Literal | undefined)?.value ?? '?';
const line = node.position?.start.line ?? '?';
throw new Error(
`Markdown link URL is mandatory in "${toMessageRelativeFilePath(
context.filePath,
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-mdx-loader/src/remark/utils/index.ts
Expand Up @@ -15,7 +15,7 @@ export function stringifyContent(node: Parent): string {
}

export function toValue(node: PhrasingContent | Heading): string {
switch (node?.type) {
switch (node.type) {
case 'text':
return escapeHtml(node.value);
case 'heading':
Expand Down
8 changes: 4 additions & 4 deletions packages/docusaurus-migrate/src/__tests__/index.test.ts
Expand Up @@ -19,22 +19,22 @@ async function testMigration(siteDir: string, newDir: string) {
await migrateDocusaurusProject(siteDir, newDir, true, true);
expect(
writeMock.mock.calls.sort((a, b) =>
posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)),
posixPath(a[0]).localeCompare(posixPath(b[0])),
),
).toMatchSnapshot('write');
expect(
mkdirpMock.mock.calls.sort((a, b) =>
posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)),
posixPath(a[0]).localeCompare(posixPath(b[0])),
),
).toMatchSnapshot('mkdirp');
expect(
mkdirsMock.mock.calls.sort((a, b) =>
posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)),
posixPath(a[0]).localeCompare(posixPath(b[0])),
),
).toMatchSnapshot('mkdirs');
expect(
copyMock.mock.calls.sort((a, b) =>
posixPath(a[0] as string).localeCompare(posixPath(b[0] as string)),
posixPath(a[0]).localeCompare(posixPath(b[0])),
),
).toMatchSnapshot('copy');
writeMock.mockRestore();
Expand Down
7 changes: 1 addition & 6 deletions packages/docusaurus-migrate/src/frontMatter.ts
Expand Up @@ -40,12 +40,7 @@ export default function extractMetadata(content: string): Data {
lines.slice(0, -1).forEach((line) => {
const keyValue = line.split(':') as [string, ...string[]];
const key = keyValue[0].trim();
let value = keyValue.slice(1).join(':').trim();
try {
value = JSON.parse(value);
} catch (err) {
// Ignore the error as it means it's not a JSON value.
}
const value = keyValue.slice(1).join(':').trim();
metadata[key] = value;
});
return {metadata, rawContent: both.content};
Expand Down
61 changes: 31 additions & 30 deletions packages/docusaurus-migrate/src/index.ts
Expand Up @@ -474,7 +474,7 @@ async function migrateVersionedDocs(
versions.reverse().map(async (version, index) => {
if (index === 0) {
await fs.copy(
path.join(siteDir, '..', context.v1Config.customDocsPath || 'docs'),
path.join(siteDir, '..', context.v1Config.customDocsPath ?? 'docs'),
path.join(newDir, 'versioned_docs', `version-${version}`),
);
await fs.copy(
Expand Down Expand Up @@ -551,7 +551,9 @@ async function migrateVersionedSidebar(
const newSidebar = Object.entries(sidebarEntries).reduce(
(topLevel: SidebarEntries, value) => {
const key = value[0].replace(versionRegex, '');
topLevel[key] = Object.entries(value[1]).reduce((acc, val) => {
topLevel[key] = Object.entries(value[1]).reduce<{
[key: string]: Array<string | {[key: string]: unknown}>;
}>((acc, val) => {
acc[val[0].replace(versionRegex, '')] = (
val[1] as SidebarEntry[]
).map((item) => {
Expand All @@ -565,7 +567,7 @@ async function migrateVersionedSidebar(
};
});
return acc;
}, {} as {[key: string]: Array<string | {[key: string]: unknown}>});
}, {});
return topLevel;
},
{},
Expand All @@ -574,33 +576,32 @@ async function migrateVersionedSidebar(
}
await Promise.all(
sidebars.map(async (sidebar) => {
const newSidebar = Object.entries(sidebar.entries).reduce(
(acc, val) => {
const key = `version-${sidebar.version}/${val[0]}`;
acc[key] = Object.entries(val[1]).map((value) => ({
type: 'category',
label: value[0],
items: (value[1] as SidebarEntry[]).map((sidebarItem) => {
if (typeof sidebarItem === 'string') {
return {
type: 'doc',
id: `version-${sidebar.version}/${sidebarItem}`,
};
}
const newSidebar = Object.entries(
sidebar.entries,
).reduce<SidebarEntries>((acc, val) => {
const key = `version-${sidebar.version}/${val[0]}`;
acc[key] = Object.entries(val[1]).map((value) => ({
type: 'category',
label: value[0],
items: (value[1] as SidebarEntry[]).map((sidebarItem) => {
if (typeof sidebarItem === 'string') {
return {
type: 'category',
label: sidebarItem.label,
items: sidebarItem.ids.map((id) => ({
type: 'doc',
id: `version-${sidebar.version}/${id}`,
})),
type: 'doc',
id: `version-${sidebar.version}/${sidebarItem}`,
};
}),
}));
return acc;
},
{} as SidebarEntries,
);
}
return {
type: 'category',
label: sidebarItem.label,
items: sidebarItem.ids.map((id) => ({
type: 'doc',
id: `version-${sidebar.version}/${id}`,
})),
};
}),
}));
return acc;
}, {});
await fs.outputFile(
path.join(
newDir,
Expand Down Expand Up @@ -702,12 +703,12 @@ async function migrateLatestDocs(context: MigrationContext) {

async function migratePackageFile(context: MigrationContext): Promise<void> {
const {deps, siteDir, newDir} = context;
const packageFile = importFresh(`${siteDir}/package.json`) as {
const packageFile = importFresh<{
scripts?: {[key: string]: string};
dependencies?: {[key: string]: string};
devDependencies?: {[key: string]: string};
[otherKey: string]: unknown;
};
}>(`${siteDir}/package.json`);
packageFile.scripts = {
...packageFile.scripts,
start: 'docusaurus start',
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-migrate/src/sanitizeMD.ts
Expand Up @@ -37,7 +37,7 @@ export default function sanitizeMD(code: string): string {
const htmlTree = unified().use(parse).parse(markdownString);

visit(htmlTree, 'element', (node: Element) => {
if (!tags[node.tagName as string]) {
if (!tags[node.tagName]) {
(node as Element | Text).type = 'text';
(node as Element & Partial<Omit<Text, 'type'>>).value =
node.tagName + toText(node);
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-module-type-aliases/src/index.d.ts
Expand Up @@ -8,7 +8,7 @@
declare module '@generated/client-modules' {
import type {ClientModule} from '@docusaurus/types';

const clientModules: readonly (ClientModule & {default: ClientModule})[];
const clientModules: readonly (ClientModule & {default?: ClientModule})[];
export default clientModules;
}

Expand Down

0 comments on commit bf1513a

Please sign in to comment.