refactor: fix a lot of errors in type-aware linting (#7477)

This commit is contained in:
Joshua Chen 2022-05-24 15:40:26 +08:00 committed by GitHub
parent 222bf3c091
commit bf1513a3e3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
120 changed files with 407 additions and 364 deletions

View file

@ -90,13 +90,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc1 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc1 title",
},
"id": "doc1",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc1 title",
"slug": "any",
"source": "any",
"title": "doc1 title",
@ -106,13 +108,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc2 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc2 title",
},
"id": "doc2",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc2 title",
"slug": "any",
"source": "any",
"title": "doc2 title",
@ -122,13 +126,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc3 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc3 title",
},
"id": "doc3",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc3 title",
"slug": "any",
"source": "any",
"title": "doc3 title",
@ -138,13 +144,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc4 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc4 title",
},
"id": "doc4",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc4 title",
"slug": "any",
"source": "any",
"title": "doc4 title",
@ -154,13 +162,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc5 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc5 title",
},
"id": "doc5",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc5 title",
"slug": "any",
"source": "any",
"title": "doc5 title",
@ -232,13 +242,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc1 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc1 title",
},
"id": "doc1",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc1 title",
"slug": "any",
"source": "any",
"title": "doc1 title",
@ -248,13 +260,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc2 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc2 title",
},
"id": "doc2",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc2 title",
"slug": "any",
"source": "any",
"title": "doc2 title",
@ -264,13 +278,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc3 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc3 title",
},
"id": "doc3",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc3 title",
"slug": "any",
"source": "any",
"title": "doc3 title",
@ -280,13 +296,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc4 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc4 title",
},
"id": "doc4",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc4 title",
"slug": "any",
"source": "any",
"title": "doc4 title",
@ -296,13 +314,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc5 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc5 title",
},
"id": "doc5",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc5 title",
"slug": "any",
"source": "any",
"title": "doc5 title",
@ -374,13 +394,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc1 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc1 title",
},
"id": "doc1",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc1 title",
"slug": "any",
"source": "any",
"title": "doc1 title",
@ -390,13 +412,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc2 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc2 title",
},
"id": "doc2",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc2 title",
"slug": "any",
"source": "any",
"title": "doc2 title",
@ -406,13 +430,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc3 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc3 title",
},
"id": "doc3",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc3 title",
"slug": "any",
"source": "any",
"title": "doc3 title",
@ -422,13 +448,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc4 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc4 title",
},
"id": "doc4",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc4 title",
"slug": "any",
"source": "any",
"title": "doc4 title",
@ -438,13 +466,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"description": "doc5 description",
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc5 title",
},
"id": "doc5",
"lastUpdatedAt": 0,
"lastUpdatedBy": "any",
"next": undefined,
"permalink": "any",
"previous": undefined,
"sidebar_label": "doc5 title",
"slug": "any",
"source": "any",
"title": "doc5 title",

View file

@ -119,7 +119,7 @@ function createTestUtils({
async function testSlug(docFileSource: string, expectedPermalink: string) {
const docFile = await readDoc(docFileSource);
const metadata = await processDocMetadata({
const metadata = processDocMetadata({
docFile,
versionMetadata,
context,

View file

@ -54,9 +54,9 @@ const createFakeActions = (contentDir: string) => {
addRoute: (config: RouteConfig) => {
routeConfigs.push(config);
},
createData: async (name: string, content: unknown) => {
createData: (name: string, content: unknown) => {
dataContainer[name] = content;
return path.join(contentDir, name);
return Promise.resolve(path.join(contentDir, name));
},
setGlobalData: (data: unknown) => {
globalDataContainer.pluginName = {pluginId: data};

View file

@ -31,11 +31,11 @@ const defaultOptions = {
};
describe('normalizeDocsPluginOptions', () => {
it('returns default options for undefined user options', async () => {
it('returns default options for undefined user options', () => {
expect(testValidate({})).toEqual(defaultOptions);
});
it('accepts correctly defined user options', async () => {
it('accepts correctly defined user options', () => {
const userOptions = {
path: 'my-docs', // Path to data on filesystem, relative to site dir.
routeBasePath: 'my-docs', // URL Route.
@ -83,7 +83,7 @@ describe('normalizeDocsPluginOptions', () => {
});
});
it('accepts correctly defined remark and rehype plugin options', async () => {
it('accepts correctly defined remark and rehype plugin options', () => {
const userOptions = {
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [markdownPluginsFunctionStub],
@ -100,7 +100,7 @@ describe('normalizeDocsPluginOptions', () => {
});
});
it('accepts admonitions false', async () => {
it('accepts admonitions false', () => {
const admonitionsFalse = {
admonitions: false,
};
@ -110,7 +110,7 @@ describe('normalizeDocsPluginOptions', () => {
});
});
it('rejects admonitions true', async () => {
it('rejects admonitions true', () => {
const admonitionsTrue = {
admonitions: true,
};

View file

@ -30,7 +30,9 @@ function createSampleDoc(doc: Pick<DocMetadata, 'id'>): DocMetadata {
unversionedId: 'any',
version: 'any',
title: `${doc.id} title`,
sidebar_label: `${doc.id} title`,
frontMatter: {
sidebar_label: `${doc.id} title`,
},
description: `${doc.id} description`,
...doc,
};
@ -136,7 +138,7 @@ function getSampleTranslationFilesTranslated() {
}
describe('getLoadedContentTranslationFiles', () => {
it('returns translation files', async () => {
it('returns translation files', () => {
expect(getSampleTranslationFiles()).toMatchSnapshot();
});
});

View file

@ -126,6 +126,6 @@ export function getDocVersionSuggestions(
const latestVersion = getLatestVersion(data);
const activeDocContext = getActiveDocContext(data, pathname);
const latestDocSuggestion: GlobalDoc | undefined =
activeDocContext?.alternateDocVersions[latestVersion.name];
activeDocContext.alternateDocVersions[latestVersion.name];
return {latestDocSuggestion, latestVersionSuggestion: latestVersion};
}

View file

@ -34,9 +34,11 @@ const StableEmptyObject = {};
// In blog-only mode, docs hooks are still used by the theme. We need a fail-
// safe fallback when the docs plugin is not in use
export const useAllDocsData = (): {[pluginId: string]: GlobalPluginData} =>
(useAllPluginInstancesData('docusaurus-plugin-content-docs') as {
[pluginId: string]: GlobalPluginData;
}) ?? StableEmptyObject;
(useAllPluginInstancesData('docusaurus-plugin-content-docs') as
| {
[pluginId: string]: GlobalPluginData;
}
| undefined) ?? StableEmptyObject;
export const useDocsData = (pluginId: string | undefined): GlobalPluginData =>
usePluginData('docusaurus-plugin-content-docs', pluginId, {

View file

@ -143,7 +143,7 @@ export default async function pluginContentDocs(
)}".`,
);
}
async function processVersionDoc(docFile: DocFile) {
function processVersionDoc(docFile: DocFile) {
return processDocMetadata({
docFile,
versionMetadata,

View file

@ -16,5 +16,5 @@ export default function markdownLoader(
const fileString = source;
const callback = this.async();
const options = this.getOptions();
return callback?.(null, linkify(fileString, this.resourcePath, options));
return callback(null, linkify(fileString, this.resourcePath, options));
}

View file

@ -165,7 +165,7 @@ export function validateOptions({
}
}
const normalizedOptions = validate(OptionsSchema, options) as PluginOptions;
const normalizedOptions = validate(OptionsSchema, options);
if (normalizedOptions.admonitions) {
normalizedOptions.remarkPlugins = normalizedOptions.remarkPlugins.concat([

View file

@ -51,7 +51,7 @@ Available document ids are:
} = docMetadata;
return {
type: 'link',
label: sidebarLabel || item.label || title,
label: sidebarLabel ?? item.label ?? title,
href: permalink,
className: item.className,
customProps:

View file

@ -463,7 +463,7 @@ describe('DefaultSidebarItemsGenerator', () => {
expect(sidebarSlice).toMatchSnapshot();
});
it('throws for unknown index link', async () => {
it('throws for unknown index link', () => {
const generateSidebar = () =>
DefaultSidebarItemsGenerator({
numberPrefixParser: DefaultNumberPrefixParser,
@ -499,7 +499,7 @@ describe('DefaultSidebarItemsGenerator', () => {
},
});
await expect(generateSidebar).rejects.toThrowErrorMatchingInlineSnapshot(`
expect(() => generateSidebar()).toThrowErrorMatchingInlineSnapshot(`
"Can't find any doc with ID foo.
Available doc IDs:
- intro"

View file

@ -26,7 +26,7 @@ describe('processSidebars', () => {
function createStaticSidebarItemGenerator(
sidebarSlice: SidebarItem[],
): SidebarItemsGenerator {
return jest.fn(async () => sidebarSlice);
return jest.fn(() => sidebarSlice);
}
const StaticGeneratedSidebarSlice: NormalizedSidebar = [
@ -40,7 +40,7 @@ describe('processSidebars', () => {
// @ts-expect-error: good enough for this test
const version: VersionMetadata = {
versionName: '1.0.0',
versionPath: '/docs/1.0.0',
path: '/docs/1.0.0',
};
const params: SidebarProcessorParams = {

View file

@ -134,11 +134,11 @@ describe('createSidebarsUtils', () => {
getFirstLink,
} = createSidebarsUtils(sidebars);
it('getFirstDocIdOfFirstSidebar', async () => {
it('getFirstDocIdOfFirstSidebar', () => {
expect(getFirstDocIdOfFirstSidebar()).toBe('doc1');
});
it('getSidebarNameByDocId', async () => {
it('getSidebarNameByDocId', () => {
expect(getSidebarNameByDocId('doc1')).toBe('sidebar1');
expect(getSidebarNameByDocId('doc2')).toBe('sidebar1');
expect(getSidebarNameByDocId('doc3')).toBe('sidebar2');
@ -149,7 +149,7 @@ describe('createSidebarsUtils', () => {
expect(getSidebarNameByDocId('unknown_id')).toBeUndefined();
});
it('getDocNavigation', async () => {
it('getDocNavigation', () => {
expect(getDocNavigation('doc1', 'doc1', undefined)).toEqual({
sidebarName: 'sidebar1',
previous: undefined,
@ -229,7 +229,7 @@ describe('createSidebarsUtils', () => {
});
});
it('getCategoryGeneratedIndexNavigation', async () => {
it('getCategoryGeneratedIndexNavigation', () => {
expect(
getCategoryGeneratedIndexNavigation('/s3-subcategory-index-permalink'),
).toMatchObject({
@ -259,7 +259,7 @@ describe('createSidebarsUtils', () => {
});
});
it('getCategoryGeneratedIndexList', async () => {
it('getCategoryGeneratedIndexList', () => {
expect(getCategoryGeneratedIndexList()).toMatchObject([
{
type: 'category',
@ -301,7 +301,7 @@ describe('createSidebarsUtils', () => {
});
describe('collectSidebarDocItems', () => {
it('can collect docs', async () => {
it('can collect docs', () => {
const sidebar: Sidebar = [
{
type: 'category',
@ -357,7 +357,7 @@ describe('collectSidebarDocItems', () => {
});
describe('collectSidebarCategories', () => {
it('can collect categories', async () => {
it('can collect categories', () => {
const sidebar: Sidebar = [
{
type: 'category',
@ -415,7 +415,7 @@ describe('collectSidebarCategories', () => {
});
describe('collectSidebarLinks', () => {
it('can collect links', async () => {
it('can collect links', () => {
const sidebar: Sidebar = [
{
type: 'category',
@ -453,7 +453,7 @@ describe('collectSidebarLinks', () => {
});
describe('collectSidebarsDocIds', () => {
it('can collect sidebars doc items', async () => {
it('can collect sidebars doc items', () => {
const sidebar1: Sidebar = [
{
type: 'category',
@ -499,7 +499,7 @@ describe('collectSidebarsDocIds', () => {
});
describe('transformSidebarItems', () => {
it('can transform sidebar items', async () => {
it('can transform sidebar items', () => {
const sidebar: Sidebar = [
{
type: 'category',

View file

@ -9,7 +9,7 @@ import {validateSidebars, validateCategoryMetadataFile} from '../validation';
import type {SidebarsConfig, CategoryMetadataFile} from '../types';
describe('validateSidebars', () => {
it('throw for bad value', async () => {
it('throw for bad value', () => {
expect(() => validateSidebars({sidebar: [{type: 42}]}))
.toThrowErrorMatchingInlineSnapshot(`
"{
@ -21,12 +21,12 @@ describe('validateSidebars', () => {
`);
});
it('accept empty object', async () => {
it('accept empty object', () => {
const sidebars: SidebarsConfig = {};
validateSidebars(sidebars);
});
it('accept valid values', async () => {
it('accept valid values', () => {
const sidebars: SidebarsConfig = {
sidebar1: [
{type: 'doc', id: 'doc1'},
@ -207,7 +207,7 @@ describe('validateSidebars', () => {
).toThrowErrorMatchingInlineSnapshot(`"sidebar.forEach is not a function"`);
});
it('sidebars item doc but id is not a string', async () => {
it('sidebars item doc but id is not a string', () => {
expect(() =>
validateSidebars({
docs: [
@ -267,18 +267,18 @@ describe('validateSidebars', () => {
describe('validateCategoryMetadataFile', () => {
// TODO add more tests
it('throw for bad value', async () => {
it('throw for bad value', () => {
expect(() =>
validateCategoryMetadataFile(42),
).toThrowErrorMatchingInlineSnapshot(`""value" must be of type object"`);
});
it('accept empty object', async () => {
it('accept empty object', () => {
const content: CategoryMetadataFile = {};
expect(validateCategoryMetadataFile(content)).toEqual(content);
});
it('accept valid values', async () => {
it('accept valid values', () => {
const content: CategoryMetadataFile = {
className: 'className',
label: 'Category Label',
@ -295,7 +295,7 @@ describe('validateCategoryMetadataFile', () => {
expect(validateCategoryMetadataFile(content)).toEqual(content);
});
it('rejects permalink', async () => {
it('rejects permalink', () => {
const content: CategoryMetadataFile = {
className: 'className',
label: 'Category Label',

View file

@ -46,7 +46,7 @@ type Dir = {
};
// Comment for this feature: https://github.com/facebook/docusaurus/issues/3464#issuecomment-818670449
export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async ({
export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = ({
numberPrefixParser,
isCategoryIndex,
docs: allDocs,

View file

@ -84,7 +84,7 @@ function postProcessSidebarItem(
};
}
// A non-collapsible category can't be collapsed!
if (category.collapsible === false) {
if (!category.collapsible) {
category.collapsed = false;
}
return category;

View file

@ -251,7 +251,7 @@ export type SidebarItemsGeneratorArgs = {
};
export type SidebarItemsGenerator = (
generatorArgs: SidebarItemsGeneratorArgs,
) => Promise<NormalizedSidebar>;
) => NormalizedSidebar | Promise<NormalizedSidebar>;
export type SidebarItemsGeneratorOption = (
generatorArgs: {
@ -262,7 +262,7 @@ export type SidebarItemsGeneratorOption = (
*/
defaultSidebarItemsGenerator: SidebarItemsGenerator;
} & SidebarItemsGeneratorArgs,
) => Promise<NormalizedSidebarItem[]>;
) => NormalizedSidebar | Promise<NormalizedSidebar>;
export type SidebarProcessorParams = {
sidebarItemsGenerator: SidebarItemsGeneratorOption;

View file

@ -257,7 +257,7 @@ export function createSidebarsUtils(sidebars: Sidebars): SidebarsUtils {
): boolean {
return (
item.type === 'category' &&
item.link?.type === 'generated-index' &&
item.link.type === 'generated-index' &&
item.link.permalink === categoryGeneratedIndexPermalink
);
}

View file

@ -144,7 +144,7 @@ function validateSidebarItem(
// manually
Joi.assert(item, sidebarItemSchema);
if ((item as NormalizedSidebarItemCategory).type === 'category') {
if ((item as NormalizedSidebarItem).type === 'category') {
(item as NormalizedSidebarItemCategory).items.forEach(validateSidebarItem);
}
}
@ -170,5 +170,9 @@ const categoryMetadataFileSchema = Joi.object<CategoryMetadataFile>({
export function validateCategoryMetadataFile(
unsafeContent: unknown,
): CategoryMetadataFile {
return Joi.attempt(unsafeContent, categoryMetadataFileSchema);
const {error, value} = categoryMetadataFileSchema.validate(unsafeContent);
if (error) {
throw error;
}
return value;
}

View file

@ -58,7 +58,7 @@ export default function getSlug({
) {
return dirNameSlug;
}
const baseSlug = frontMatterSlug || baseID;
const baseSlug = frontMatterSlug ?? baseID;
return resolvePathname(baseSlug, getDirNameSlug());
}

View file

@ -604,7 +604,7 @@ describe('readVersionsMetadata', () => {
context: defaultContext,
}),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Versions should be strings. Found type "number" for version "1.1"."`,
`"Versions should be strings. Found type "number" for version 1.1."`,
);
jsonMock.mockImplementationOnce(() => [' ']);

View file

@ -11,7 +11,9 @@ import type {VersionsOptions} from '@docusaurus/plugin-content-docs';
export function validateVersionName(name: unknown): asserts name is string {
if (typeof name !== 'string') {
throw new Error(
`Versions should be strings. Found type "${typeof name}" for version "${name}".`,
`Versions should be strings. Found type "${typeof name}" for version ${JSON.stringify(
name,
)}.`,
);
}
if (!name.trim()) {