From 88e17bf1b4ab791ba16b3ad012501ac3726e021c Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sat, 20 Aug 2022 23:40:52 +0530 Subject: [PATCH 01/31] Typescript init --- .prettierrc.json | 3 - .webpack/webpack.config.base.js | 7 ++- package.json | 2 + src/{Diagram.js => Diagram.ts} | 23 ++++++-- src/logger.js | 10 ++-- tsconfig.json | 101 ++++++++++++++++++++++++++++++++ yarn.lock | 19 +++++- 7 files changed, 148 insertions(+), 17 deletions(-) rename src/{Diagram.js => Diagram.ts} (84%) create mode 100644 tsconfig.json diff --git a/.prettierrc.json b/.prettierrc.json index 8cadfefaf7..0835748d6f 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,8 +1,5 @@ { "endOfLine": "auto", - "plugins": [ - "prettier-plugin-jsdoc" - ], "printWidth": 100, "singleQuote": true } \ No newline at end of file diff --git a/.webpack/webpack.config.base.js b/.webpack/webpack.config.base.js index 055f59dfc9..25dfbffcc5 100644 --- a/.webpack/webpack.config.base.js +++ b/.webpack/webpack.config.base.js @@ -9,7 +9,7 @@ export default { mermaid: './src/mermaid.js', }, resolve: { - extensions: ['.wasm', '.mjs', '.js', '.json', '.jison'], + extensions: ['.wasm', '.mjs', '.js', '.ts', '.json', '.jison'], fallback: { fs: false, // jison generated code requires 'fs' path: require.resolve('path-browserify'), @@ -27,6 +27,11 @@ export default { }, module: { rules: [ + { + test: /\.ts$/, + use: 'ts-loader', + exclude: /node_modules/, + }, { test: /\.js$/, include: [resolveRoot('./src'), resolveRoot('./node_modules/dagre-d3-renderer/lib')], diff --git a/package.json b/package.json index e71afdc894..4b6e676a50 100644 --- a/package.json +++ b/package.json @@ -106,6 +106,8 @@ "prettier-plugin-jsdoc": "^0.3.30", "start-server-and-test": "^1.12.6", "terser-webpack-plugin": "^5.2.4", + "ts-loader": "^9.3.1", + "typescript": "^4.7.4", "webpack": "^5.53.0", "webpack-cli": "^4.7.2", "webpack-dev-server": "^4.3.0", diff --git a/src/Diagram.js b/src/Diagram.ts similarity index 84% rename from src/Diagram.js rename to src/Diagram.ts index 16dfb89d39..c4e265b04b 100644 --- a/src/Diagram.js +++ b/src/Diagram.ts @@ -1,4 +1,3 @@ -import utils from './utils'; import * as configApi from './config'; import { log } from './logger'; import { getDiagrams } from './diagram-api/diagramAPI'; @@ -8,7 +7,7 @@ class Diagram { parser; renderer; db; - constructor(txt) { + constructor(public txt: string) { const diagrams = getDiagrams(); const cnf = configApi.getConfig(); this.txt = txt; @@ -17,26 +16,32 @@ class Diagram { // console.log('this.type', this.type, diagrams[this.type]); // Setup diagram + // @ts-ignore this.db = diagrams[this.type].db; this.db.clear?.(); + // @ts-ignore this.renderer = diagrams[this.type].renderer; + // @ts-ignore this.parser = diagrams[this.type].parser; + // @ts-ignore this.parser.parser.yy = this.db; + // @ts-ignore if (typeof diagrams[this.type].init === 'function') { + // @ts-ignore diagrams[this.type].init(cnf); log.debug('Initialized diagram ' + this.type, cnf); } - this.txt = this.txt + '\n'; - + this.txt += '\n'; this.parser.parser.yy.graphType = this.type; - this.parser.parser.yy.parseError = (str, hash) => { + this.parser.parser.yy.parseError = (str: string, hash: string) => { const error = { str, hash }; throw error; }; this.parser.parse(this.txt); } - parse(text) { + + parse(text: string) { var parseEncounteredException = false; try { text = text + '\n'; @@ -47,13 +52,17 @@ class Diagram { parseEncounteredException = true; // Is this the correct way to access mermiad's parseError() // method ? (or global.mermaid.parseError()) ? + // @ts-ignore if (global.mermaid.parseError) { + // @ts-ignore if (error.str != undefined) { // handle case where error string and hash were // wrapped in object like`const error = { str, hash };` + // @ts-ignore global.mermaid.parseError(error.str, error.hash); } else { // assume it is just error string and pass it on + // @ts-ignore global.mermaid.parseError(error); } } else { @@ -63,9 +72,11 @@ class Diagram { } return !parseEncounteredException; } + getParser() { return this.parser; } + getType() { return this.type; } diff --git a/src/logger.js b/src/logger.js index ac4fc8f051..557bb15cee 100644 --- a/src/logger.js +++ b/src/logger.js @@ -12,11 +12,11 @@ export const LEVELS = { }; export const log = { - debug: () => {}, - info: () => {}, - warn: () => {}, - error: () => {}, - fatal: () => {}, + debug: (...args) => {}, + info: (...args) => {}, + warn: (...args) => {}, + error: (...args) => {}, + fatal: (...args) => {}, }; /** diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000..7fdd4d736f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,101 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + // "incremental": true, /* Enable incremental compilation */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ + // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + + /* Modules */ + "module": "ES6", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "resolveJsonModule": true, /* Enable importing .json files */ + // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ + // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ + // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/yarn.lock b/yarn.lock index b44324a2ef..815afd3dd1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5098,7 +5098,7 @@ end-of-stream@^1.0.0, end-of-stream@^1.1.0: dependencies: once "^1.4.0" -enhanced-resolve@^5.10.0: +enhanced-resolve@^5.0.0, enhanced-resolve@^5.10.0: version "5.10.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.10.0.tgz#0dc579c3bb2a1032e357ac45b8f3a6f3ad4fb1e6" integrity sha512-T0yTFjdpldGY8PmuXXR0PyQ1ufZpEGiHVrp7zHKB7jdR4qlmZHhONVM5AQOAWXuF/w3dnHbEQVrNptJgt7F+cQ== @@ -8475,7 +8475,7 @@ micromatch@^3.1.5: snapdragon "^0.8.1" to-regex "^3.0.2" -micromatch@^4.0.2, micromatch@^4.0.4, micromatch@^4.0.5: +micromatch@^4.0.0, micromatch@^4.0.2, micromatch@^4.0.4, micromatch@^4.0.5: version "4.0.5" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.5.tgz#bc8999a7cbbf77cdc89f132f6e467051b49090c6" integrity sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA== @@ -11098,6 +11098,16 @@ trough@^1.0.0: resolved "https://registry.yarnpkg.com/trough/-/trough-1.0.5.tgz#b8b639cefad7d0bb2abd37d433ff8293efa5f406" integrity sha512-rvuRbTarPXmMb79SmzEp8aqXNKcK+y0XaB298IXueQ8I2PsrATcPBCSPyK/dDNa2iWOhKlfNnOjdAOTBU/nkFA== +ts-loader@^9.3.1: + version "9.3.1" + resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-9.3.1.tgz#fe25cca56e3e71c1087fe48dc67f4df8c59b22d4" + integrity sha512-OkyShkcZTsTwyS3Kt7a4rsT/t2qvEVQuKCTg4LJmpj9fhFR7ukGdZwV6Qq3tRUkqcXtfGpPR7+hFKHCG/0d3Lw== + dependencies: + chalk "^4.1.0" + enhanced-resolve "^5.0.0" + micromatch "^4.0.0" + semver "^7.3.4" + ts-node@^10.7.0: version "10.7.0" resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.7.0.tgz#35d503d0fab3e2baa672a0e94f4b40653c2463f5" @@ -11213,6 +11223,11 @@ typescript@^4.6.4: resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.6.4.tgz#caa78bbc3a59e6a5c510d35703f6a09877ce45e9" integrity sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg== +typescript@^4.7.4: + version "4.7.4" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.7.4.tgz#1a88596d1cf47d59507a1bcdfb5b9dfe4d488235" + integrity sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ== + uglify-js@^3.1.4: version "3.14.4" resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.14.4.tgz#68756f17d1b90b9d289341736cb9a567d6882f90" From 95dbbb350b018ab9a639c8ef77c7d787340c0cb6 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 00:38:26 +0530 Subject: [PATCH 02/31] tsConversion: DetectType --- jest.config.js | 1 + package.json | 2 + src/Diagram.ts | 2 +- src/diagram-api/detectType.js | 100 ------------------ src/diagram-api/detectType.ts | 77 ++++++++++++++ ...hestration.js => diagram-orchestration.ts} | 10 +- src/diagram-api/diagramAPI.js | 4 + src/diagrams/git/gitGraphDetector.js | 8 -- src/diagrams/git/gitGraphDetector.ts | 3 + src/diagrams/git/gitGraphParserV2.spec.js | 1 - src/diagrams/mindmap/mindamapDetector.js | 8 -- src/diagrams/mindmap/mindamapDetector.ts | 3 + src/mermaidAPI.js | 2 +- src/types.d.ts | 7 ++ src/utils.js | 2 +- src/utils.spec.js | 4 +- yarn.lock | 51 +++++++-- 17 files changed, 152 insertions(+), 133 deletions(-) delete mode 100644 src/diagram-api/detectType.js create mode 100644 src/diagram-api/detectType.ts rename src/diagram-api/{diagram-orchestration.js => diagram-orchestration.ts} (75%) delete mode 100644 src/diagrams/git/gitGraphDetector.js create mode 100644 src/diagrams/git/gitGraphDetector.ts delete mode 100644 src/diagrams/mindmap/mindamapDetector.js create mode 100644 src/diagrams/mindmap/mindamapDetector.ts create mode 100644 src/types.d.ts diff --git a/jest.config.js b/jest.config.js index 9930a513e5..ebc6b9fb03 100644 --- a/jest.config.js +++ b/jest.config.js @@ -2,6 +2,7 @@ const path = require('path'); module.exports = { testEnvironment: 'jsdom', + preset: 'ts-jest', transform: { '^.+\\.jsx?$': ['babel-jest', { rootMode: 'upward' }], '^.+\\.jison$': [ diff --git a/package.json b/package.json index 4b6e676a50..926d56f346 100644 --- a/package.json +++ b/package.json @@ -76,6 +76,7 @@ "@babel/register": "^7.14.5", "@commitlint/cli": "^17.0.0", "@commitlint/config-conventional": "^17.0.0", + "@types/jest": "^28.1.7", "babel-jest": "^28.0.3", "babel-loader": "^8.2.2", "concurrently": "^7.0.0", @@ -106,6 +107,7 @@ "prettier-plugin-jsdoc": "^0.3.30", "start-server-and-test": "^1.12.6", "terser-webpack-plugin": "^5.2.4", + "ts-jest": "^28.0.8", "ts-loader": "^9.3.1", "typescript": "^4.7.4", "webpack": "^5.53.0", diff --git a/src/Diagram.ts b/src/Diagram.ts index c4e265b04b..e822d0195c 100644 --- a/src/Diagram.ts +++ b/src/Diagram.ts @@ -1,7 +1,7 @@ import * as configApi from './config'; import { log } from './logger'; import { getDiagrams } from './diagram-api/diagramAPI'; -import detectType from './diagram-api/detectType'; +import { detectType } from './diagram-api/detectType'; class Diagram { type = 'graph'; parser; diff --git a/src/diagram-api/detectType.js b/src/diagram-api/detectType.js deleted file mode 100644 index a5f074e3e1..0000000000 --- a/src/diagram-api/detectType.js +++ /dev/null @@ -1,100 +0,0 @@ -const directive = - /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi; -const anyComment = /\s*%%.*\n/gm; -const detectors = {}; -/** - * @function detectType Detects the type of the graph text. Takes into consideration the possible - * existence of an %%init directive - * - * ```mermaid - * %%{initialize: {"startOnLoad": true, logLevel: "fatal" }}%% - * graph LR - * a-->b - * b-->c - * c-->d - * d-->e - * e-->f - * f-->g - * g-->h - * ``` - * @param {string} text The text defining the graph - * @param {{ - * class: { defaultRenderer: string } | undefined; - * state: { defaultRenderer: string } | undefined; - * flowchart: { defaultRenderer: string } | undefined; - * }} [cnf] - * @returns {string} A graph definition key - */ -const detectType = function (text, cnf) { - text = text.replace(directive, '').replace(anyComment, '\n'); - if (text.match(/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/)) { - return 'c4'; - } - - if (text.match(/^\s*sequenceDiagram/)) { - return 'sequence'; - } - - if (text.match(/^\s*gantt/)) { - return 'gantt'; - } - if (text.match(/^\s*classDiagram-v2/)) { - return 'classDiagram'; - } - if (text.match(/^\s*classDiagram/)) { - if (cnf && cnf.class && cnf.class.defaultRenderer === 'dagre-wrapper') return 'classDiagram'; - return 'class'; - } - - if (text.match(/^\s*stateDiagram-v2/)) { - return 'stateDiagram'; - } - - if (text.match(/^\s*stateDiagram/)) { - if (cnf && cnf.class && cnf.state.defaultRenderer === 'dagre-wrapper') return 'stateDiagram'; - return 'state'; - } - - // if (text.match(/^\s*gitGraph/)) { - // return 'gitGraph'; - // } - if (text.match(/^\s*flowchart/)) { - return 'flowchart-v2'; - } - - if (text.match(/^\s*info/)) { - return 'info'; - } - if (text.match(/^\s*pie/)) { - return 'pie'; - } - - if (text.match(/^\s*erDiagram/)) { - return 'er'; - } - - if (text.match(/^\s*journey/)) { - return 'journey'; - } - - if (text.match(/^\s*requirement/) || text.match(/^\s*requirementDiagram/)) { - return 'requirement'; - } - if (cnf && cnf.flowchart && cnf.flowchart.defaultRenderer === 'dagre-wrapper') - return 'flowchart-v2'; - const k = Object.keys(detectors); - for (let i = 0; i < k.length; i++) { - const key = k[i]; - const dia = detectors[key]; - if (dia && dia.detector(text)) { - return key; - } - } - return 'flowchart'; -}; -export const addDetector = (key, detector) => { - detectors[key] = { - detector, - }; -}; -export default detectType; diff --git a/src/diagram-api/detectType.ts b/src/diagram-api/detectType.ts new file mode 100644 index 0000000000..417d3ace4d --- /dev/null +++ b/src/diagram-api/detectType.ts @@ -0,0 +1,77 @@ +const directive = + /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi; +const anyComment = /\s*%%.*\n/gm; + +const detectors: Record = {}; +const diagramMatchers: Record = { + c4: /^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/, + sequence: /^\s*sequenceDiagram/, + gantt: /^\s*gantt/, + classDiagram: /^\s*classDiagram-v2/, + stateDiagram: /^\s*stateDiagram-v2/, + 'flowchart-v2': /^\s*flowchart/, + info: /^\s*info/, + pie: /^\s*pie/, + er: /^\s*erDiagram/, + journey: /^\s*journey/, + // gitGraph: /^\s*gitGraph/, + requirement: /^\s*requirement(Diagram)?/, +}; + +/** + * @function detectType Detects the type of the graph text. Takes into consideration the possible + * existence of an %%init directive + * + * ```mermaid + * %%{initialize: {"startOnLoad": true, logLevel: "fatal" }}%% + * graph LR + * a-->b + * b-->c + * c-->d + * d-->e + * e-->f + * f-->g + * g-->h + * ``` + * @param {string} text The text defining the graph + * @param {{ + * class: { defaultRenderer: string } | undefined; + * state: { defaultRenderer: string } | undefined; + * flowchart: { defaultRenderer: string } | undefined; + * }} [cnf] + * @returns {string} A graph definition key + */ +export const detectType = function (text: string, cnf: ConfigType): string { + text = text.replace(directive, '').replace(anyComment, '\n'); + for (const [diagram, matcher] of Object.entries(diagramMatchers)) { + if (text.match(matcher)) { + return diagram; + } + } + + if (text.match(/^\s*classDiagram/)) { + if (cnf?.class?.defaultRenderer === 'dagre-wrapper') return 'classDiagram'; + return 'class'; + } + + if (text.match(/^\s*stateDiagram/)) { + if (cnf?.state?.defaultRenderer === 'dagre-wrapper') return 'stateDiagram'; + return 'state'; + } + + if (cnf?.flowchart?.defaultRenderer === 'dagre-wrapper') { + return 'flowchart-v2'; + } + + for (const [key, detector] of Object.entries(detectors)) { + if (detector(text)) { + return key; + } + } + + return 'flowchart'; +}; + +export const addDetector = (key: string, detector: DiagramDetector) => { + detectors[key] = detector; +}; diff --git a/src/diagram-api/diagram-orchestration.js b/src/diagram-api/diagram-orchestration.ts similarity index 75% rename from src/diagram-api/diagram-orchestration.js rename to src/diagram-api/diagram-orchestration.ts index d73bc1bbba..ecdb7e4673 100644 --- a/src/diagram-api/diagram-orchestration.js +++ b/src/diagram-api/diagram-orchestration.ts @@ -1,13 +1,14 @@ -import { registerDiagram } from './diagramAPI.js'; +import { registerDiagram } from './diagramAPI'; // import mindmapDb from '../diagrams/mindmap/mindmapDb'; // import mindmapRenderer from '../diagrams/mindmap/mindmapRenderer'; // import mindmapParser from '../diagrams/mindmap/parser/mindmapDiagram'; -// import mindmapDetector from '../diagrams/mindmap/mindmapDetector'; +// import { mindmapDetector } from '../diagrams/mindmap/mindmapDetector'; import gitGraphDb from '../diagrams/git/gitGraphAst'; import gitGraphRenderer from '../diagrams/git/gitGraphRenderer'; +// @ts-ignore import gitGraphParser from '../diagrams/git/parser/gitGraph'; -import gitGraphDetector from '../diagrams/git/gitGraphDetector'; +import { gitGraphDetector } from '../diagrams/git/gitGraphDetector'; // Register mindmap and other built-in diagrams // registerDiagram( @@ -19,7 +20,7 @@ import gitGraphDetector from '../diagrams/git/gitGraphDetector'; // mindmapRenderer, // mindmapDetector // ); -const addDiagrams = () => { +export const addDiagrams = () => { registerDiagram( 'gitGraph', gitGraphParser, @@ -29,4 +30,3 @@ const addDiagrams = () => { gitGraphDetector ); }; -export default addDiagrams; diff --git a/src/diagram-api/diagramAPI.js b/src/diagram-api/diagramAPI.js index 62c8843682..13ebe8ab8f 100644 --- a/src/diagram-api/diagramAPI.js +++ b/src/diagram-api/diagramAPI.js @@ -35,6 +35,7 @@ import journeyDb from '../diagrams/user-journey/journeyDb'; import journeyRenderer from '../diagrams/user-journey/journeyRenderer'; import journeyParser from '../diagrams/user-journey/parser/journey'; import { addDetector } from './detectType'; +import { log } from '../logger'; const diagrams = { c4: { @@ -165,6 +166,9 @@ const diagrams = { }; // console.log(sequenceDb); export const registerDiagram = (id, parser, db, renderer, init, detector) => { + if (diagrams[id]) { + log.warn(`Diagram ${id} already registered.`); + } diagrams[id] = { parser, db, renderer, init }; addDetector(id, detector); }; diff --git a/src/diagrams/git/gitGraphDetector.js b/src/diagrams/git/gitGraphDetector.js deleted file mode 100644 index 3707a33047..0000000000 --- a/src/diagrams/git/gitGraphDetector.js +++ /dev/null @@ -1,8 +0,0 @@ -const detector = (txt) => { - if (txt.match(/^\s*gitGraph/)) { - return 'gitGraph'; - } - return null; -}; - -export default detector; diff --git a/src/diagrams/git/gitGraphDetector.ts b/src/diagrams/git/gitGraphDetector.ts new file mode 100644 index 0000000000..08e4d8a6f4 --- /dev/null +++ b/src/diagrams/git/gitGraphDetector.ts @@ -0,0 +1,3 @@ +export const gitGraphDetector: DiagramDetector = (txt) => { + return txt.match(/^\s*gitGraph/) != null; +}; diff --git a/src/diagrams/git/gitGraphParserV2.spec.js b/src/diagrams/git/gitGraphParserV2.spec.js index b57ce1af00..fa8015fd9d 100644 --- a/src/diagrams/git/gitGraphParserV2.spec.js +++ b/src/diagrams/git/gitGraphParserV2.spec.js @@ -4,7 +4,6 @@ import gitGraphAst from './gitGraphAst'; import { parser } from './parser/gitGraph'; //import randomString from 'crypto-random-string'; //import cryptoRandomString from 'crypto-random-string'; -import { logger } from '../../logger'; //jest.mock('crypto-random-string'); diff --git a/src/diagrams/mindmap/mindamapDetector.js b/src/diagrams/mindmap/mindamapDetector.js deleted file mode 100644 index 341e3968cf..0000000000 --- a/src/diagrams/mindmap/mindamapDetector.js +++ /dev/null @@ -1,8 +0,0 @@ -const detector = (txt) => { - if (txt.match(/^\s*mindmap/)) { - return 'mindmap'; - } - return null; -}; - -export default detector; diff --git a/src/diagrams/mindmap/mindamapDetector.ts b/src/diagrams/mindmap/mindamapDetector.ts new file mode 100644 index 0000000000..b6e5d3cdeb --- /dev/null +++ b/src/diagrams/mindmap/mindamapDetector.ts @@ -0,0 +1,3 @@ +export const mindmapDetector: DiagramDetector = (txt) => { + return txt.match(/^\s*mindmap/) != null; +}; diff --git a/src/mermaidAPI.js b/src/mermaidAPI.js index 6a00e80cae..b393dd94e7 100644 --- a/src/mermaidAPI.js +++ b/src/mermaidAPI.js @@ -19,7 +19,7 @@ import { select } from 'd3'; import { compile, serialize, stringify } from 'stylis'; import pkg from '../package.json'; import * as configApi from './config'; -import addDiagrams from './diagram-api/diagram-orchestration'; +import { addDiagrams } from './diagram-api/diagram-orchestration'; import classDb from './diagrams/class/classDb'; import flowDb from './diagrams/flowchart/flowDb'; import flowRenderer from './diagrams/flowchart/flowRenderer'; diff --git a/src/types.d.ts b/src/types.d.ts new file mode 100644 index 0000000000..9570962c9c --- /dev/null +++ b/src/types.d.ts @@ -0,0 +1,7 @@ +interface ConfigType { + class?: { defaultRenderer: string }; + state?: { defaultRenderer: string }; + flowchart?: { defaultRenderer: string }; +} + +type DiagramDetector = (text: string) => boolean; diff --git a/src/utils.js b/src/utils.js index db45ab9f62..e7fc5dcb0f 100644 --- a/src/utils.js +++ b/src/utils.js @@ -16,7 +16,7 @@ import { import common from './diagrams/common/common'; import { configKeys } from './defaultConfig'; import { log } from './logger'; -import detectType from './diagram-api/detectType'; +import { detectType } from './diagram-api/detectType'; import assignWithDepth from './assignWithDepth'; // Effectively an enum of the supported curve types, accessible by name diff --git a/src/utils.spec.js b/src/utils.spec.js index 7eb3af9ff2..6db395797d 100644 --- a/src/utils.spec.js +++ b/src/utils.spec.js @@ -1,7 +1,7 @@ import utils from './utils'; import assignWithDepth from './assignWithDepth'; -import detectType from './diagram-api/detectType'; -import addDiagrams from './diagram-api/diagram-orchestration'; +import { detectType } from './diagram-api/detectType'; +import { addDiagrams } from './diagram-api/diagram-orchestration'; addDiagrams(); diff --git a/yarn.lock b/yarn.lock index 815afd3dd1..ac77dcf9dc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2305,6 +2305,14 @@ dependencies: "@types/istanbul-lib-report" "*" +"@types/jest@^28.1.7": + version "28.1.7" + resolved "https://registry.yarnpkg.com/@types/jest/-/jest-28.1.7.tgz#a680c5d05b69634c2d54a63cb106d7fb1adaba16" + integrity sha512-acDN4VHD40V24tgu0iC44jchXavRNVFXQ/E6Z5XNsswgoSO/4NgsXoEYmPUGookKldlZQyIpmrEXsHI9cA3ZTA== + dependencies: + expect "^28.0.0" + pretty-format "^28.0.0" + "@types/jsdom@^16.2.4": version "16.2.14" resolved "https://registry.yarnpkg.com/@types/jsdom/-/jsdom-16.2.14.tgz#26fe9da6a8870715b154bb84cd3b2e53433d8720" @@ -3380,6 +3388,13 @@ browserslist@^4.14.5, browserslist@^4.20.2, browserslist@^4.21.0: node-releases "^2.0.5" update-browserslist-db "^1.0.4" +bs-logger@0.x: + version "0.2.6" + resolved "https://registry.yarnpkg.com/bs-logger/-/bs-logger-0.2.6.tgz#eb7d365307a72cf974cc6cda76b68354ad336bd8" + integrity sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog== + dependencies: + fast-json-stable-stringify "2.x" + bser@2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.1.tgz#e6787da20ece9d07998533cfd9de6f5c38f4bc05" @@ -5520,7 +5535,7 @@ expand-brackets@^2.1.4: snapdragon "^0.8.1" to-regex "^3.0.1" -expect@^28.1.3: +expect@^28.0.0, expect@^28.1.3: version "28.1.3" resolved "https://registry.yarnpkg.com/expect/-/expect-28.1.3.tgz#90a7c1a124f1824133dd4533cce2d2bdcb6603ec" integrity sha512-eEh0xn8HlsuOBxFgIss+2mX85VAS4Qy3OSkjV7rlBWljtA4oWH37glVGyOZSZvErDT/yBywZdPGwCXuTvSG85g== @@ -5643,7 +5658,7 @@ fast-glob@^3.2.9: merge2 "^1.3.0" micromatch "^4.0.4" -fast-json-stable-stringify@^2.0.0: +fast-json-stable-stringify@2.x, fast-json-stable-stringify@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== @@ -7434,7 +7449,7 @@ jest-snapshot@^28.1.3: pretty-format "^28.1.3" semver "^7.3.5" -jest-util@^28.1.3: +jest-util@^28.0.0, jest-util@^28.1.3: version "28.1.3" resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-28.1.3.tgz#f4f932aa0074f0679943220ff9cbba7e497028b0" integrity sha512-XdqfpHwpcSRko/C35uLYFM2emRAltIIKZiJ9eAmhjsj0CqZMa0p1ib0R5fWIqGhn1a103DebTbpqIaP1qCQ6tQ== @@ -7966,6 +7981,11 @@ lodash.ismatch@^4.4.0: resolved "https://registry.yarnpkg.com/lodash.ismatch/-/lodash.ismatch-4.4.0.tgz#756cb5150ca3ba6f11085a78849645f188f85f37" integrity sha1-dWy1FQyjum8RCFp4hJZF8Yj4Xzc= +lodash.memoize@4.x: + version "4.1.2" + resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-4.1.2.tgz#bcc6c49a42a2840ed997f323eada5ecd182e0bfe" + integrity sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag== + lodash.merge@^4.6.1, lodash.merge@^4.6.2: version "4.6.2" resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a" @@ -8053,7 +8073,7 @@ make-dir@^3.0.0, make-dir@^3.0.2, make-dir@^3.1.0: dependencies: semver "^6.0.0" -make-error@^1.1.1: +make-error@1.x, make-error@^1.1.1: version "1.3.6" resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== @@ -9359,7 +9379,7 @@ pretty-bytes@^5.6.0: resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-5.6.0.tgz#356256f643804773c82f64723fe78c92c62beaeb" integrity sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg== -pretty-format@^28.1.3: +pretty-format@^28.0.0, pretty-format@^28.1.3: version "28.1.3" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-28.1.3.tgz#c9fba8cedf99ce50963a11b27d982a9ae90970d5" integrity sha512-8gFb/To0OmxHR9+ZTb14Df2vNxdGCX8g1xWGUTqUw5TiZvcQf5sHKObd5UcPyLLyowNwDAMTF3XWOG1B6mxl1Q== @@ -10163,7 +10183,7 @@ semver@7.0.0: resolved "https://registry.yarnpkg.com/semver/-/semver-7.0.0.tgz#5f3ca35761e47e05b206c6daff2cf814f0316b8e" integrity sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A== -semver@7.3.7, semver@^7.1.1, semver@^7.3.2, semver@^7.3.4, semver@^7.3.5, semver@^7.3.7: +semver@7.3.7, semver@7.x, semver@^7.1.1, semver@^7.3.2, semver@^7.3.4, semver@^7.3.5, semver@^7.3.7: version "7.3.7" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.7.tgz#12c5b649afdbf9049707796e22a4028814ce523f" integrity sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g== @@ -11098,6 +11118,20 @@ trough@^1.0.0: resolved "https://registry.yarnpkg.com/trough/-/trough-1.0.5.tgz#b8b639cefad7d0bb2abd37d433ff8293efa5f406" integrity sha512-rvuRbTarPXmMb79SmzEp8aqXNKcK+y0XaB298IXueQ8I2PsrATcPBCSPyK/dDNa2iWOhKlfNnOjdAOTBU/nkFA== +ts-jest@^28.0.8: + version "28.0.8" + resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-28.0.8.tgz#cd204b8e7a2f78da32cf6c95c9a6165c5b99cc73" + integrity sha512-5FaG0lXmRPzApix8oFG8RKjAz4ehtm8yMKOTy5HX3fY6W8kmvOrmcY0hKDElW52FJov+clhUbrKAqofnj4mXTg== + dependencies: + bs-logger "0.x" + fast-json-stable-stringify "2.x" + jest-util "^28.0.0" + json5 "^2.2.1" + lodash.memoize "4.x" + make-error "1.x" + semver "7.x" + yargs-parser "^21.0.1" + ts-loader@^9.3.1: version "9.3.1" resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-9.3.1.tgz#fe25cca56e3e71c1087fe48dc67f4df8c59b22d4" @@ -12059,6 +12093,11 @@ yargs-parser@^21.0.0: resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.0.0.tgz#a485d3966be4317426dd56bdb6a30131b281dc55" integrity sha512-z9kApYUOCwoeZ78rfRYYWdiU/iNL6mwwYlkkZfJoyMR1xps+NEBX5X7XmRpxkZHhXJ6+Ey00IwKxBBSW9FIjyA== +yargs-parser@^21.0.1: + version "21.1.1" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35" + integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== + yargs@17.4.1, yargs@^17.0.0, yargs@^17.3.1: version "17.4.1" resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.4.1.tgz#ebe23284207bb75cee7c408c33e722bfb27b5284" From c9cd56914f029cce36f0c8b86dbe93371a3c5d23 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 00:58:52 +0530 Subject: [PATCH 03/31] tsConversion: errorRenderer --- package.json | 1 + src/{errorRenderer.js => errorRenderer.ts} | 17 +- yarn.lock | 215 +++++++++++++++++++++ 3 files changed, 223 insertions(+), 10 deletions(-) rename src/{errorRenderer.js => errorRenderer.ts} (92%) diff --git a/package.json b/package.json index 926d56f346..94fa72e01f 100644 --- a/package.json +++ b/package.json @@ -76,6 +76,7 @@ "@babel/register": "^7.14.5", "@commitlint/cli": "^17.0.0", "@commitlint/config-conventional": "^17.0.0", + "@types/d3": "^7.4.0", "@types/jest": "^28.1.7", "babel-jest": "^28.0.3", "babel-loader": "^8.2.2", diff --git a/src/errorRenderer.js b/src/errorRenderer.ts similarity index 92% rename from src/errorRenderer.js rename to src/errorRenderer.ts index 28a9579ad0..1f2b61e2ec 100644 --- a/src/errorRenderer.js +++ b/src/errorRenderer.ts @@ -2,28 +2,24 @@ import { select } from 'd3'; import { log } from './logger'; -const conf = {}; +let conf = {}; /** * Merges the value of `conf` with the passed `cnf` * * @param {object} cnf Config to merge */ -export const setConf = function (cnf) { - const keys = Object.keys(cnf); - - keys.forEach(function (key) { - conf[key] = cnf[key]; - }); +export const setConf = function (cnf: any) { + conf = { ...conf, ...cnf }; }; /** * Draws a an info picture in the tag with id: id based on the graph definition in text. * * @param {string} id The text for the error - * @param {string} ver The version + * @param {string} mermaidVersion The version */ -export const draw = (id, ver) => { +export const draw = (id: string, mermaidVersion: string) => { try { log.debug('Renering svg for syntax error\n'); @@ -86,13 +82,14 @@ export const draw = (id, ver) => { .attr('y', 400) .attr('font-size', '100px') .style('text-anchor', 'middle') - .text('mermaid version ' + ver); + .text('mermaid version ' + mermaidVersion); svg.attr('height', 100); svg.attr('width', 400); svg.attr('viewBox', '768 0 512 512'); } catch (e) { log.error('Error while rendering info diagram'); + // @ts-ignore log.error(e.message); } }; diff --git a/yarn.lock b/yarn.lock index ac77dcf9dc..9848cc6bbb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2220,6 +2220,216 @@ dependencies: "@types/node" "*" +"@types/d3-array@*": + version "3.0.3" + resolved "https://registry.yarnpkg.com/@types/d3-array/-/d3-array-3.0.3.tgz#87d990bf504d14ad6b16766979d04e943c046dac" + integrity sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ== + +"@types/d3-axis@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-axis/-/d3-axis-3.0.1.tgz#6afc20744fa5cc0cbc3e2bd367b140a79ed3e7a8" + integrity sha512-zji/iIbdd49g9WN0aIsGcwcTBUkgLsCSwB+uH+LPVDAiKWENMtI3cJEWt+7/YYwelMoZmbBfzA3qCdrZ2XFNnw== + dependencies: + "@types/d3-selection" "*" + +"@types/d3-brush@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-brush/-/d3-brush-3.0.1.tgz#ae5f17ce391935ca88b29000e60ee20452c6357c" + integrity sha512-B532DozsiTuQMHu2YChdZU0qsFJSio3Q6jmBYGYNp3gMDzBmuFFgPt9qKA4VYuLZMp4qc6eX7IUFUEsvHiXZAw== + dependencies: + "@types/d3-selection" "*" + +"@types/d3-chord@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-chord/-/d3-chord-3.0.1.tgz#54c8856c19c8e4ab36a53f73ba737de4768ad248" + integrity sha512-eQfcxIHrg7V++W8Qxn6QkqBNBokyhdWSAS73AbkbMzvLQmVVBviknoz2SRS/ZJdIOmhcmmdCRE/NFOm28Z1AMw== + +"@types/d3-color@*": + version "3.1.0" + resolved "https://registry.yarnpkg.com/@types/d3-color/-/d3-color-3.1.0.tgz#6594da178ded6c7c3842f3cc0ac84b156f12f2d4" + integrity sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA== + +"@types/d3-contour@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-contour/-/d3-contour-3.0.1.tgz#9ff4e2fd2a3910de9c5097270a7da8a6ef240017" + integrity sha512-C3zfBrhHZvrpAAK3YXqLWVAGo87A4SvJ83Q/zVJ8rFWJdKejUnDYaWZPkA8K84kb2vDA/g90LTQAz7etXcgoQQ== + dependencies: + "@types/d3-array" "*" + "@types/geojson" "*" + +"@types/d3-delaunay@*": + version "6.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz#006b7bd838baec1511270cb900bf4fc377bbbf41" + integrity sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ== + +"@types/d3-dispatch@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-dispatch/-/d3-dispatch-3.0.1.tgz#a1b18ae5fa055a6734cb3bd3cbc6260ef19676e3" + integrity sha512-NhxMn3bAkqhjoxabVJWKryhnZXXYYVQxaBnbANu0O94+O/nX9qSjrA1P1jbAQJxJf+VC72TxDX/YJcKue5bRqw== + +"@types/d3-drag@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-drag/-/d3-drag-3.0.1.tgz#fb1e3d5cceeee4d913caa59dedf55c94cb66e80f" + integrity sha512-o1Va7bLwwk6h03+nSM8dpaGEYnoIG19P0lKqlic8Un36ymh9NSkNFX1yiXMKNMx8rJ0Kfnn2eovuFaL6Jvj0zA== + dependencies: + "@types/d3-selection" "*" + +"@types/d3-dsv@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-dsv/-/d3-dsv-3.0.0.tgz#f3c61fb117bd493ec0e814856feb804a14cfc311" + integrity sha512-o0/7RlMl9p5n6FQDptuJVMxDf/7EDEv2SYEO/CwdG2tr1hTfUVi0Iavkk2ax+VpaQ/1jVhpnj5rq1nj8vwhn2A== + +"@types/d3-ease@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-ease/-/d3-ease-3.0.0.tgz#c29926f8b596f9dadaeca062a32a45365681eae0" + integrity sha512-aMo4eaAOijJjA6uU+GIeW018dvy9+oH5Y2VPPzjjfxevvGQ/oRDs+tfYC9b50Q4BygRR8yE2QCLsrT0WtAVseA== + +"@types/d3-fetch@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-fetch/-/d3-fetch-3.0.1.tgz#f9fa88b81aa2eea5814f11aec82ecfddbd0b8fe0" + integrity sha512-toZJNOwrOIqz7Oh6Q7l2zkaNfXkfR7mFSJvGvlD/Ciq/+SQ39d5gynHJZ/0fjt83ec3WL7+u3ssqIijQtBISsw== + dependencies: + "@types/d3-dsv" "*" + +"@types/d3-force@*": + version "3.0.3" + resolved "https://registry.yarnpkg.com/@types/d3-force/-/d3-force-3.0.3.tgz#76cb20d04ae798afede1ea6e41750763ff5a9c82" + integrity sha512-z8GteGVfkWJMKsx6hwC3SiTSLspL98VNpmvLpEFJQpZPq6xpA1I8HNBDNSpukfK0Vb0l64zGFhzunLgEAcBWSA== + +"@types/d3-format@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-format/-/d3-format-3.0.1.tgz#194f1317a499edd7e58766f96735bdc0216bb89d" + integrity sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg== + +"@types/d3-geo@*": + version "3.0.2" + resolved "https://registry.yarnpkg.com/@types/d3-geo/-/d3-geo-3.0.2.tgz#e7ec5f484c159b2c404c42d260e6d99d99f45d9a" + integrity sha512-DbqK7MLYA8LpyHQfv6Klz0426bQEf7bRTvhMy44sNGVyZoWn//B0c+Qbeg8Osi2Obdc9BLLXYAKpyWege2/7LQ== + dependencies: + "@types/geojson" "*" + +"@types/d3-hierarchy@*": + version "3.1.0" + resolved "https://registry.yarnpkg.com/@types/d3-hierarchy/-/d3-hierarchy-3.1.0.tgz#4561bb7ace038f247e108295ef77b6a82193ac25" + integrity sha512-g+sey7qrCa3UbsQlMZZBOHROkFqx7KZKvUpRzI/tAp/8erZWpYq7FgNKvYwebi2LaEiVs1klhUfd3WCThxmmWQ== + +"@types/d3-interpolate@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz#e7d17fa4a5830ad56fe22ce3b4fac8541a9572dc" + integrity sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw== + dependencies: + "@types/d3-color" "*" + +"@types/d3-path@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-path/-/d3-path-3.0.0.tgz#939e3a784ae4f80b1fde8098b91af1776ff1312b" + integrity sha512-0g/A+mZXgFkQxN3HniRDbXMN79K3CdTpLsevj+PXiTcb2hVyvkZUBg37StmgCQkaD84cUJ4uaDAWq7UJOQy2Tg== + +"@types/d3-polygon@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-polygon/-/d3-polygon-3.0.0.tgz#5200a3fa793d7736fa104285fa19b0dbc2424b93" + integrity sha512-D49z4DyzTKXM0sGKVqiTDTYr+DHg/uxsiWDAkNrwXYuiZVd9o9wXZIo+YsHkifOiyBkmSWlEngHCQme54/hnHw== + +"@types/d3-quadtree@*": + version "3.0.2" + resolved "https://registry.yarnpkg.com/@types/d3-quadtree/-/d3-quadtree-3.0.2.tgz#433112a178eb7df123aab2ce11c67f51cafe8ff5" + integrity sha512-QNcK8Jguvc8lU+4OfeNx+qnVy7c0VrDJ+CCVFS9srBo2GL9Y18CnIxBdTF3v38flrGy5s1YggcoAiu6s4fLQIw== + +"@types/d3-random@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-random/-/d3-random-3.0.1.tgz#5c8d42b36cd4c80b92e5626a252f994ca6bfc953" + integrity sha512-IIE6YTekGczpLYo/HehAy3JGF1ty7+usI97LqraNa8IiDur+L44d0VOjAvFQWJVdZOJHukUJw+ZdZBlgeUsHOQ== + +"@types/d3-scale-chromatic@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.0.0.tgz#103124777e8cdec85b20b51fd3397c682ee1e954" + integrity sha512-dsoJGEIShosKVRBZB0Vo3C8nqSDqVGujJU6tPznsBJxNJNwMF8utmS83nvCBKQYPpjCzaaHcrf66iTRpZosLPw== + +"@types/d3-scale@*": + version "4.0.2" + resolved "https://registry.yarnpkg.com/@types/d3-scale/-/d3-scale-4.0.2.tgz#41be241126af4630524ead9cb1008ab2f0f26e69" + integrity sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA== + dependencies: + "@types/d3-time" "*" + +"@types/d3-selection@*": + version "3.0.3" + resolved "https://registry.yarnpkg.com/@types/d3-selection/-/d3-selection-3.0.3.tgz#57be7da68e7d9c9b29efefd8ea5a9ef1171e42ba" + integrity sha512-Mw5cf6nlW1MlefpD9zrshZ+DAWL4IQ5LnWfRheW6xwsdaWOb6IRRu2H7XPAQcyXEx1D7XQWgdoKR83ui1/HlEA== + +"@types/d3-shape@*": + version "3.1.0" + resolved "https://registry.yarnpkg.com/@types/d3-shape/-/d3-shape-3.1.0.tgz#1d87a6ddcf28285ef1e5c278ca4bdbc0658f3505" + integrity sha512-jYIYxFFA9vrJ8Hd4Se83YI6XF+gzDL1aC5DCsldai4XYYiVNdhtpGbA/GM6iyQ8ayhSp3a148LY34hy7A4TxZA== + dependencies: + "@types/d3-path" "*" + +"@types/d3-time-format@*": + version "4.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-time-format/-/d3-time-format-4.0.0.tgz#ee7b6e798f8deb2d9640675f8811d0253aaa1946" + integrity sha512-yjfBUe6DJBsDin2BMIulhSHmr5qNR5Pxs17+oW4DoVPyVIXZ+m6bs7j1UVKP08Emv6jRmYrYqxYzO63mQxy1rw== + +"@types/d3-time@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-time/-/d3-time-3.0.0.tgz#e1ac0f3e9e195135361fa1a1d62f795d87e6e819" + integrity sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg== + +"@types/d3-timer@*": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@types/d3-timer/-/d3-timer-3.0.0.tgz#e2505f1c21ec08bda8915238e397fb71d2fc54ce" + integrity sha512-HNB/9GHqu7Fo8AQiugyJbv6ZxYz58wef0esl4Mv828w1ZKpAshw/uFWVDUcIB9KKFeFKoxS3cHY07FFgtTRZ1g== + +"@types/d3-transition@*": + version "3.0.2" + resolved "https://registry.yarnpkg.com/@types/d3-transition/-/d3-transition-3.0.2.tgz#393dc3e3d55009a43cc6f252e73fccab6d78a8a4" + integrity sha512-jo5o/Rf+/u6uerJ/963Dc39NI16FQzqwOc54bwvksGAdVfvDrqDpVeq95bEvPtBwLCVZutAEyAtmSyEMxN7vxQ== + dependencies: + "@types/d3-selection" "*" + +"@types/d3-zoom@*": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@types/d3-zoom/-/d3-zoom-3.0.1.tgz#4bfc7e29625c4f79df38e2c36de52ec3e9faf826" + integrity sha512-7s5L9TjfqIYQmQQEUcpMAcBOahem7TRoSO/+Gkz02GbMVuULiZzjF2BOdw291dbO2aNon4m2OdFsRGaCq2caLQ== + dependencies: + "@types/d3-interpolate" "*" + "@types/d3-selection" "*" + +"@types/d3@^7.4.0": + version "7.4.0" + resolved "https://registry.yarnpkg.com/@types/d3/-/d3-7.4.0.tgz#fc5cac5b1756fc592a3cf1f3dc881bf08225f515" + integrity sha512-jIfNVK0ZlxcuRDKtRS/SypEyOQ6UHaFQBKv032X45VvxSJ6Yi5G9behy9h6tNTHTDGh5Vq+KbmBjUWLgY4meCA== + dependencies: + "@types/d3-array" "*" + "@types/d3-axis" "*" + "@types/d3-brush" "*" + "@types/d3-chord" "*" + "@types/d3-color" "*" + "@types/d3-contour" "*" + "@types/d3-delaunay" "*" + "@types/d3-dispatch" "*" + "@types/d3-drag" "*" + "@types/d3-dsv" "*" + "@types/d3-ease" "*" + "@types/d3-fetch" "*" + "@types/d3-force" "*" + "@types/d3-format" "*" + "@types/d3-geo" "*" + "@types/d3-hierarchy" "*" + "@types/d3-interpolate" "*" + "@types/d3-path" "*" + "@types/d3-polygon" "*" + "@types/d3-quadtree" "*" + "@types/d3-random" "*" + "@types/d3-scale" "*" + "@types/d3-scale-chromatic" "*" + "@types/d3-selection" "*" + "@types/d3-shape" "*" + "@types/d3-time" "*" + "@types/d3-time-format" "*" + "@types/d3-timer" "*" + "@types/d3-transition" "*" + "@types/d3-zoom" "*" + "@types/debug@^4.0.0": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82" @@ -2267,6 +2477,11 @@ "@types/qs" "*" "@types/serve-static" "*" +"@types/geojson@*": + version "7946.0.10" + resolved "https://registry.yarnpkg.com/@types/geojson/-/geojson-7946.0.10.tgz#6dfbf5ea17142f7f9a043809f1cd4c448cb68249" + integrity sha512-Nmh0K3iWQJzniTuPRcJn5hxXkfB1T1pgB89SBig5PlJQU5yocazeu4jATJlaA0GYFKWMqDdvYemoSnF2pXgLVA== + "@types/graceful-fs@^4.1.3": version "4.1.5" resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.5.tgz#21ffba0d98da4350db64891f92a9e5db3cdb4e15" From 896154d89f4ea87f7887f723c462554246642df2 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 00:59:54 +0530 Subject: [PATCH 04/31] tsConversion: logger --- src/{interactionDb.js => interactionDb.ts} | 4 +-- src/{logger.js => logger.ts} | 41 +++++++++++----------- 2 files changed, 22 insertions(+), 23 deletions(-) rename src/{interactionDb.js => interactionDb.ts} (63%) rename src/{logger.js => logger.ts} (62%) diff --git a/src/interactionDb.js b/src/interactionDb.ts similarity index 63% rename from src/interactionDb.js rename to src/interactionDb.ts index 147837232c..379685c83f 100644 --- a/src/interactionDb.js +++ b/src/interactionDb.ts @@ -1,5 +1,5 @@ -let interactionFunctions = []; -export const addFunction = (func) => { +let interactionFunctions: (() => {})[] = []; +export const addFunction = (func: () => {}) => { interactionFunctions.push(func); }; export const attachFunctions = () => { diff --git a/src/logger.js b/src/logger.ts similarity index 62% rename from src/logger.js rename to src/logger.ts index 557bb15cee..a57285c7bc 100644 --- a/src/logger.js +++ b/src/logger.ts @@ -1,9 +1,8 @@ import moment from 'moment-mini'; -/** @typedef {'debug' | 'info' | 'warn' | 'error' | 'fatal'} LogLevel A log level */ +export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; -/** @type {Object} */ -export const LEVELS = { +export const LEVELS: Record = { debug: 1, info: 2, warn: 3, @@ -11,12 +10,12 @@ export const LEVELS = { fatal: 5, }; -export const log = { - debug: (...args) => {}, - info: (...args) => {}, - warn: (...args) => {}, - error: (...args) => {}, - fatal: (...args) => {}, +export const log: Record = { + debug: (..._args: any[]) => {}, + info: (..._args: any[]) => {}, + warn: (..._args: any[]) => {}, + error: (..._args: any[]) => {}, + fatal: (..._args: any[]) => {}, }; /** @@ -24,40 +23,40 @@ export const log = { * * @param {LogLevel} [level="fatal"] The level to set the logging to. Default is `"fatal"` */ -export const setLogLevel = function (level = 'fatal') { - if (isNaN(level)) { +export const setLogLevel = function (level: keyof typeof LEVELS | number | string = 'fatal') { + let numericLevel: number = LEVELS.fatal; + if (typeof level === 'string') { level = level.toLowerCase(); - if (LEVELS[level] !== undefined) { - level = LEVELS[level]; + if (level in LEVELS) { + numericLevel = LEVELS[level as keyof typeof LEVELS]; } } - log.trace = () => {}; log.debug = () => {}; log.info = () => {}; log.warn = () => {}; log.error = () => {}; log.fatal = () => {}; - if (level <= LEVELS.fatal) { + if (numericLevel <= LEVELS.fatal) { log.fatal = console.error ? console.error.bind(console, format('FATAL'), 'color: orange') : console.log.bind(console, '\x1b[35m', format('FATAL')); } - if (level <= LEVELS.error) { + if (numericLevel <= LEVELS.error) { log.error = console.error ? console.error.bind(console, format('ERROR'), 'color: orange') : console.log.bind(console, '\x1b[31m', format('ERROR')); } - if (level <= LEVELS.warn) { + if (numericLevel <= LEVELS.warn) { log.warn = console.warn ? console.warn.bind(console, format('WARN'), 'color: orange') : console.log.bind(console, `\x1b[33m`, format('WARN')); } - if (level <= LEVELS.info) { - log.info = console.info // ? console.info.bind(console, '\x1b[34m', format('INFO'), 'color: blue') + if (numericLevel <= LEVELS.info) { + log.info = console.info ? console.info.bind(console, format('INFO'), 'color: lightblue') : console.log.bind(console, '\x1b[34m', format('INFO')); } - if (level <= LEVELS.debug) { + if (numericLevel <= LEVELS.debug) { log.debug = console.debug ? console.debug.bind(console, format('DEBUG'), 'color: lightgreen') : console.log.bind(console, '\x1b[32m', format('DEBUG')); @@ -70,7 +69,7 @@ export const setLogLevel = function (level = 'fatal') { * @param {LogLevel} level The level for the log format * @returns {string} The format with the timestamp and log level */ -const format = (level) => { +const format = (level: string): string => { const time = moment().format('ss.SSS'); return `%c${time} : ${level} : `; }; From fab96881353ff22062aa8000d351759a1a2d50a5 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 01:21:47 +0530 Subject: [PATCH 05/31] tsConversion: flowchartStyles --- .../flowchart/{styles.js => styles.ts} | 40 +++++++++---------- 1 file changed, 18 insertions(+), 22 deletions(-) rename src/diagrams/flowchart/{styles.js => styles.ts} (77%) diff --git a/src/diagrams/flowchart/styles.js b/src/diagrams/flowchart/styles.ts similarity index 77% rename from src/diagrams/flowchart/styles.js rename to src/diagrams/flowchart/styles.ts index abaecb0b41..82fb1f8759 100644 --- a/src/diagrams/flowchart/styles.js +++ b/src/diagrams/flowchart/styles.ts @@ -1,25 +1,21 @@ -/** - * Returns the styles given options - * - * @param {{ - * fontFamily: string; - * nodeTextColor: string; - * textColor: string; - * titleColor: string; - * mainBkg: string; - * nodeBorder: string; - * arrowheadColor: string; - * lineColor: string; - * edgeLabelBackground: string; - * clusterBkg: string; - * clusterBorder: string; - * tertiaryColor: string; - * border2: string; - * }} options - * The options for the styles - * @returns {string} The resulting styles - */ -const getStyles = (options) => +/** Returns the styles given options */ +export interface FlowChartStyleOptions { + arrowheadColor: string; + border2: string; + clusterBkg: string; + clusterBorder: string; + edgeLabelBackground: string; + fontFamily: string; + lineColor: string; + mainBkg: string; + nodeBorder: string; + nodeTextColor: string; + tertiaryColor: string; + textColor: string; + titleColor: string; +} + +const getStyles = (options: FlowChartStyleOptions) => `.label { font-family: ${options.fontFamily}; color: ${options.nodeTextColor || options.textColor}; From d9bace053b9105bfed99b00a244d20273601927b Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 08:45:17 +0530 Subject: [PATCH 06/31] Add `trace` logLevel --- src/logger.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/logger.ts b/src/logger.ts index a57285c7bc..195cde7f3d 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,8 +1,9 @@ import moment from 'moment-mini'; -export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; +export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'; export const LEVELS: Record = { + trace: 0, debug: 1, info: 2, warn: 3, @@ -11,6 +12,7 @@ export const LEVELS: Record = { }; export const log: Record = { + trace: (..._args: any[]) => {}, debug: (..._args: any[]) => {}, info: (..._args: any[]) => {}, warn: (..._args: any[]) => {}, @@ -31,6 +33,7 @@ export const setLogLevel = function (level: keyof typeof LEVELS | number | strin numericLevel = LEVELS[level as keyof typeof LEVELS]; } } + log.trace = () => {}; log.debug = () => {}; log.info = () => {}; log.warn = () => {}; @@ -61,6 +64,11 @@ export const setLogLevel = function (level: keyof typeof LEVELS | number | strin ? console.debug.bind(console, format('DEBUG'), 'color: lightgreen') : console.log.bind(console, '\x1b[32m', format('DEBUG')); } + if (numericLevel <= LEVELS.trace) { + log.trace = console.debug + ? console.debug.bind(console, format('TRACE'), 'color: lightgreen') + : console.log.bind(console, '\x1b[32m', format('TRACE')); + } }; /** From 238cbd14ca98d7218b9c9ca95147a0b6e1477833 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 08:54:27 +0530 Subject: [PATCH 07/31] tsConversion: styles --- src/{styles.js => styles.ts} | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) rename src/{styles.js => styles.ts} (67%) diff --git a/src/styles.js b/src/styles.ts similarity index 67% rename from src/styles.js rename to src/styles.ts index 15e804ef98..54266ff9af 100644 --- a/src/styles.js +++ b/src/styles.ts @@ -10,8 +10,10 @@ import sequence from './diagrams/sequence/styles'; import stateDiagram from './diagrams/state/styles'; import journey from './diagrams/user-journey/styles'; import c4 from './diagrams/c4/styles'; +import { FlowChartStyleOptions } from './diagrams/flowchart/styles'; import { log } from './logger'; +// TODO Q: Shouldn't registerDiagram be injecting data here? const themes = { flowchart, 'flowchart-v2': flowchart, @@ -31,12 +33,30 @@ const themes = { c4, }; -export const calcThemeVariables = (theme, userOverRides) => { - log.info('userOverides', userOverRides); - return theme.calcColors(userOverRides); -}; +// TODO: Delete as it's not used +// export const calcThemeVariables = (theme: string, userOverRides) => { +// log.info('userOverides', userOverRides); +// return theme.calcColors(userOverRides); +// }; -const getStyles = (type, userStyles, options) => { +const getStyles = ( + type: string, + userStyles: string, + options: { + fontFamily: string; + fontSize: string; + textColor: string; + errorBkgColor: string; + errorTextColor: string; + lineColor: string; + } & FlowChartStyleOptions +) => { + let diagramStyles: string = ''; + if (type in themes && themes[type as keyof typeof themes]) { + diagramStyles = themes[type as keyof typeof themes](options); + } else { + log.warn(`No theme found for ${type}`); + } return ` { font-family: ${options.fontFamily}; font-size: ${options.fontSize}; @@ -83,7 +103,7 @@ const getStyles = (type, userStyles, options) => { font-size: ${options.fontSize}; } - ${themes[type](options)} + ${diagramStyles} ${userStyles} `; From 6de66eaba38607d92793b5833606297760b54da6 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 09:42:30 +0530 Subject: [PATCH 08/31] Add `trace` logLevel --- docs/Setup.md | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/docs/Setup.md b/docs/Setup.md index 85070a1e72..1092520fa3 100644 --- a/docs/Setup.md +++ b/docs/Setup.md @@ -58,17 +58,10 @@ Theme , the CSS style sheet ## logLevel -| Parameter | Description | Type | Required | Values | -| --------- | ----------------------------------------------------- | ---------------- | -------- | ------------- | -| logLevel | This option decides the amount of logging to be used. | string \| number | Required | 1, 2, 3, 4, 5 | +| Parameter | Description | Type | Required | Values | +| --------- | ----------------------------------------------------- | ---------------- | -------- | -------------------------------------------------- | +| logLevel | This option decides the amount of logging to be used. | string \| number | Required | 'trace', 'debug', 'info', 'warn', 'error', 'fatal' | -**Notes:** - -- Debug: 1 -- Info: 2 -- Warn: 3 -- Error: 4 -- Fatal: 5 (default) ## securityLevel From f14f0d9857c60131f79e2c2ca35d99f4a2bb2bb8 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 11:00:22 +0530 Subject: [PATCH 09/31] tsConversion: config & common --- .webpack/webpack.config.base.js | 5 +- .webpack/webpack.config.e2e.babel.js | 2 +- package.json | 2 + src/@types/config.d.ts | 342 +++++++++++++++++++ src/@types/types.d.ts | 1 + src/{commonDb.js => commonDb.ts} | 16 +- src/{defaultConfig.js => defaultConfig.ts} | 21 +- src/diagram-api/detectType.ts | 4 +- src/diagrams/common/{common.js => common.ts} | 81 ++--- src/{mermaid.js => mermaid.ts} | 28 +- src/types.d.ts | 7 - src/utils.js | 1 + tsconfig.json | 35 +- yarn.lock | 169 ++++++++- 14 files changed, 605 insertions(+), 109 deletions(-) create mode 100644 src/@types/config.d.ts create mode 100644 src/@types/types.d.ts rename src/{commonDb.js => commonDb.ts} (57%) rename src/{defaultConfig.js => defaultConfig.ts} (98%) rename src/diagrams/common/{common.js => common.ts} (64%) rename src/{mermaid.js => mermaid.ts} (91%) delete mode 100644 src/types.d.ts diff --git a/.webpack/webpack.config.base.js b/.webpack/webpack.config.base.js index 25dfbffcc5..24db2a4f36 100644 --- a/.webpack/webpack.config.base.js +++ b/.webpack/webpack.config.base.js @@ -1,12 +1,12 @@ import path from 'path'; - +const { TsConfigPathsPlugin } = require('awesome-typescript-loader'); export const resolveRoot = (...relativePath) => path.resolve(__dirname, '..', ...relativePath); export default { amd: false, // https://github.com/lodash/lodash/issues/3052 target: 'web', entry: { - mermaid: './src/mermaid.js', + mermaid: './src/mermaid.ts', }, resolve: { extensions: ['.wasm', '.mjs', '.js', '.ts', '.json', '.jison'], @@ -14,6 +14,7 @@ export default { fs: false, // jison generated code requires 'fs' path: require.resolve('path-browserify'), }, + plugins: [new TsConfigPathsPlugin()], }, output: { path: resolveRoot('./dist'), diff --git a/.webpack/webpack.config.e2e.babel.js b/.webpack/webpack.config.e2e.babel.js index 3ec2bdcd78..b9c5b77330 100644 --- a/.webpack/webpack.config.e2e.babel.js +++ b/.webpack/webpack.config.e2e.babel.js @@ -4,7 +4,7 @@ import { merge } from 'webpack-merge'; export default merge(baseConfig, { mode: 'development', entry: { - mermaid: './src/mermaid.js', + mermaid: './src/mermaid.ts', e2e: './cypress/platform/viewer.js', 'bundle-test': './cypress/platform/bundle-test.js', }, diff --git a/package.json b/package.json index 94fa72e01f..9aceb65683 100644 --- a/package.json +++ b/package.json @@ -77,7 +77,9 @@ "@commitlint/cli": "^17.0.0", "@commitlint/config-conventional": "^17.0.0", "@types/d3": "^7.4.0", + "@types/dompurify": "^2.3.3", "@types/jest": "^28.1.7", + "awesome-typescript-loader": "^5.2.1", "babel-jest": "^28.0.3", "babel-loader": "^8.2.2", "concurrently": "^7.0.0", diff --git a/src/@types/config.d.ts b/src/@types/config.d.ts new file mode 100644 index 0000000000..2e947273d1 --- /dev/null +++ b/src/@types/config.d.ts @@ -0,0 +1,342 @@ +// TODO: This was auto generated from defaultConfig. Needs to be verified. + +import DOMPurify from 'dompurify'; + +export interface MermaidConfig { + theme?: string; + themeVariables?: any; + themeCSS?: string; + maxTextSize?: number; + darkMode?: boolean; + fontFamily?: string; + logLevel?: number; + securityLevel?: string; + startOnLoad?: boolean; + arrowMarkerAbsolute?: boolean; + secure?: string[]; + deterministicIds?: boolean; + deterministicIDSeed?: string; + flowchart?: FlowchartDiagramConfig; + sequence?: SequenceDiagramConfig; + gantt?: GanttDiagramConfig; + journey?: JourneyDiagramConfig; + class?: ClassDiagramConfig; + state?: StateDiagramConfig; + er?: ErDiagramConfig; + pie?: PieDiagramConfig; + requirement?: RequirementDiagramConfig; + gitGraph?: GitGraphDiagramConfig; + c4?: C4DiagramConfig; + dompurifyConfig?: DOMPurify.Config; +} + +// TODO: More configs needs to be moved in here +export interface BaseDiagramConfig extends BaseDiagramConfig { + useWidth?: number; + useMaxWidth?: boolean; +} + +export interface C4DiagramConfig extends BaseDiagramConfig { + diagramMarginX?: number; + diagramMarginY?: number; + c4ShapeMargin?: number; + c4ShapePadding?: number; + width?: number; + height?: number; + boxMargin?: number; + c4ShapeInRow?: number; + nextLinePaddingX?: number; + c4BoundaryInRow?: number; + personFontSize?: string | number; + personFontFamily?: string; + personFontWeight?: string | number; + external_personFontSize?: string | number; + external_personFontFamily?: string; + external_personFontWeight?: string | number; + systemFontSize?: string | number; + systemFontFamily?: string; + systemFontWeight?: string | number; + external_systemFontSize?: string | number; + external_systemFontFamily?: string; + external_systemFontWeight?: string | number; + system_dbFontSize?: string | number; + system_dbFontFamily?: string; + system_dbFontWeight?: string | number; + external_system_dbFontSize?: string | number; + external_system_dbFontFamily?: string; + external_system_dbFontWeight?: string | number; + system_queueFontSize?: string | number; + system_queueFontFamily?: string; + system_queueFontWeight?: string | number; + external_system_queueFontSize?: string | number; + external_system_queueFontFamily?: string; + external_system_queueFontWeight?: string | number; + boundaryFontSize?: string | number; + boundaryFontFamily?: string; + boundaryFontWeight?: string | number; + messageFontSize?: string | number; + messageFontFamily?: string; + messageFontWeight?: string | number; + containerFontSize?: string | number; + containerFontFamily?: string; + containerFontWeight?: string | number; + external_containerFontSize?: string | number; + external_containerFontFamily?: string; + external_containerFontWeight?: string | number; + container_dbFontSize?: string | number; + container_dbFontFamily?: string; + container_dbFontWeight?: string | number; + external_container_dbFontSize?: string | number; + external_container_dbFontFamily?: string; + external_container_dbFontWeight?: string | number; + container_queueFontSize?: string | number; + container_queueFontFamily?: string; + container_queueFontWeight?: string | number; + external_container_queueFontSize?: string | number; + external_container_queueFontFamily?: string; + external_container_queueFontWeight?: string | number; + componentFontSize?: string | number; + componentFontFamily?: string; + componentFontWeight?: string | number; + external_componentFontSize?: string | number; + external_componentFontFamily?: string; + external_componentFontWeight?: string | number; + component_dbFontSize?: string | number; + component_dbFontFamily?: string; + component_dbFontWeight?: string | number; + external_component_dbFontSize?: string | number; + external_component_dbFontFamily?: string; + external_component_dbFontWeight?: string | number; + component_queueFontSize?: string | number; + component_queueFontFamily?: string; + component_queueFontWeight?: string | number; + external_component_queueFontSize?: string | number; + external_component_queueFontFamily?: string; + external_component_queueFontWeight?: string | number; + wrap?: boolean; + wrapPadding?: number; + person_bg_color?: string; + person_border_color?: string; + external_person_bg_color?: string; + external_person_border_color?: string; + system_bg_color?: string; + system_border_color?: string; + system_db_bg_color?: string; + system_db_border_color?: string; + system_queue_bg_color?: string; + system_queue_border_color?: string; + external_system_bg_color?: string; + external_system_border_color?: string; + external_system_db_bg_color?: string; + external_system_db_border_color?: string; + external_system_queue_bg_color?: string; + external_system_queue_border_color?: string; + container_bg_color?: string; + container_border_color?: string; + container_db_bg_color?: string; + container_db_border_color?: string; + container_queue_bg_color?: string; + container_queue_border_color?: string; + external_container_bg_color?: string; + external_container_border_color?: string; + external_container_db_bg_color?: string; + external_container_db_border_color?: string; + external_container_queue_bg_color?: string; + external_container_queue_border_color?: string; + component_bg_color?: string; + component_border_color?: string; + component_db_bg_color?: string; + component_db_border_color?: string; + component_queue_bg_color?: string; + component_queue_border_color?: string; + external_component_bg_color?: string; + external_component_border_color?: string; + external_component_db_bg_color?: string; + external_component_db_border_color?: string; + external_component_queue_bg_color?: string; + external_component_queue_border_color?: string; + personFont?: FontCalculator; + external_personFont?: FontCalculator; + systemFont?: FontCalculator; + external_systemFont?: FontCalculator; + system_dbFont?: FontCalculator; + external_system_dbFont?: FontCalculator; + system_queueFont?: FontCalculator; + external_system_queueFont?: FontCalculator; + containerFont?: FontCalculator; + external_containerFont?: FontCalculator; + container_dbFont?: FontCalculator; + external_container_dbFont?: FontCalculator; + container_queueFont?: FontCalculator; + external_container_queueFont?: FontCalculator; + componentFont?: FontCalculator; + external_componentFont?: FontCalculator; + component_dbFont?: FontCalculator; + external_component_dbFont?: FontCalculator; + component_queueFont?: FontCalculator; + external_component_queueFont?: FontCalculator; + boundaryFont?: FontCalculator; + messageFont?: FontCalculator; +} + +export interface GitGraphDiagramConfig extends BaseDiagramConfig { + diagramPadding?: number; + nodeLabel?: NodeLabel; + mainBranchName?: string; + mainBranchOrder?: number; + showCommitLabel?: boolean; + showBranches?: boolean; + rotateCommitLabel?: boolean; + arrowMarkerAbsolute?: boolean; +} + +export interface NodeLabel { + width?: number; + height?: number; + x?: number; + y?: number; +} + +export interface RequirementDiagramConfig extends BaseDiagramConfig { + rect_fill?: string; + text_color?: string; + rect_border_size?: string; + rect_border_color?: string; + rect_min_width?: number; + rect_min_height?: number; + fontSize?: number; + rect_padding?: number; + line_height?: number; +} + +export interface PieDiagramConfig extends BaseDiagramConfig {} + +export interface ErDiagramConfig extends BaseDiagramConfig { + diagramPadding?: number; + layoutDirection?: string; + minEntityWidth?: number; + minEntityHeight?: number; + entityPadding?: number; + stroke?: string; + fill?: string; + fontSize?: number; +} + +export interface StateDiagramConfig extends BaseDiagramConfig { + dividerMargin?: number; + sizeUnit?: number; + padding?: number; + textHeight?: number; + titleShift?: number; + noteMargin?: number; + forkWidth?: number; + forkHeight?: number; + miniPadding?: number; + fontSizeFactor?: number; + fontSize?: number; + labelHeight?: number; + edgeLengthFactor?: string; + compositTitleSize?: number; + radius?: number; + defaultRenderer?: string; +} + +export interface ClassDiagramConfig extends BaseDiagramConfig { + arrowMarkerAbsolute?: boolean; + dividerMargin?: number; + padding?: number; + textHeight?: number; + defaultRenderer?: string; +} + +export interface JourneyDiagramConfig extends BaseDiagramConfig { + diagramMarginX?: number; + diagramMarginY?: number; + leftMargin?: number; + width?: number; + height?: number; + boxMargin?: number; + boxTextMargin?: number; + noteMargin?: number; + messageMargin?: number; + messageAlign?: string; + bottomMarginAdj?: number; + rightAngles?: boolean; + taskFontSize?: string | number; + taskFontFamily?: string; + taskMargin?: number; + activationWidth?: number; + textPlacement?: string; + actorColours?: string[]; + sectionFills?: string[]; + sectionColours?: string[]; +} + +export interface GanttDiagramConfig extends BaseDiagramConfig { + titleTopMargin?: number; + barHeight?: number; + barGap?: number; + topPadding?: number; + rightPadding?: number; + leftPadding?: number; + gridLineStartPadding?: number; + fontSize?: number; + sectionFontSize?: string | number; + numberSectionStyles?: number; + axisFormat?: string; + topAxis?: boolean; +} + +export interface SequenceDiagramConfig extends BaseDiagramConfig { + hideUnusedParticipants?: boolean; + activationWidth?: number; + diagramMarginX?: number; + diagramMarginY?: number; + actorMargin?: number; + width?: number; + height?: number; + boxMargin?: number; + boxTextMargin?: number; + noteMargin?: number; + messageMargin?: number; + messageAlign?: string; + mirrorActors?: boolean; + forceMenus?: boolean; + bottomMarginAdj?: number; + rightAngles?: boolean; + showSequenceNumbers?: boolean; + actorFontSize?: string | number; + actorFontFamily?: string; + actorFontWeight?: string | number; + noteFontSize?: string | number; + noteFontFamily?: string; + noteFontWeight?: string | number; + noteAlign?: string; + messageFontSize?: string | number; + messageFontFamily?: string; + messageFontWeight?: string | number; + wrap?: boolean; + wrapPadding?: number; + labelBoxWidth?: number; + labelBoxHeight?: number; + messageFont?: FontCalculator; + noteFont?: FontCalculator; + actorFont?: FontCalculator; +} + +export interface FlowchartDiagramConfig extends BaseDiagramConfig { + diagramPadding?: number; + htmlLabels?: boolean; + nodeSpacing?: number; + rankSpacing?: number; + curve?: string; + padding?: number; + defaultRenderer?: string; +} + +export interface FontConfig { + fontSize?: string | number; + fontFamily?: string; + fontWeight?: string | number; +} +export type FontCalculator = () => Partial; diff --git a/src/@types/types.d.ts b/src/@types/types.d.ts new file mode 100644 index 0000000000..24318d1d32 --- /dev/null +++ b/src/@types/types.d.ts @@ -0,0 +1 @@ +type DiagramDetector = (text: string) => boolean; diff --git a/src/commonDb.js b/src/commonDb.ts similarity index 57% rename from src/commonDb.js rename to src/commonDb.ts index 90e99facae..42ffde0044 100644 --- a/src/commonDb.js +++ b/src/commonDb.ts @@ -3,35 +3,35 @@ import { getConfig } from './config'; let title = ''; let diagramTitle = ''; let description = ''; -const sanitizeText = (txt) => _sanitizeText(txt, getConfig()); +const sanitizeText = (txt: string): string => _sanitizeText(txt, getConfig()); -export const clear = function () { +export const clear = function (): void { title = ''; description = ''; diagramTitle = ''; }; -export const setAccTitle = function (txt) { +export const setAccTitle = function (txt: string): void { title = sanitizeText(txt).replace(/^\s+/g, ''); }; -export const getAccTitle = function () { +export const getAccTitle = function (): string { return title || diagramTitle; }; -export const setAccDescription = function (txt) { +export const setAccDescription = function (txt: string): void { description = sanitizeText(txt).replace(/\n\s+/g, '\n'); }; -export const getAccDescription = function () { +export const getAccDescription = function (): string { return description; }; -export const setDiagramTitle = function (txt) { +export const setDiagramTitle = function (txt: string): void { diagramTitle = sanitizeText(txt); }; -export const getDiagramTitle = function () { +export const getDiagramTitle = function (): string { return diagramTitle; }; diff --git a/src/defaultConfig.js b/src/defaultConfig.ts similarity index 98% rename from src/defaultConfig.js rename to src/defaultConfig.ts index acf85055ff..8328510b7b 100644 --- a/src/defaultConfig.js +++ b/src/defaultConfig.ts @@ -1,4 +1,5 @@ import theme from './themes'; +import { MermaidConfig } from 'types/config'; /** * **Configuration methods in Mermaid version 8.6.0 have been updated, to learn more[[click * here](8.6.0_docs.md)].** @@ -21,7 +22,7 @@ import theme from './themes'; * * @name Configuration */ -const config = { +const config: Partial = { /** * Theme , the CSS style sheet * @@ -49,12 +50,13 @@ const config = { fontFamily: '"trebuchet ms", verdana, arial, sans-serif;', /** - * | Parameter | Description | Type | Required | Values | - * | --------- | ----------------------------------------------------- | ---------------- | -------- | ------------- | - * | logLevel | This option decides the amount of logging to be used. | string \| number | Required | 1, 2, 3, 4, 5 | + * | Parameter | Description | Type | Required | Values | + * | --------- | ----------------------------------------------------- | ---------------- | -------- | --------------------------------------------- | + * | logLevel | This option decides the amount of logging to be used. | string \| number | Required | 'trace','debug','info','warn','error','fatal' | * * **Notes:** * + * - Trace: 0 * - Debug: 1 * - Info: 2 * - Warn: 3 @@ -1820,11 +1822,12 @@ const config = { }, }; -config.class.arrowMarkerAbsolute = config.arrowMarkerAbsolute; -config.gitGraph.arrowMarkerAbsolute = config.arrowMarkerAbsolute; +console.log(JSON.stringify(config)); +if (config.class) config.class.arrowMarkerAbsolute = config.arrowMarkerAbsolute; +if (config.gitGraph) config.gitGraph.arrowMarkerAbsolute = config.arrowMarkerAbsolute; -const keyify = (obj, prefix = '') => - Object.keys(obj).reduce((res, el) => { +const keyify = (obj: any, prefix = ''): string[] => + Object.keys(obj).reduce((res: string[], el): string[] => { if (Array.isArray(obj[el])) { return res; } else if (typeof obj[el] === 'object' && obj[el] !== null) { @@ -1833,5 +1836,5 @@ const keyify = (obj, prefix = '') => return [...res, prefix + el]; }, []); -export const configKeys = keyify(config, ''); +export const configKeys: string[] = keyify(config, ''); export default config; diff --git a/src/diagram-api/detectType.ts b/src/diagram-api/detectType.ts index 417d3ace4d..3a3250aa04 100644 --- a/src/diagram-api/detectType.ts +++ b/src/diagram-api/detectType.ts @@ -1,3 +1,5 @@ +import type { MermaidConfig } from 'types/config'; + const directive = /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi; const anyComment = /\s*%%.*\n/gm; @@ -41,7 +43,7 @@ const diagramMatchers: Record = { * }} [cnf] * @returns {string} A graph definition key */ -export const detectType = function (text: string, cnf: ConfigType): string { +export const detectType = function (text: string, cnf: MermaidConfig): string { text = text.replace(directive, '').replace(anyComment, '\n'); for (const [diagram, matcher] of Object.entries(diagramMatchers)) { if (text.match(matcher)) { diff --git a/src/diagrams/common/common.js b/src/diagrams/common/common.ts similarity index 64% rename from src/diagrams/common/common.js rename to src/diagrams/common/common.ts index b4a3411694..2d1d06bbc4 100644 --- a/src/diagrams/common/common.js +++ b/src/diagrams/common/common.ts @@ -1,19 +1,19 @@ import DOMPurify from 'dompurify'; +import { MermaidConfig } from 'types/config'; /** - * Gets the number of lines in a string + * Gets the rows of lines in a string * * @param {string | undefined} s The string to check the lines for - * @returns {number} The number of lines in that string + * @returns {string[]} The rows in that string */ -export const getRows = (s) => { - if (!s) return 1; - let str = breakToPlaceholder(s); - str = str.replace(/\\n/g, '#br#'); +export const getRows = (s?: string): string[] => { + if (!s) return ['']; + const str = breakToPlaceholder(s).replace(/\\n/g, '#br#'); return str.split('#br#'); }; -export const removeEscapes = (text) => { +export const removeEscapes = (text: string): string => { let newStr = text.replace(/\\u[\dA-F]{4}/gi, function (match) { return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16)); }); @@ -35,7 +35,7 @@ export const removeEscapes = (text) => { * @param {string} txt The text to sanitize * @returns {string} The safer text */ -export const removeScript = (txt) => { +export const removeScript = (txt: string): string => { var rs = ''; var idx = 0; @@ -65,49 +65,39 @@ export const removeScript = (txt) => { return decodedText; }; -const sanitizeMore = (text, config) => { - let txt = text; - let htmlLabels = true; - if ( - config.flowchart && - (config.flowchart.htmlLabels === false || config.flowchart.htmlLabels === 'false') - ) { - htmlLabels = false; - } - - if (htmlLabels) { +const sanitizeMore = (text: string, config: MermaidConfig) => { + // TODO Q: Should this check really be here? Feels like we should be sanitizing it regardless. + if (config.flowchart?.htmlLabels !== false) { const level = config.securityLevel; - if (level === 'antiscript' || level === 'strict') { - txt = removeScript(txt); + text = removeScript(text); } else if (level !== 'loose') { - // eslint-disable-line - txt = breakToPlaceholder(txt); - txt = txt.replace(//g, '>'); - txt = txt.replace(/=/g, '='); - txt = placeholderToBreak(txt); + text = breakToPlaceholder(text); + text = text.replace(//g, '>'); + text = text.replace(/=/g, '='); + text = placeholderToBreak(text); } } - - return txt; + return text; }; -export const sanitizeText = (text, config) => { +export const sanitizeText = (text: string, config: MermaidConfig): string => { if (!text) return text; - let txt = ''; - if (config['dompurifyConfig']) { - txt = DOMPurify.sanitize(sanitizeMore(text, config), config['dompurifyConfig']); + if (config.dompurifyConfig) { + text = DOMPurify.sanitize(sanitizeMore(text, config), config.dompurifyConfig).toString(); } else { - txt = DOMPurify.sanitize(sanitizeMore(text, config)); + text = DOMPurify.sanitize(sanitizeMore(text, config)); } - return txt; + return text; }; -export const sanitizeTextOrArray = (a, config) => { +export const sanitizeTextOrArray = ( + a: string | string[] | string[][], + config: MermaidConfig +): string | string[] => { if (typeof a === 'string') return sanitizeText(a, config); - - const f = (x) => sanitizeText(x, config); - return a.flat().map(f); + // TODO Q: Do we need flat? + return a.flat().map((x: string) => sanitizeText(x, config)); }; export const lineBreakRegex = //gi; @@ -118,7 +108,7 @@ export const lineBreakRegex = //gi; * @param {string} text The text to test * @returns {boolean} Whether or not the text has breaks */ -export const hasBreaks = (text) => { +export const hasBreaks = (text: string): boolean => { return lineBreakRegex.test(text); }; @@ -128,7 +118,7 @@ export const hasBreaks = (text) => { * @param {string} text Text to split * @returns {string[]} List of lines as strings */ -export const splitBreaks = (text) => { +export const splitBreaks = (text: string): string[] => { return text.split(lineBreakRegex); }; @@ -138,7 +128,7 @@ export const splitBreaks = (text) => { * @param {string} s HTML with placeholders * @returns {string} HTML with breaks instead of placeholders */ -const placeholderToBreak = (s) => { +const placeholderToBreak = (s: string): string => { return s.replace(/#br#/g, '
'); }; @@ -148,7 +138,7 @@ const placeholderToBreak = (s) => { * @param {string} s HTML string * @returns {string} String with placeholders */ -const breakToPlaceholder = (s) => { +const breakToPlaceholder = (s: string): string => { return s.replace(lineBreakRegex, '#br#'); }; @@ -158,8 +148,9 @@ const breakToPlaceholder = (s) => { * @param {boolean} useAbsolute Whether to return the absolute URL or not * @returns {string} The current URL */ -const getUrl = (useAbsolute) => { +const getUrl = (useAbsolute: boolean): string => { let url = ''; + // TODO Q: If useAbsolute if false, empty string is returned. Bug? if (useAbsolute) { url = window.location.protocol + @@ -180,7 +171,9 @@ const getUrl = (useAbsolute) => { * @param {string | boolean} val String or boolean to convert * @returns {boolean} The result from the input */ -export const evaluate = (val) => (val === 'false' || val === false ? false : true); +// TODO Q: Should we make this check more specific? 'False', '0', 'null' all will evaluate to true. +export const evaluate = (val: string | boolean): boolean => + val === 'false' || val === false ? false : true; export default { getRows, diff --git a/src/mermaid.js b/src/mermaid.ts similarity index 91% rename from src/mermaid.js rename to src/mermaid.ts index 3d20922530..13b693b8cb 100644 --- a/src/mermaid.js +++ b/src/mermaid.ts @@ -1,3 +1,5 @@ +// TODO: Remove +// @ts-nocheck /** * Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid * functionality and to render the diagrams to svg code. @@ -29,9 +31,9 @@ import utils from './utils'; * * Renders the mermaid diagrams */ -const init = function () { +const init = function (config: any, ...nodes: any[]) { try { - initThrowsErrors(...arguments); + initThrowsErrors(config, nodes); } catch (e) { log.warn('Syntax Error rendering'); log.warn(e.str); @@ -41,25 +43,17 @@ const init = function () { } }; -const initThrowsErrors = function () { +const initThrowsErrors = function (config: any, nodes: any[]) { const conf = mermaidAPI.getConfig(); // console.log('Starting rendering diagrams (init) - mermaid.init', conf); - let nodes; - if (arguments.length >= 2) { - /*! sequence config was passed as #1 */ - if (typeof arguments[0] !== 'undefined') { - mermaid.sequenceConfig = arguments[0]; - } - - nodes = arguments[1]; - } else { - nodes = arguments[0]; + if (config) { + mermaid.sequenceConfig = config; } // if last argument is a function this is the callback function - let callback; - if (typeof arguments[arguments.length - 1] === 'function') { - callback = arguments[arguments.length - 1]; + let callback: (id: string) => void; + if (typeof nodes[nodes.length - 1] === 'function') { + callback = nodes[nodes.length - 1]; log.debug('Callback function found'); } else { if (typeof conf.mermaid !== 'undefined') { @@ -140,7 +134,7 @@ const initThrowsErrors = function () { } }; -const initialize = function (config) { +const initialize = function (config: any) { // mermaidAPI.reset(); if (typeof config.mermaid !== 'undefined') { if (typeof config.mermaid.startOnLoad !== 'undefined') { diff --git a/src/types.d.ts b/src/types.d.ts deleted file mode 100644 index 9570962c9c..0000000000 --- a/src/types.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -interface ConfigType { - class?: { defaultRenderer: string }; - state?: { defaultRenderer: string }; - flowchart?: { defaultRenderer: string }; -} - -type DiagramDetector = (text: string) => boolean; diff --git a/src/utils.js b/src/utils.js index e7fc5dcb0f..24fb965b5a 100644 --- a/src/utils.js +++ b/src/utils.js @@ -814,6 +814,7 @@ export const setupGraphViewbox = function (graph, svgElem, padding, useMaxWidth) export const initIdGenerator = class iterator { constructor(deterministic, seed) { this.deterministic = deterministic; + // TODO: Seed is only used for length? this.seed = seed; this.count = seed ? seed.length : 0; diff --git a/tsconfig.json b/tsconfig.json index 7fdd4d736f..9db9a88742 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,7 +3,7 @@ /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Projects */ - // "incremental": true, /* Enable incremental compilation */ + "incremental": true /* Enable incremental compilation */, // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ @@ -11,8 +11,10 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, + "lib": [ + "ES2021" + ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */, // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ @@ -24,20 +26,25 @@ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ /* Modules */ - "module": "ES6", /* Specify what module code is generated. */ + "module": "ES6" /* Specify what module code is generated. */, // "rootDir": "./", /* Specify the root folder within your source files. */ - "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, + "baseUrl": "./src" /* Specify the base directory to resolve non-relative module names. */, + "paths": { + "types/*": ["@types/*"] + } /* Specify a set of entries that re-map imports to additional lookup locations. */, // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ + "typeRoots": [ + "./node_modules/@types", + "./src/@types" + ] /* Specify multiple folders that act like `./node_modules/@types`. */, // "types": [], /* Specify type package names to be included without being referenced in a source file. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "resolveJsonModule": true, /* Enable importing .json files */ // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ /* JavaScript Support */ - "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */, // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ @@ -47,7 +54,7 @@ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ - "outDir": "./dist", /* Specify an output folder for all emitted files. */ + "outDir": "./dist" /* Specify an output folder for all emitted files. */, // "removeComments": true, /* Disable emitting comments. */ // "noEmit": true, /* Disable emitting files from a compilation. */ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ @@ -69,12 +76,12 @@ /* Interop Constraints */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ @@ -96,6 +103,6 @@ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } diff --git a/yarn.lock b/yarn.lock index 9848cc6bbb..7e72ef394c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2437,6 +2437,13 @@ dependencies: "@types/ms" "*" +"@types/dompurify@^2.3.3": + version "2.3.3" + resolved "https://registry.yarnpkg.com/@types/dompurify/-/dompurify-2.3.3.tgz#c24c92f698f77ed9cc9d9fa7888f90cf2bfaa23f" + integrity sha512-nnVQSgRVuZ/843oAfhA25eRSNzUFcBPk/LOiw5gm8mD9/X7CNcbRkQu/OsjCewO8+VIYfPxUnXvPEVGenw14+w== + dependencies: + "@types/trusted-types" "*" + "@types/eslint-scope@^3.7.3": version "3.7.3" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.3.tgz#125b88504b61e3c8bc6f870882003253005c3224" @@ -2675,6 +2682,11 @@ resolved "https://registry.yarnpkg.com/@types/tough-cookie/-/tough-cookie-4.0.2.tgz#6286b4c7228d58ab7866d19716f3696e03a09397" integrity sha512-Q5vtl1W5ue16D+nIaW8JWebSSraJVlK+EthKn7e7UcD4KWsaSJ8BqGPXNaPghgtcn/fhvrN17Tv8ksUsQpiplw== +"@types/trusted-types@*": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@types/trusted-types/-/trusted-types-2.0.2.tgz#fc25ad9943bcac11cceb8168db4f275e0e72e756" + integrity sha512-F5DIZ36YVLE+PN+Zwws4kJogq47hNgX3Nx6WyDJ3kcplxyke3XIzB8uK5n/Lpm1HBsbGzd6nmGehL8cPekP+Tg== + "@types/unist@*", "@types/unist@^2.0.0", "@types/unist@^2.0.2": version "2.0.6" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" @@ -3314,6 +3326,20 @@ atob@^2.1.2: resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== +awesome-typescript-loader@^5.2.1: + version "5.2.1" + resolved "https://registry.yarnpkg.com/awesome-typescript-loader/-/awesome-typescript-loader-5.2.1.tgz#a41daf7847515f4925cdbaa3075d61f289e913fc" + integrity sha512-slv66OAJB8orL+UUaTI3pKlLorwIvS4ARZzYR9iJJyGsEgOqueMfOMdKySWzZ73vIkEe3fcwFgsKMg4d8zyb1g== + dependencies: + chalk "^2.4.1" + enhanced-resolve "^4.0.0" + loader-utils "^1.1.0" + lodash "^4.17.5" + micromatch "^3.1.9" + mkdirp "^0.5.1" + source-map-support "^0.5.3" + webpack-log "^1.2.0" + aws-sign2@~0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" @@ -3777,7 +3803,7 @@ chalk@^1.1.3: strip-ansi "^3.0.0" supports-color "^2.0.0" -chalk@^2.0.0, chalk@^2.3.0, chalk@^2.4.1, chalk@^2.4.2: +chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0, chalk@^2.4.1, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== @@ -4796,6 +4822,14 @@ d3@^5.14, d3@^7.0.0: d3-transition "3" d3-zoom "3" +d@1, d@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/d/-/d-1.0.1.tgz#8698095372d58dbee346ffd0c7093f99f8f9eb5a" + integrity sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA== + dependencies: + es5-ext "^0.10.50" + type "^1.0.1" + dagre-d3@^0.6.4: version "0.6.4" resolved "https://registry.yarnpkg.com/dagre-d3/-/dagre-d3-0.6.4.tgz#0728d5ce7f177ca2337df141ceb60fbe6eeb7b29" @@ -5328,6 +5362,15 @@ end-of-stream@^1.0.0, end-of-stream@^1.1.0: dependencies: once "^1.4.0" +enhanced-resolve@^4.0.0: + version "4.5.0" + resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.5.0.tgz#2f3cfd84dbe3b487f18f2db2ef1e064a571ca5ec" + integrity sha512-Nv9m36S/vxpsI+Hc4/ZGRs0n9mXqSWGGq49zxb/cJfPAQMbUtttJAlNPS4AQzaBdw/pKskw5bMbekT/Y7W/Wlg== + dependencies: + graceful-fs "^4.1.2" + memory-fs "^0.5.0" + tapable "^1.0.0" + enhanced-resolve@^5.0.0, enhanced-resolve@^5.10.0: version "5.10.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.10.0.tgz#0dc579c3bb2a1032e357ac45b8f3a6f3ad4fb1e6" @@ -5353,6 +5396,13 @@ envinfo@^7.7.3: resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== +errno@^0.1.3: + version "0.1.8" + resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.8.tgz#8bb3e9c7d463be4976ff888f76b4809ebc2e811f" + integrity sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A== + dependencies: + prr "~1.0.1" + error-ex@^1.3.1: version "1.3.2" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" @@ -5372,6 +5422,32 @@ es-module-lexer@^0.9.0: resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-0.9.3.tgz#6f13db00cc38417137daf74366f535c8eb438f19" integrity sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ== +es5-ext@^0.10.35, es5-ext@^0.10.50: + version "0.10.62" + resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.62.tgz#5e6adc19a6da524bf3d1e02bbc8960e5eb49a9a5" + integrity sha512-BHLqn0klhEpnOKSrzn/Xsz2UIW8j+cGmo9JLzr8BiUapV8hPL9+FliFqjwr9ngW7jWdnxv6eO+/LqyhJVqgrjA== + dependencies: + es6-iterator "^2.0.3" + es6-symbol "^3.1.3" + next-tick "^1.1.0" + +es6-iterator@^2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.3.tgz#a7de889141a05a94b0854403b2d0a0fbfa98f3b7" + integrity sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g== + dependencies: + d "1" + es5-ext "^0.10.35" + es6-symbol "^3.1.1" + +es6-symbol@^3.1.1, es6-symbol@^3.1.3: + version "3.1.3" + resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.3.tgz#bad5d3c1bcdac28269f4cb331e431c78ac705d18" + integrity sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA== + dependencies: + d "^1.0.1" + ext "^1.1.2" + escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" @@ -5797,6 +5873,13 @@ express@^4.17.3: utils-merge "1.0.1" vary "~1.1.2" +ext@^1.1.2: + version "1.6.0" + resolved "https://registry.yarnpkg.com/ext/-/ext-1.6.0.tgz#3871d50641e874cc172e2b53f919842d19db4c52" + integrity sha512-sdBImtzkq2HpkdRLtlLWDa6w4DX22ijZLKx8BMPUuKe1c5lbN6xwQDQCxSfxBQnHZ13ls/FH0MQZx/q/gr6FQg== + dependencies: + type "^2.5.0" + extend-shallow@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" @@ -7891,6 +7974,13 @@ json5@^0.5.0: resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821" integrity sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE= +json5@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.1.tgz#779fb0018604fa854eacbf6252180d83543e3dbe" + integrity sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow== + dependencies: + minimist "^1.2.0" + json5@^2.1.2, json5@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.1.tgz#655d50ed1e6f95ad1a3caababd2b0efda10b395c" @@ -8147,6 +8237,15 @@ loader-utils@^0.2.15: json5 "^0.5.0" object-assign "^4.0.1" +loader-utils@^1.1.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.0.tgz#c579b5e34cb34b1a74edc6c1fb36bfa371d5a613" + integrity sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA== + dependencies: + big.js "^5.2.2" + emojis-list "^3.0.0" + json5 "^1.0.1" + loader-utils@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.2.tgz#d6e3b4fb81870721ae4e0868ab11dd638368c129" @@ -8211,7 +8310,7 @@ lodash.once@^4.1.1: resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac" integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w= -lodash@^4.17.10, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.21, lodash@^4.17.4: +lodash@^4.17.10, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.21, lodash@^4.17.4, lodash@^4.17.5: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== @@ -8221,6 +8320,13 @@ log-driver@^1.2.7: resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.7.tgz#63b95021f0702fedfa2c9bb0a24e7797d71871d8" integrity sha512-U7KCmLdqsGHBLeWqYlFA0V0Sl6P08EE1ZrmA9cxjUE0WVqT9qnyVDPz1kzpFEP0jdJuFnasWIfSd7fsaNXkpbg== +log-symbols@^2.1.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" + integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== + dependencies: + chalk "^2.0.1" + log-symbols@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.1.0.tgz#3fbdbb95b4683ac9fc785111e792e558d4abd503" @@ -8249,6 +8355,14 @@ loglevel@^1.6.0: resolved "https://registry.yarnpkg.com/loglevel/-/loglevel-1.8.0.tgz#e7ec73a57e1e7b419cb6c6ac06bf050b67356114" integrity sha512-G6A/nJLRgWOuuwdNuA6koovfEV1YpqqAG4pRUlFaz3jj2QNZ8M4vBqnVA+HBTmU/AMNUtlOsMmSpF6NyOjztbA== +loglevelnext@^1.0.1: + version "1.0.5" + resolved "https://registry.yarnpkg.com/loglevelnext/-/loglevelnext-1.0.5.tgz#36fc4f5996d6640f539ff203ba819641680d75a2" + integrity sha512-V/73qkPuJmx4BcBF19xPBr+0ZRVBhc4POxvZTZdMeXpJ4NItXSJ/MSwuFT0kQJlCbXvdlZoQQ/418bS1y9Jh6A== + dependencies: + es6-symbol "^3.1.1" + object.assign "^4.1.0" + longest-streak@^2.0.1: version "2.0.4" resolved "https://registry.yarnpkg.com/longest-streak/-/longest-streak-2.0.4.tgz#b8599957da5b5dab64dee3fe316fa774597d90e4" @@ -8451,6 +8565,14 @@ memfs@^3.4.1: dependencies: fs-monkey "1.0.3" +memory-fs@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.5.0.tgz#324c01288b88652966d161db77838720845a8e3c" + integrity sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA== + dependencies: + errno "^0.1.3" + readable-stream "^2.0.1" + meow@^8.0.0: version "8.1.2" resolved "https://registry.yarnpkg.com/meow/-/meow-8.1.2.tgz#bcbe45bda0ee1729d350c03cffc8395a36c4e897" @@ -8691,7 +8813,7 @@ micromark@~2.11.0: debug "^4.0.0" parse-entities "^2.0.0" -micromatch@^3.1.5: +micromatch@^3.1.5, micromatch@^3.1.9: version "3.1.10" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== @@ -8786,7 +8908,7 @@ minimist-options@4.1.0: is-plain-obj "^1.1.0" kind-of "^6.0.3" -minimist@^1.1.0, minimist@^1.1.1, minimist@^1.2.5, minimist@^1.2.6: +minimist@^1.1.0, minimist@^1.1.1, minimist@^1.2.0, minimist@^1.2.5, minimist@^1.2.6: version "1.2.6" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== @@ -8908,6 +9030,11 @@ netmask@^2.0.1: resolved "https://registry.yarnpkg.com/netmask/-/netmask-2.0.2.tgz#8b01a07644065d536383835823bc52004ebac5e7" integrity sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg== +next-tick@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-1.1.0.tgz#1836ee30ad56d67ef281b22bd199f709449b35eb" + integrity sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ== + nice-try@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" @@ -9671,6 +9798,11 @@ proxy-from-env@^1.0.0: resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2" integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg== +prr@~1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" + integrity sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw== + ps-tree@1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/ps-tree/-/ps-tree-1.2.0.tgz#5e7425b89508736cdd4f2224d028f7bb3f722ebd" @@ -10650,7 +10782,7 @@ source-map-support@0.5.13: buffer-from "^1.0.0" source-map "^0.6.0" -source-map-support@^0.5.16, source-map-support@~0.5.20: +source-map-support@^0.5.16, source-map-support@^0.5.3, source-map-support@~0.5.20: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== @@ -11089,6 +11221,11 @@ symbol-tree@^3.2.4: resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== +tapable@^1.0.0: + version "1.1.3" + resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" + integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA== + tapable@^2.1.1, tapable@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.1.tgz#1967a73ef4060a82f12ab96af86d52fdb76eeca0" @@ -11462,6 +11599,16 @@ type-is@~1.6.18: media-typer "0.3.0" mime-types "~2.1.24" +type@^1.0.1: + version "1.2.0" + resolved "https://registry.yarnpkg.com/type/-/type-1.2.0.tgz#848dd7698dafa3e54a6c479e759c4bc3f18847a0" + integrity sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg== + +type@^2.5.0: + version "2.7.2" + resolved "https://registry.yarnpkg.com/type/-/type-2.7.2.tgz#2376a15a3a28b1efa0f5350dcf72d24df6ef98d0" + integrity sha512-dzlvlNlt6AXU7EBSfpAscydQ7gXB+pPGsPnfJnZpiNJBDj7IaJzQlBZYGdEi4R9HmPdBv2XmWJ6YUtoTa7lmCw== + typedarray@^0.0.6, typedarray@~0.0.5: version "0.0.6" resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" @@ -11693,7 +11840,7 @@ uuid@8.3.2, uuid@^8.3.2: resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== -uuid@^3.3.2: +uuid@^3.1.0, uuid@^3.3.2: version "3.4.0" resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee" integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A== @@ -12047,6 +12194,16 @@ webpack-dev-server@^4.3.0: webpack-dev-middleware "^5.3.1" ws "^8.4.2" +webpack-log@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/webpack-log/-/webpack-log-1.2.0.tgz#a4b34cda6b22b518dbb0ab32e567962d5c72a43d" + integrity sha512-U9AnICnu50HXtiqiDxuli5gLB5PGBo7VvcHx36jRZHwK4vzOYLbImqT4lwWwoMHdQWwEKw736fCHEekokTEKHA== + dependencies: + chalk "^2.1.0" + log-symbols "^2.1.0" + loglevelnext "^1.0.1" + uuid "^3.1.0" + webpack-merge@^5.7.3, webpack-merge@^5.8.0: version "5.8.0" resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-5.8.0.tgz#2b39dbf22af87776ad744c390223731d30a68f61" From 4710f67bafb362ddd3896a90fd1812bdcf2c0e63 Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sun, 21 Aug 2022 11:26:45 +0530 Subject: [PATCH 10/31] fix: sanitization bug --- src/diagrams/common/common.spec.js | 58 ++++-------------------------- src/diagrams/common/common.ts | 45 +---------------------- 2 files changed, 7 insertions(+), 96 deletions(-) diff --git a/src/diagrams/common/common.spec.js b/src/diagrams/common/common.spec.js index ac73098297..66ac7b2ea0 100644 --- a/src/diagrams/common/common.spec.js +++ b/src/diagrams/common/common.spec.js @@ -1,4 +1,4 @@ -import { sanitizeText, removeScript, removeEscapes } from './common'; +import { sanitizeText, removeScript } from './common'; describe('when securityLevel is antiscript, all script must be removed', function () { /** @@ -6,7 +6,7 @@ describe('when securityLevel is antiscript, all script must be removed', functio * @param {string} result The expected sanitized text */ function compareRemoveScript(original, result) { - expect(removeScript(original)).toEqual(result); + expect(removeScript(original).trim()).toEqual(result); } it('should remove all script block, script inline.', function () { @@ -29,70 +29,24 @@ describe('when securityLevel is antiscript, all script must be removed', functio compareRemoveScript( `This is a clean link + clean link and me too`, - `This is a clean link + clean link - and me too` + `This is a clean link + clean link + and me too` ); }); it('should detect malicious images', function () { - compareRemoveScript(``, ``); + compareRemoveScript(``, ``); }); it('should detect iframes', function () { compareRemoveScript( ` `, - ` src="http://abc.com/script1.js"> - src="http://example.com/iframeexample">` + '' ); }); }); -describe('remove escape code in text', function () { - it('should remove a unicode colon', function () { - const labelString = '\\u003A'; - - const result = removeEscapes(labelString); - expect(result).toEqual(':'); - }); - it('should remove a hex colon', function () { - const labelString = '\\x3A'; - - const result = removeEscapes(labelString); - expect(result).toEqual(':'); - }); - it('should remove a oct colon', function () { - const labelString = '\\72'; - - const result = removeEscapes(labelString); - expect(result).toEqual(':'); - }); - it('should remove a oct colon 3 numbers', function () { - const labelString = '\\072'; - - const result = removeEscapes(labelString); - expect(result).toEqual(':'); - }); - it('should remove multiple colons 3 numbers', function () { - const labelString = '\\072\\072\\72'; - - const result = removeEscapes(labelString); - expect(result).toEqual(':::'); - }); - it('should handle greater and smaller then', function () { - const labelString = '\\74\\076'; - - const result = removeEscapes(labelString); - expect(result).toEqual('<>'); - }); - it('should handle letters', function () { - const labelString = '\\u0073\\143ri\\x70\\u0074\\x3A'; - - const result = removeEscapes(labelString); - expect(result).toEqual('script:'); - }); -}); - describe('Sanitize text', function () { it('should remove script tag', function () { const maliciousStr = 'javajavascript:script:alert(1)'; diff --git a/src/diagrams/common/common.ts b/src/diagrams/common/common.ts index 2d1d06bbc4..a1b5f027fe 100644 --- a/src/diagrams/common/common.ts +++ b/src/diagrams/common/common.ts @@ -13,22 +13,6 @@ export const getRows = (s?: string): string[] => { return str.split('#br#'); }; -export const removeEscapes = (text: string): string => { - let newStr = text.replace(/\\u[\dA-F]{4}/gi, function (match) { - return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16)); - }); - - newStr = newStr.replace(/\\x([0-9a-f]{2})/gi, (_, c) => String.fromCharCode(parseInt(c, 16))); - newStr = newStr.replace(/\\[\d\d\d]{3}/gi, function (match) { - return String.fromCharCode(parseInt(match.replace(/\\/g, ''), 8)); - }); - newStr = newStr.replace(/\\[\d\d\d]{2}/gi, function (match) { - return String.fromCharCode(parseInt(match.replace(/\\/g, ''), 8)); - }); - - return newStr; -}; - /** * Removes script tags from a text * @@ -36,33 +20,7 @@ export const removeEscapes = (text: string): string => { * @returns {string} The safer text */ export const removeScript = (txt: string): string => { - var rs = ''; - var idx = 0; - - while (idx >= 0) { - idx = txt.indexOf('= 0) { - rs += txt.substr(0, idx); - txt = txt.substr(idx + 1); - - idx = txt.indexOf(''); - if (idx >= 0) { - idx += 9; - txt = txt.substr(idx); - } - } else { - rs += txt; - idx = -1; - break; - } - } - let decodedText = removeEscapes(rs); - decodedText = decodedText.replaceAll(/script>/gi, '#'); - decodedText = decodedText.replaceAll(/javascript:/gi, '#'); - decodedText = decodedText.replaceAll(/javascript&colon/gi, '#'); - decodedText = decodedText.replaceAll(/onerror=/gi, 'onerror:'); - decodedText = decodedText.replaceAll(/