Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESLint V9 - Typed #5608

Merged
merged 13 commits into from
Jun 30, 2024
3 changes: 3 additions & 0 deletions .cspell/misc-terms.txt
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
BRANDES
handdrawn
KOEPF
newbranch
2 changes: 1 addition & 1 deletion .esbuild/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const handler = (e) => {

const main = async () => {
await generateLangium();
await mkdir('stats').catch(() => {});
await mkdir('stats', { recursive: true });
const packageNames = Object.keys(packageOptions) as (keyof typeof packageOptions)[];
// it should build `parser` before `mermaid` because it's a dependency
for (const pkg of packageNames) {
Expand Down
3 changes: 1 addition & 2 deletions .esbuild/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ async function createServer() {
return;
}
console.log(`${path} changed. Rebuilding...`);

if (/\.langium$/.test(path)) {
if (path.endsWith('.langium')) {
await generateLangium();
}
handleFileChange();
Expand Down
17 changes: 8 additions & 9 deletions cypress/helpers/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const mermaidUrl = (
};
const objStr: string = JSON.stringify(codeObject);
let url = `http://localhost:9000/e2e.html?graph=${utf8ToB64(objStr)}`;
if (api) {
if (api && typeof graphStr === 'string') {
url = `http://localhost:9000/xss.html?graph=${graphStr}`;
}

Expand All @@ -54,16 +54,15 @@ export const imgSnapshotTest = (
): void => {
const options: CypressMermaidConfig = {
..._options,
fontFamily: _options.fontFamily || 'courier',
fontFamily: _options.fontFamily ?? 'courier',
// @ts-ignore TODO: Fix type of fontSize
fontSize: _options.fontSize || '16px',
fontSize: _options.fontSize ?? '16px',
sequence: {
...(_options.sequence || {}),
...(_options.sequence ?? {}),
actorFontFamily: 'courier',
noteFontFamily:
_options.sequence && _options.sequence.noteFontFamily
? _options.sequence.noteFontFamily
: 'courier',
noteFontFamily: _options.sequence?.noteFontFamily
? _options.sequence.noteFontFamily
: 'courier',
messageFontFamily: 'courier',
},
};
Expand Down Expand Up @@ -95,7 +94,7 @@ export const openURLAndVerifyRendering = (
options: CypressMermaidConfig,
validation?: any
): void => {
const name: string = (options.name || cy.state('runnable').fullTitle()).replace(/\s+/g, '-');
const name: string = (options.name ?? cy.state('runnable').fullTitle()).replace(/\s+/g, '-');

cy.visit(url);
cy.window().should('have.property', 'rendered', true);
Expand Down
2 changes: 1 addition & 1 deletion cypress/platform/bundle-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const code3 = `flowchart TD
A(<img scr='https://iconscout.com/ms-icon-310x310.png' width='20' height='20' />)
B(<b>Bold text!</b>)`;

if (location.href.match('test-html-escaping')) {
if (/test-html-escaping/.exec(location.href)) {
code = code3;
}

Expand Down
2 changes: 1 addition & 1 deletion cypress/platform/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ if (typeof document !== 'undefined') {
window.addEventListener(
'load',
function () {
if (this.location.href.match('xss.html')) {
if (/xss.html/.exec(this.location.href)) {
this.console.log('Using api');
void contentLoadedApi().finally(markRendered);
} else {
Expand Down
8 changes: 4 additions & 4 deletions docs/config/setup/interfaces/mermaid.DetailedError.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

#### Defined in

[packages/mermaid/src/utils.ts:789](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L789)
[packages/mermaid/src/utils.ts:785](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L785)

---

Expand All @@ -26,7 +26,7 @@

#### Defined in

[packages/mermaid/src/utils.ts:787](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L787)
[packages/mermaid/src/utils.ts:783](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L783)

---

Expand All @@ -36,7 +36,7 @@

#### Defined in

[packages/mermaid/src/utils.ts:790](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L790)
[packages/mermaid/src/utils.ts:786](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L786)

---

Expand All @@ -46,4 +46,4 @@

#### Defined in

[packages/mermaid/src/utils.ts:785](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L785)
[packages/mermaid/src/utils.ts:781](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/utils.ts#L781)
2 changes: 1 addition & 1 deletion docs/config/setup/modules/mermaid.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

#### Defined in

[packages/mermaid/src/Diagram.ts:9](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/Diagram.ts#L9)
[packages/mermaid/src/Diagram.ts:10](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/Diagram.ts#L10)

## Variables

Expand Down
12 changes: 11 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import tseslint from 'typescript-eslint';

export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
...tseslint.configs.stylisticTypeChecked,
{
ignores: [
'**/dist/',
Expand Down Expand Up @@ -101,6 +102,15 @@ export default tseslint.config(
},
},
],
// START: These rules should be turned on once the codebase is cleaned up
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/only-throw-error': 'warn',
'@typescript-eslint/prefer-promise-reject-errors': 'warn',
// END
'json/*': ['error', 'allowComments'],
'@cspell/spellchecker': [
'error',
Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid-example-diagram/src/mermaidUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const log: Record<keyof typeof LEVELS, typeof console.log> = {
fatal: warning,
};

export let setLogLevel: (level: keyof typeof LEVELS | number | string) => void;
export let setLogLevel: (level: keyof typeof LEVELS | number) => void;
export let getConfig: () => object;
export let sanitizeText: (str: string) => string;
export let commonDb: () => object;
Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid-zenuml/src/mermaidUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const log: Record<keyof typeof LEVELS, typeof console.log> = {
fatal: warning,
};

export let setLogLevel: (level: keyof typeof LEVELS | number | string) => void;
export let setLogLevel: (level: keyof typeof LEVELS | number) => void;
export let getConfig: () => MermaidConfig;
export let sanitizeText: (str: string) => string;
// eslint-disable @typescript-eslint/no-explicit-any
Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid-zenuml/src/zenumlRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function createTemporaryZenumlContainer(id: string) {
container.id = `container-${id}`;
container.style.display = 'flex';
container.innerHTML = `<div id="zenUMLApp-${id}"></div>`;
const app = container.querySelector(`#zenUMLApp-${id}`) as HTMLElement;
const app = container.querySelector(`#zenUMLApp-${id}`)!;
return { container, app };
}

Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid/scripts/create-types-from-json-schema.mts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ async function generateTypescript(mermaidConfigSchema: JSONSchemaType<MermaidCon
* @returns The schema with `allOf` replaced with `extends`.
*/
function replaceAllOfWithExtends(schema: JSONSchemaType<Record<string, any>>) {
if (schema['allOf']) {
if (schema.allOf) {
const { allOf, ...schemaWithoutAllOf } = schema;
return {
...schemaWithoutAllOf,
Expand Down
11 changes: 6 additions & 5 deletions packages/mermaid/scripts/docs.mts
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ const WARN_DOCSDIR_DOESNT_MATCH = `Changed files were transformed in ${SOURCE_DO
const prettierConfig = (await prettier.resolveConfig('.')) ?? {};
// From https://github.com/vuejs/vitepress/blob/428eec3750d6b5648a77ac52d88128df0554d4d1/src/node/markdownToVue.ts#L20-L21
const includesRE = /<!--\s*@include:\s*(.*?)\s*-->/g;
const includedFiles: Set<string> = new Set();
const includedFiles = new Set<string>();

const filesTransformed: Set<string> = new Set();
const filesTransformed = new Set<string>();

const generateHeader = (file: string): string => {
// path from file in docs/* to repo root, e.g ../ or ../../ */
Expand Down Expand Up @@ -181,10 +181,10 @@ export const transformToBlockQuote = (
) => {
if (vitepress) {
const vitepressType = type === 'note' ? 'info' : type;
return `::: ${vitepressType} ${customTitle || ''}\n${content}\n:::`;
return `::: ${vitepressType} ${customTitle ?? ''}\n${content}\n:::`;
} else {
const icon = blockIcons[type] || '';
const title = `${icon}${customTitle || capitalize(type)}`;
const icon = blockIcons[type] ?? '';
const title = `${icon}${customTitle ?? capitalize(type)}`;
return `> **${title}** \n> ${content.replace(/\n/g, '\n> ')}`;
}
};
Expand All @@ -201,6 +201,7 @@ const transformIncludeStatements = (file: string, text: string): string => {
includedFiles.add(changeToFinalDocDir(includePath));
return content;
} catch (error) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Failed to resolve include "${m1}" in "${file}": ${error}`);
}
});
Expand Down
1 change: 1 addition & 0 deletions packages/mermaid/src/Diagram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { encodeEntities } from './utils.js';
import type { DetailedError } from './utils.js';
import type { DiagramDefinition, DiagramMetadata } from './diagram-api/types.js';

// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
export type ParseErrorFunction = (err: string | DetailedError | unknown, hash?: any) => void;

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export const addDirective = (directive: MermaidConfig) => {
sanitizeDirective(directive);

// If the directive has a fontFamily, but no themeVariables, add the fontFamily to the themeVariables
if (directive.fontFamily && (!directive.themeVariables || !directive.themeVariables.fontFamily)) {
if (directive.fontFamily && !directive.themeVariables?.fontFamily) {
directive.themeVariables = { fontFamily: directive.fontFamily };
}

Expand Down
1 change: 1 addition & 0 deletions packages/mermaid/src/dagre-wrapper/edgeMarker.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/unbound-method */
import type { Mocked } from 'vitest';
import type { SVG } from '../diagram-api/types.js';
import { addEdgeMarkers } from './edgeMarker.js';
Expand Down
4 changes: 2 additions & 2 deletions packages/mermaid/src/dagre-wrapper/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const recursiveRender = async (_elem, graph, diagramType, id, parentCluster, sit
}
}
log.info('(Insert) Node XXX' + v + ': ' + JSON.stringify(graph.node(v)));
if (node && node.clusterNode) {
if (node?.clusterNode) {
// const children = graph.children(v);
log.info('Cluster identified', v, node.width, graph.node(v));
// `node.graph.setGraph` applies the graph configurations such as nodeSpacing to subgraphs as without this the default values would be used
Expand Down Expand Up @@ -130,7 +130,7 @@ const recursiveRender = async (_elem, graph, diagramType, id, parentCluster, sit
' height: ',
node.height
);
if (node && node.clusterNode) {
if (node?.clusterNode) {
// clusterDb[node.id].node = node;
node.y += subGraphTitleTotalMargin;
positionNode(node);
Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid/src/dagre-wrapper/mermaid-graphlib.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ export const extractor = (graph, depth) => {

const graphSettings = graph.graph();
let dir = graphSettings.rankdir === 'TB' ? 'LR' : 'TB';
if (clusterDb[node] && clusterDb[node].clusterData && clusterDb[node].clusterData.dir) {
if (clusterDb[node]?.clusterData?.dir) {
dir = clusterDb[node].clusterData.dir;
log.warn('Fixing dir', clusterDb[node].clusterData.dir, dir);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid/src/dagre-wrapper/nodes.js
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ const class_box = (parent, node) => {

const labelContainer = shapeSvg.insert('g').attr('class', 'label');
let verticalPos = 0;
const hasInterface = node.classData.annotations && node.classData.annotations[0];
const hasInterface = node.classData.annotations?.[0];

// 1. Create the labels
const interfaceLabelText = node.classData.annotations[0]
Expand Down
4 changes: 2 additions & 2 deletions packages/mermaid/src/defaultConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const config: RequiredDeep<MermaidConfig> = {
themeCSS: undefined,

// add non-JSON default config values
themeVariables: theme['default'].getThemeVariables(),
themeVariables: theme.default.getThemeVariables(),
sequence: {
...defaultConfigJson.sequence,
messageFont: function () {
Expand Down Expand Up @@ -272,5 +272,5 @@ const keyify = (obj: any, prefix = ''): string[] =>
return [...res, prefix + el];
}, []);

export const configKeys: Set<string> = new Set(keyify(config, ''));
export const configKeys = new Set<string>(keyify(config, ''));
export default config;
2 changes: 1 addition & 1 deletion packages/mermaid/src/diagram-api/diagramAPI.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ describe('DiagramAPI', () => {
`[UnknownDiagramError: No diagram type detected matching given configuration for text: loki diagram]`
);
const detector: DiagramDetector = (str: string) => {
return str.match('loki') !== null;
return /loki/.exec(str) !== null;
};
registerDiagram(
'loki',
Expand Down
4 changes: 1 addition & 3 deletions packages/mermaid/src/diagram-api/diagramAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ export const getCommonDb = () => {
};

const diagrams: Record<string, DiagramDefinition> = {};
export interface Detectors {
[key: string]: DiagramDetector;
}
export type Detectors = Record<string, DiagramDetector>;

/**
* Registers the given diagram with Mermaid.
Expand Down
6 changes: 3 additions & 3 deletions packages/mermaid/src/diagram.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ const getDummyDiagram = (id: string, title?: string): Awaited<ReturnType<Diagram

describe('diagram detection', () => {
test('should detect inbuilt diagrams', async () => {
const graph = (await Diagram.fromText('graph TD; A-->B')) as Diagram;
const graph = await Diagram.fromText('graph TD; A-->B');
expect(graph).toBeInstanceOf(Diagram);
expect(graph.type).toBe('flowchart-v2');
const sequence = (await Diagram.fromText(
const sequence = await Diagram.fromText(
'sequenceDiagram; Alice->>+John: Hello John, how are you?'
)) as Diagram;
);
expect(sequence).toBeInstanceOf(Diagram);
expect(sequence.type).toBe('sequence');
});
Expand Down
Loading
Loading