diff --git a/generators/angular/generator.ts b/generators/angular/generator.ts index b20fda58f056..5299c340cd5b 100644 --- a/generators/angular/generator.ts +++ b/generators/angular/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -21,7 +20,7 @@ import { camelCase } from 'lodash-es'; import chalk from 'chalk'; import { isFileStateModified } from 'mem-fs-editor/state'; -import BaseApplicationGenerator, { type Entity } from '../base-application/index.js'; +import BaseApplicationGenerator from '../base-application/index.js'; import { GENERATOR_ANGULAR, GENERATOR_CLIENT, GENERATOR_LANGUAGES } from '../generator-list.js'; import { defaultLanguage } from '../languages/support/index.js'; import { clientFrameworkTypes } from '../../jdl/jhipster/index.js'; @@ -32,9 +31,9 @@ import { generateTestEntityId as getTestEntityId, generateTestEntityPrimaryKey as getTestEntityPrimaryKey, } from '../client/support/index.js'; -import type { CommonClientServerApplication } from '../base-application/types.js'; import { createNeedleCallback, mutateData } from '../base/support/index.js'; import { writeEslintClientRootConfigFile } from '../javascript/generators/eslint/support/tasks.js'; +import type { PostWritingEntitiesTaskParam } from '../../lib/types/application/tasks.js'; import { cleanupEntitiesFiles, postWriteEntitiesFiles, writeEntitiesFiles } from './entity-files-angular.js'; import { writeFiles } from './files-angular.js'; import cleanupOldFilesTask from './cleanup.js'; @@ -101,9 +100,8 @@ export default class AngularGenerator extends BaseApplicationGenerator { }, addNeedles({ source, application }) { source.addEntitiesToClient = param => { - const { application, entities } = param; - this.addEntitiesToModule({ application, entities }); - this.addEntitiesToMenu({ application, entities }); + this.addEntitiesToModule(param); + this.addEntitiesToMenu(param); }; source.addAdminRoute = (args: Omit[0], 'needle'>) => @@ -394,7 +392,7 @@ export default class AngularGenerator extends BaseApplicationGenerator { this.needleApi.clientAngular.addElementToAdminMenu(routerName, iconName, enableTranslation, translationKeyMenu, jhiPrefix); } - addEntitiesToMenu({ application, entities }: { application: CommonClientServerApplication; entities: Entity[] }) { + addEntitiesToMenu({ application, entities }: PostWritingEntitiesTaskParam) { const filePath = `${application.clientSrcDir}app/layouts/navbar/navbar.component.html`; const ignoreNonExisting = chalk.yellow('Reference to entities not added to menu.'); const editCallback = addToEntitiesMenu({ application, entities }); @@ -402,10 +400,10 @@ export default class AngularGenerator extends BaseApplicationGenerator { this.editFile(filePath, { ignoreNonExisting }, editCallback); } - addEntitiesToModule({ application, entities }: { application: CommonClientServerApplication; entities: Entity[] }) { - const filePath = `${application.clientSrcDir}app/entities/entity.routes.ts`; + addEntitiesToModule(param: PostWritingEntitiesTaskParam) { + const filePath = `${param.application.clientSrcDir}app/entities/entity.routes.ts`; const ignoreNonExisting = chalk.yellow(`Route(s) not added to ${filePath}.`); - const addRouteCallback = addEntitiesRoute({ application, entities }); + const addRouteCallback = addEntitiesRoute(param); this.editFile(filePath, { ignoreNonExisting }, addRouteCallback); } diff --git a/generators/angular/support/needles.ts b/generators/angular/support/needles.ts index b13606868186..c479e29ea9cb 100644 --- a/generators/angular/support/needles.ts +++ b/generators/angular/support/needles.ts @@ -21,7 +21,7 @@ import type { BaseApplication } from '../../base-application/types.js'; import { createNeedleCallback } from '../../base/support/needles.js'; import { upperFirstCamelCase } from '../../../lib/utils/string.js'; import { joinCallbacks } from '../../base/support/write-files.js'; -import { asPostWritingEntitiesTask } from '../../base-application/support/task-type-inference.js'; +import type { PostWritingEntitiesTaskParam } from '../../../lib/types/application/tasks.js'; export function addRoute({ needle, @@ -56,7 +56,7 @@ export function addRoute({ }); } -export const addEntitiesRoute = asPostWritingEntitiesTask(function addEntitiesRoute({ application, entities }: { application; entities }) { +export function addEntitiesRoute({ application, entities }: PostWritingEntitiesTaskParam) { const { enableTranslation } = application; return joinCallbacks( ...entities.map(entity => { @@ -73,7 +73,7 @@ export const addEntitiesRoute = asPostWritingEntitiesTask(function addEntitiesRo }); }), ); -}); +} type MenuItem = { jhiPrefix: string; diff --git a/generators/angular/support/translate-angular.ts b/generators/angular/support/translate-angular.ts index adafd666db95..46c426285f0f 100644 --- a/generators/angular/support/translate-angular.ts +++ b/generators/angular/support/translate-angular.ts @@ -314,7 +314,7 @@ export const createTranslationReplacer = (getWebappTranslation, opts: ReplacerOp ); } return function replaceAngularTranslations(content, filePath) { - if (/\.html$/.test(filePath)) { + if (filePath.endsWith('.html')) { if (!enableTranslation) { content = content.replace(new RegExp(TRANSLATE_REGEX, 'g'), ''); content = replacePlaceholders(getWebappTranslation, content); @@ -332,7 +332,7 @@ export const createTranslationReplacer = (getWebappTranslation, opts: ReplacerOp if (/(:?route|module)\.ts$/.test(filePath)) { content = replacePageTitles(getWebappTranslation, content); } - if (/error\.route\.ts$/.test(filePath)) { + if (filePath.endsWith('error.route.ts')) { content = replaceErrorMessage(getWebappTranslation, content); } } diff --git a/generators/app/__snapshots__/generator.spec.ts.snap b/generators/app/__snapshots__/generator.spec.ts.snap index e70a3c66c8bc..ed64f7680b31 100644 --- a/generators/app/__snapshots__/generator.spec.ts.snap +++ b/generators/app/__snapshots__/generator.spec.ts.snap @@ -250,6 +250,7 @@ exports[`generator - app with default config should match snapshot 1`] = ` "clientFramework": "angular", "clientFrameworkAngular": true, "clientFrameworkAny": true, + "clientFrameworkBuiltIn": true, "clientFrameworkNo": false, "clientFrameworkReact": false, "clientFrameworkVue": false, @@ -867,6 +868,7 @@ exports[`generator - app with gateway should match snapshot 1`] = ` "clientFramework": "angular", "clientFrameworkAngular": true, "clientFrameworkAny": true, + "clientFrameworkBuiltIn": true, "clientFrameworkNo": false, "clientFrameworkReact": false, "clientFrameworkVue": false, diff --git a/generators/base-application/support/enum.ts b/generators/base-application/support/enum.ts index f81ba061d3ec..75cfd68cfd74 100644 --- a/generators/base-application/support/enum.ts +++ b/generators/base-application/support/enum.ts @@ -47,7 +47,7 @@ const getEnums = (enums, customValuesState, comments) => { return enums.map(enumValue => ({ name: enumValue, value: enumValue, - comment: comments && comments[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4), + comment: comments?.[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4), })); } return enums.map(enumValue => { @@ -55,7 +55,7 @@ const getEnums = (enums, customValuesState, comments) => { return { name: enumValue.trim(), value: enumValue.trim(), - comment: comments && comments[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4), + comment: comments?.[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4), }; } @@ -63,7 +63,7 @@ const getEnums = (enums, customValuesState, comments) => { return { name: matched![1], value: matched![2], - comment: comments && comments[matched![1]] && formatDocAsJavaDoc(comments[matched![1]], 4), + comment: comments?.[matched![1]] && formatDocAsJavaDoc(comments[matched![1]], 4), }; }); }; diff --git a/generators/base-application/support/prepare-entity.ts b/generators/base-application/support/prepare-entity.ts index c7c8fccd8728..f690005071c0 100644 --- a/generators/base-application/support/prepare-entity.ts +++ b/generators/base-application/support/prepare-entity.ts @@ -275,9 +275,9 @@ export default function prepareEntity(entityWithConfig, generator, application) export function derivedPrimaryKeyProperties(primaryKey) { mutateData(primaryKey, { - hasUUID: primaryKey.fields && primaryKey.fields.some(field => field.fieldType === UUID), - hasLong: primaryKey.fields && primaryKey.fields.some(field => field.fieldType === LONG), - hasInteger: primaryKey.fields && primaryKey.fields.some(field => field.fieldType === INTEGER), + hasUUID: primaryKey.fields?.some(field => field.fieldType === UUID), + hasLong: primaryKey.fields?.some(field => field.fieldType === LONG), + hasInteger: primaryKey.fields?.some(field => field.fieldType === INTEGER), typeUUID: primaryKey.type === UUID, typeString: primaryKey.type === STRING, typeLong: primaryKey.type === LONG, @@ -604,7 +604,7 @@ function preparePostEntityCommonDerivedPropertiesNotTyped(entity: any) { entity.relationships.some(relationship => !relationship.id && relationship.persistableRelationship); entity.allReferences - .filter(reference => reference.relationship && reference.relationship.relatedField) + .filter(reference => reference.relationship?.relatedField) .forEach(reference => { reference.relatedReference = reference.relationship.relatedField.reference; }); diff --git a/generators/base-application/support/prepare-field.ts b/generators/base-application/support/prepare-field.ts index f8c49b33be35..09ac74bc1bc3 100644 --- a/generators/base-application/support/prepare-field.ts +++ b/generators/base-application/support/prepare-field.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -22,6 +21,7 @@ import { fieldTypes, validations } from '../../../jdl/jhipster/index.js'; import { getTypescriptType, prepareField as prepareClientFieldForTemplates } from '../../client/support/index.js'; import { prepareField as prepareServerFieldForTemplates } from '../../server/support/index.js'; import { mutateData } from '../../../lib/utils/object.js'; +import type CoreGenerator from '../../base-core/generator.js'; import { fieldIsEnum } from './field-utils.js'; import { prepareProperty } from './prepare-property.js'; @@ -104,7 +104,7 @@ const fakeStringTemplateForFieldName = columnName => { * @param {string} type csv, cypress, json-serializable, ts * @returns fake value */ -function generateFakeDataForField(field, faker, changelogDate, type = 'csv') { +function generateFakeDataForField(this: CoreGenerator, field, faker, changelogDate, type = 'csv') { let data; if (field.fakerTemplate) { data = faker.faker(field.fakerTemplate); @@ -264,7 +264,7 @@ export default function prepareField(entityWithConfig, field, generator) { prepareServerFieldForTemplates(entityWithConfig, field, generator); } - prepareClientFieldForTemplates(entityWithConfig, field, generator); + prepareClientFieldForTemplates(entityWithConfig, field); return field; } @@ -371,8 +371,8 @@ export function getEnumValuesWithCustomValues(enumValues) { } const matched = /\s*(.+?)\s*\((.+?)\)/.exec(enumValue); return { - name: matched[1], - value: matched[2], + name: matched![1], + value: matched![2], }; }); } diff --git a/generators/base-application/support/prepare-relationship.ts b/generators/base-application/support/prepare-relationship.ts index 4ca7e03d8db1..ee260b29591e 100644 --- a/generators/base-application/support/prepare-relationship.ts +++ b/generators/base-application/support/prepare-relationship.ts @@ -1,3 +1,4 @@ +// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -22,8 +23,11 @@ import pluralize from 'pluralize'; import { checkAndReturnRelationshipOnValue, databaseTypes, entityOptions, validations } from '../../../jdl/jhipster/index.js'; import { getJoinTableName, hibernateSnakeCase } from '../../server/support/index.js'; import { mutateData } from '../../../lib/utils/object.js'; -import { stringifyApplicationData } from './debug.js'; +import type CoreGenerator from '../../base-core/generator.js'; +import type { Relationship } from '../../../lib/types/application/relationship.js'; +import type { Entity } from '../../../lib/types/application/entity.js'; import { prepareProperty } from './prepare-property.js'; +import { stringifyApplicationData } from './debug.js'; const { NEO4J, NO: DATABASE_NO } = databaseTypes; const { MapperTypes } = entityOptions; @@ -33,12 +37,17 @@ const { const { MAPSTRUCT } = MapperTypes; -function _defineOnUpdateAndOnDelete(relationship, generator) { +function _defineOnUpdateAndOnDelete(relationship: Relationship, generator: CoreGenerator) { relationship.onDelete = checkAndReturnRelationshipOnValue(relationship.options?.onDelete, generator); relationship.onUpdate = checkAndReturnRelationshipOnValue(relationship.options?.onUpdate, generator); } -export default function prepareRelationship(entityWithConfig, relationship, generator, ignoreMissingRequiredRelationship) { +export default function prepareRelationship( + entityWithConfig: Entity, + relationship: Relationship, + generator: CoreGenerator, + ignoreMissingRequiredRelationship = false, +) { const entityName = entityWithConfig.name; const { otherEntityName, relationshipSide, relationshipType, relationshipName } = relationship; @@ -228,7 +237,7 @@ export default function prepareRelationship(entityWithConfig, relationship, gene relationship.otherEntityPath = relationship.otherEntityFolderName; } - if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes(REQUIRED)) { + if (relationship.relationshipValidateRules?.includes(REQUIRED)) { if (entityName.toLowerCase() === relationship.otherEntityName.toLowerCase()) { generator.log.warn(`Error at entity ${entityName}: required relationships to the same entity are not supported.`); } else { diff --git a/generators/base-application/support/relationship.ts b/generators/base-application/support/relationship.ts index cabf50ee82ac..ee2a465b48c7 100644 --- a/generators/base-application/support/relationship.ts +++ b/generators/base-application/support/relationship.ts @@ -76,7 +76,7 @@ export const loadEntitiesOtherSide = (entities: JSONEntity[], { application }: { if (!application || application.authenticationTypeOauth2) { errors.push("oauth2 applications with database and '--sync-user-with-idp' option"); } - if (!application || !application.authenticationTypeOauth2) { + if (!application?.authenticationTypeOauth2) { errors.push('jwt and session authentication types in monolith or gateway applications with database'); } throw new Error(`Error at entity ${entity.name}: relationships with built-in User entity is supported in ${errors}.`); diff --git a/generators/base-core/generator.ts b/generators/base-core/generator.ts index e87080fc83a2..747fe1241ab4 100644 --- a/generators/base-core/generator.ts +++ b/generators/base-core/generator.ts @@ -67,6 +67,7 @@ import { dockerPlaceholderGenerator } from '../docker/utils.js'; import { getConfigWithDefaults } from '../../jdl/jhipster/index.js'; import { extractArgumentsFromConfigs } from '../../lib/command/index.js'; import type { Entity } from '../../lib/types/base/entity.js'; +import type BaseApplicationGenerator from '../base-application/generator.js'; const { INITIALIZING, @@ -696,8 +697,9 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`); * Compose with a jhipster generator using default jhipster config. * @return {object} the composed generator */ - async composeWithJHipster(generator: string, options?: ComposeOptions) { - assert(typeof generator === 'string', 'generator should to be a string'); + async composeWithJHipster(gen: G, options?: ComposeOptions) { + assert(typeof gen === 'string', 'generator should to be a string'); + let generator: string = gen; if (!isAbsolute(generator)) { const namespace = generator.includes(':') ? generator : `jhipster:${generator}`; if (await this.env.get(namespace)) { @@ -729,7 +731,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`); /** * Compose with a jhipster generator using default jhipster config, but queue it immediately. */ - async dependsOnJHipster(generator: string, options?: ComposeOptions) { + async dependsOnJHipster(generator: string, options?: ComposeOptions) { return this.composeWithJHipster(generator, { ...options, schedule: false, @@ -972,7 +974,7 @@ templates: ${JSON.stringify(existingTemplates, null, 2)}`; } catch (error) { throw new Error(`Error rendering template ${sourceFileFrom} to ${targetFile}: ${error}`, { cause: error }); } - if (!isBinary && transform && transform.length) { + if (!isBinary && transform?.length) { this.editFile(targetFile, ...transform); } return targetFile; diff --git a/generators/base-workspaces/internal/docker-prompts.ts b/generators/base-workspaces/internal/docker-prompts.ts index 34f68a649625..15d06e572458 100644 --- a/generators/base-workspaces/internal/docker-prompts.ts +++ b/generators/base-workspaces/internal/docker-prompts.ts @@ -389,7 +389,7 @@ export function getAppFolders(directory, deploymentApplicationType) { deploymentApplicationType === (fileData['generator-jhipster'].applicationType ?? MONOLITH) || (deploymentApplicationType === MICROSERVICE && fileData['generator-jhipster'].applicationType === GATEWAY)) ) { - appsFolders.push(file.match(/([^/]*)\/*$/)[1]); + appsFolders.push(/([^/]*)\/*$/.exec(file)[1]); } } catch (err) { this.log.error(chalk.red(`${yoRcFile}: this .yo-rc.json can't be read`)); diff --git a/generators/base/api.d.ts b/generators/base/api.d.ts index 722bab16974e..3c96024d0390 100644 --- a/generators/base/api.d.ts +++ b/generators/base/api.d.ts @@ -14,7 +14,9 @@ export type ApplicationWithConfig = { export type JHipsterGeneratorOptions = BaseOptions & { /* cli options */ commandName: string; + programName: string; positionalArguments?: unknown[]; + createEnvBuilder?: any; /* yeoman options */ skipYoResolve?: boolean; @@ -22,6 +24,7 @@ export type JHipsterGeneratorOptions = BaseOptions & { force?: boolean; /* base options */ + defaults?: boolean; applicationId?: string; applicationWithConfig?: ApplicationWithConfig; /** @@ -191,7 +194,7 @@ export type WriteFileOptions, Generator = Cor } | { /** templates to be written */ - templates: WriteFileTemplate; + templates: WriteFileTemplate[]; } | { /** blocks to be written */ diff --git a/generators/base/generator.ts b/generators/base/generator.ts index fb39488e2c4c..9f78ccff428c 100644 --- a/generators/base/generator.ts +++ b/generators/base/generator.ts @@ -454,7 +454,7 @@ export default class JHipsterBaseBlueprintGenerator { const name = camelCase(baseName) + (baseName.endsWith('App') ? '' : 'App'); - return name.match(/^\d/) ? 'App' : name; + return /^\d/.exec(name) ? 'App' : name; }; export const getMicroserviceAppName = ({ microserviceName }: { microserviceName: string }) => { diff --git a/generators/base/support/jhipster7-context.ts b/generators/base/support/jhipster7-context.ts index ad6c34e18b7a..48b720acd4cd 100644 --- a/generators/base/support/jhipster7-context.ts +++ b/generators/base/support/jhipster7-context.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /* eslint-disable no-console */ import chalk from 'chalk'; import { camelCase } from 'lodash-es'; @@ -236,6 +235,7 @@ export const jhipster7deprecatedProperties = { get: () => (...args) => + // @ts-expect-error getJoinTableName(...args).value, }, getJavaValueGeneratorForType: { @@ -359,7 +359,7 @@ const getPropertBuilder = return undefined; }; -const createHandler = ({ log } = {}) => { +const createHandler = ({ log }: { log: (msg: string) => void } = { log: msg => console.log(msg) }) => { const getProperty = getPropertBuilder({ log }); return { ...Object.fromEntries( @@ -404,6 +404,6 @@ const createHandler = ({ log } = {}) => { }; }; -export function createJHipster7Context(generator, data, options) { +export function createJHipster7Context(generator, data, options: { log: (msg: string) => void }) { return new Proxy({ generator, data }, createHandler(options)); } diff --git a/generators/base/support/write-files.ts b/generators/base/support/write-files.ts index b91da3b6a7a2..f1ba9e41c6c0 100644 --- a/generators/base/support/write-files.ts +++ b/generators/base/support/write-files.ts @@ -30,7 +30,7 @@ const isWin32 = platform() === 'win32'; export function joinCallbacks(...callbacks: EditFileCallback[]): EditFileCallback { return function (this: Generator, content: string, filePath: string) { - if (isWin32 && content.match(/\r\n/)) { + if (isWin32 && /\r\n/.exec(content)) { const removeSlashRSlashN: EditFileCallback = ct => normalizeLineEndings(ct, '\n'); const addSlashRSlashN: EditFileCallback = ct => normalizeLineEndings(ct, '\r\n'); callbacks = [removeSlashRSlashN, ...callbacks, addSlashRSlashN]; diff --git a/generators/base/types.d.ts b/generators/base/types.d.ts index 2cbeb3b5e531..1e7bded2b3e1 100644 --- a/generators/base/types.d.ts +++ b/generators/base/types.d.ts @@ -24,4 +24,5 @@ export type Control = BaseApplicationControlProperties & { * cleanupFiles({ '6.0.0': ['file1', 'file2', [application.shouldRemove, 'file3']] }) */ cleanupFiles: (cleanup: Record) => Promise; + getWebappTranslation?: (s: string, data?: Record) => string; }; diff --git a/generators/bootstrap-application-base/generator.ts b/generators/bootstrap-application-base/generator.ts index ec4e1a6d11d5..c32c95ff2406 100644 --- a/generators/bootstrap-application-base/generator.ts +++ b/generators/bootstrap-application-base/generator.ts @@ -221,7 +221,7 @@ export default class BootstrapApplicationBase extends BaseApplicationGenerator { configureRelationships({ entityName, entityStorage, entityConfig }) { // Validate entity json relationship content - entityConfig.relationships.forEach((relationship: any) => { + entityConfig.relationships!.forEach(relationship => { const { otherEntityName, relationshipType } = relationship; assert( diff --git a/generators/bootstrap-application-base/utils.ts b/generators/bootstrap-application-base/utils.ts index 1c4c560b3a5d..35b428923650 100644 --- a/generators/bootstrap-application-base/utils.ts +++ b/generators/bootstrap-application-base/utils.ts @@ -23,6 +23,7 @@ import { loadRequiredConfigIntoEntity } from '../base-application/support/index. import { PaginationTypes } from '../../jdl/jhipster/entity-options.js'; import { LOGIN_REGEX, LOGIN_REGEX_JS } from '../generator-constants.js'; import { getDatabaseTypeData } from '../server/support/database.js'; +import type BaseApplicationGenerator from '../base-application/generator.js'; const { CASSANDRA } = databaseTypes; const { OAUTH2 } = authenticationTypes; @@ -71,13 +72,13 @@ export const auditableEntityFields = () => [ const authorityEntityName = 'Authority'; -export function createUserEntity(customUserData = {}, application) { +export function createUserEntity(this: BaseApplicationGenerator, customUserData = {}, application) { const userEntityDefinition = this.getEntityConfig('User')?.getAll(); if (userEntityDefinition) { if (userEntityDefinition.relationships && userEntityDefinition.relationships.length > 0) { this.log.warn('Relationships on the User entity side will be disregarded'); } - if (userEntityDefinition.fields && userEntityDefinition.fields.some(field => field.fieldName !== 'id')) { + if (userEntityDefinition.fields?.some(field => field.fieldName !== 'id')) { this.log.warn('Fields on the User entity side (other than id) will be disregarded'); } } @@ -191,7 +192,7 @@ export function createUserEntity(customUserData = {}, application) { return user; } -export function createUserManagementEntity(customUserManagementData = {}, application) { +export function createUserManagementEntity(this: BaseApplicationGenerator, customUserManagementData = {}, application) { const user = createUserEntity.call(this, {}, application); for (const field of user.fields) { // Login is used as the id field in rest api. @@ -236,13 +237,13 @@ export function createUserManagementEntity(customUserManagementData = {}, applic return userManagement; } -export function createAuthorityEntity(customAuthorityData = {}, application) { +export function createAuthorityEntity(this: BaseApplicationGenerator, customAuthorityData = {}, application) { const entityDefinition = this.getEntityConfig(authorityEntityName)?.getAll(); if (entityDefinition) { if (entityDefinition.relationships && entityDefinition.relationships.length > 0) { this.log.warn(`Relationships on the ${authorityEntityName} entity side will be disregarded`); } - if (entityDefinition.fields && entityDefinition.fields.some(field => field.fieldName !== 'name')) { + if (entityDefinition.fields?.some(field => field.fieldName !== 'name')) { this.log.warn(`Fields on the ${authorityEntityName} entity side (other than name) will be disregarded`); } } diff --git a/generators/bootstrap/support/multi-step-transform/index.ts b/generators/bootstrap/support/multi-step-transform/index.ts index 17e73c91f41c..830d77710b0b 100644 --- a/generators/bootstrap/support/multi-step-transform/index.ts +++ b/generators/bootstrap/support/multi-step-transform/index.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * diff --git a/generators/bootstrap/support/multi-step-transform/template-data.ts b/generators/bootstrap/support/multi-step-transform/template-data.ts index bbdc2b4b3014..1d0cc78764d6 100644 --- a/generators/bootstrap/support/multi-step-transform/template-data.ts +++ b/generators/bootstrap/support/multi-step-transform/template-data.ts @@ -1,5 +1,10 @@ -// @ts-nocheck export default class TemplateData { + private _templateFile: any; + private _defaultData: { fragment?: any; section?: string }; + private _sections: any; + private _defaultFragment: any; + private last: any; + constructor(templateFile, defaultData = {}) { this._templateFile = templateFile; this._defaultData = defaultData; @@ -32,7 +37,7 @@ export default class TemplateData { /** * Render fragments using default join and suffix. */ - render(fragmentData = {}, suffix = '\n') { + render(fragmentData: { join?: string; section?: string } = {}, suffix = '\n') { const { join = '\n' } = fragmentData; const renderedFragments = this.renderFragments(fragmentData).filter(fragment => fragment); const section = fragmentData.section || this._defaultData.section; @@ -50,7 +55,7 @@ export default class TemplateData { /** * Proxy to renderFragments for templates. */ - renderFragments(fragmentData = {}) { + renderFragments(fragmentData: { fragment?: any; section?: string } = {}) { const fragment = { ...this._defaultData.fragment, ...fragmentData.fragment }; if (this._defaultData.section && fragmentData.section) { // Disable section passed by the parent. diff --git a/generators/bootstrap/support/multi-step-transform/template-file-fs.ts b/generators/bootstrap/support/multi-step-transform/template-file-fs.ts index 9bf4515883e4..fff7f22b5e17 100644 --- a/generators/bootstrap/support/multi-step-transform/template-file-fs.ts +++ b/generators/bootstrap/support/multi-step-transform/template-file-fs.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -56,7 +55,7 @@ export default class TemplateFileFs { if (templateFile.rootTemplate) { templateFile.file = file; } else { - this.get(templateFile.parentPath).addFragment(templateFile); + this.get(templateFile.parentPath!).addFragment(templateFile); } return templateFile; } diff --git a/generators/bootstrap/support/multi-step-transform/template-file.ts b/generators/bootstrap/support/multi-step-transform/template-file.ts index bcb1afcbe320..d12964cf0c46 100644 --- a/generators/bootstrap/support/multi-step-transform/template-file.ts +++ b/generators/bootstrap/support/multi-step-transform/template-file.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import assert from 'assert'; import path from 'path'; import debugBuilder from 'debug'; @@ -8,6 +7,19 @@ import TemplateData from './template-data.js'; export default class TemplateFile { file; + rootTemplate: boolean; + basePath?: string; + parentPath?: string; + filePath?: string; + + private depth: number; + private _filename: any; + private _extension: any; + private _compiled: ejs.TemplateFunction; + // eslint-disable-next-line no-use-before-define + private _fragments: TemplateFile[]; + private _fragmentName: string; + private _debug: { enabled: boolean } & ((msg: string) => void); constructor(filename, extension) { this._filename = filename; @@ -44,7 +56,7 @@ export default class TemplateFile { } try { - this._compiled = ejs.compile(contents, options); + this._compiled = ejs.compile(contents, { ...options, async: false }) as unknown as ejs.TemplateFunction; } catch (error) { throw new Error(`Error compiling ${this._filename}, with contents:\n${contents}`, { cause: error }); } @@ -60,7 +72,7 @@ export default class TemplateFile { return this._fragments.map(templateFile => templateFile.render(data)); } - render(data = {}) { + render(data: any = {}) { const fragments = new TemplateData(this, data); try { const rendered = this._compiled({ diff --git a/generators/client/entity-files.ts b/generators/client/entity-files.ts index 2c4e4aee6ee7..2c414dba2005 100644 --- a/generators/client/entity-files.ts +++ b/generators/client/entity-files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -19,8 +18,9 @@ */ import { CLIENT_MAIN_SRC_DIR } from '../generator-constants.js'; import { getEnumInfo } from '../base-application/support/index.js'; +import type CoreGenerator from '../base-core/generator.js'; -export async function addEnumerationFiles({ application, entity }) { +export async function addEnumerationFiles(this: CoreGenerator, { application, entity }) { for (const field of entity.fields) { if (field.fieldIsEnum === true) { const { enumFileName } = field; diff --git a/generators/client/files-common.ts b/generators/client/files-common.ts index 4fbf9c833ac9..5f975616225d 100644 --- a/generators/client/files-common.ts +++ b/generators/client/files-common.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,11 +16,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { clientFrameworkTypes } from '../../jdl/jhipster/index.js'; +import { asWritingTask } from '../base-application/support/task-type-inference.js'; import { clientRootTemplatesBlock, clientSrcTemplatesBlock } from './support/files.js'; -const { ANGULAR, REACT, VUE } = clientFrameworkTypes; - export const files = { common: [ { @@ -78,8 +75,8 @@ export const files = { ], }; -export async function writeFiles({ application }) { - if (![ANGULAR, REACT, VUE].includes(application.clientFramework)) { +export const writeFiles = asWritingTask(async function writeFiles({ application }) { + if (!application.clientFrameworkBuiltIn) { return; } @@ -87,4 +84,4 @@ export async function writeFiles({ application }) { sections: files, context: application, }); -} +}); diff --git a/generators/client/generator.ts b/generators/client/generator.ts index 4186d0b08f6f..31986e71a51d 100644 --- a/generators/client/generator.ts +++ b/generators/client/generator.ts @@ -154,10 +154,11 @@ export default class JHipsterClientGenerator extends BaseApplicationGenerator { prepareForTemplates({ application }) { application.webappLoginRegExp = LOGIN_REGEX_JS; + application.clientFrameworkBuiltIn = [ANGULAR, VUE, REACT].includes(application.clientFramework); }, addExternalResource({ application, source }) { - if (![ANGULAR, VUE, REACT].includes(application.clientFramework)) { + if (!application.clientFrameworkBuiltIn) { return; } source.addExternalResourceToRoot = ({ resource, comment }) => @@ -207,7 +208,7 @@ export default class JHipsterClientGenerator extends BaseApplicationGenerator { get writingEntities() { return this.asWritingEntitiesTaskGroup({ async writeEnumerationFiles({ control, application, entities }) { - if (!application.webappEnumerationsDir || ![ANGULAR, VUE, REACT].includes(application.clientFramework)) { + if (!application.webappEnumerationsDir || !application.clientFrameworkBuiltIn) { return; } for (const entity of (control.filterEntitiesAndPropertiesForClient ?? (entities => entities))(entities)) { @@ -224,7 +225,7 @@ export default class JHipsterClientGenerator extends BaseApplicationGenerator { get postWriting() { return this.asPostWritingTaskGroup({ packageJsonScripts({ application }) { - if (![ANGULAR, VUE, REACT].includes(application.clientFramework)) { + if (!application.clientFrameworkBuiltIn) { return; } const packageJsonStorage = this.createStorage(this.destinationPath(application.clientRootDir, 'package.json')); @@ -243,7 +244,7 @@ export default class JHipsterClientGenerator extends BaseApplicationGenerator { }, microfrontend({ application, source }) { - if (!application.microfrontend || ![ANGULAR, VUE, REACT].includes(application.clientFramework)) { + if (!application.microfrontend || !application.clientFrameworkBuiltIn) { return; } if (application.clientFrameworkAngular) { diff --git a/generators/client/prompts.ts b/generators/client/prompts.ts index fba2f3f69155..0438d5bf65d3 100644 --- a/generators/client/prompts.ts +++ b/generators/client/prompts.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,9 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asPromptingTask } from '../base-application/support/task-type-inference.js'; import { httpsGet } from '../base/support/index.js'; -export async function askForClientTheme({ control }) { +type Choice = { value: string; name: string }; + +export const askForClientTheme = asPromptingTask(async function askForClientTheme({ control }) { if (control.existingProject && !this.options.askAnswered) return; const config = this.jhipsterConfigWithDefaults; @@ -30,7 +32,7 @@ export async function askForClientTheme({ control }) { when: () => ['angular', 'react', 'vue'].includes(config.clientFramework), message: 'Would you like to use a Bootswatch theme (https://bootswatch.com/)?', choices: async () => { - const bootswatchChoices = await retrieveOnlineBootswatchThemes(this).catch(errorMessage => { + const bootswatchChoices = await retrieveOnlineBootswatchThemes().catch(errorMessage => { this.log.warn(errorMessage); return retrieveLocalBootswatchThemes(); }); @@ -46,9 +48,9 @@ export async function askForClientTheme({ control }) { }, this.config, ); -} +}); -export async function askForClientThemeVariant({ control }) { +export const askForClientThemeVariant = asPromptingTask(async function askForClientThemeVariant({ control }) { if (control.existingProject && !this.options.askAnswered) return; if ((this.jhipsterConfig.clientTheme ?? 'none') === 'none') { return; @@ -70,17 +72,17 @@ export async function askForClientThemeVariant({ control }) { }, this.config, ); -} +}); -async function retrieveOnlineBootswatchThemes(generator) { - return _retrieveBootswatchThemes(generator, true); +async function retrieveOnlineBootswatchThemes(): Promise { + return _retrieveBootswatchThemes(true); } -async function retrieveLocalBootswatchThemes(generator) { - return _retrieveBootswatchThemes(generator, false); +async function retrieveLocalBootswatchThemes(): Promise { + return _retrieveBootswatchThemes(false); } -async function _retrieveBootswatchThemes(generator, useApi) { +async function _retrieveBootswatchThemes(useApi): Promise { const errorMessage = 'Could not fetch bootswatch themes from API. Using default ones.'; if (!useApi) { return [ diff --git a/generators/client/support/entity-definition.ts b/generators/client/support/entity-definition.ts index 858a11ee54d2..466c6e6421eb 100644 --- a/generators/client/support/entity-definition.ts +++ b/generators/client/support/entity-definition.ts @@ -67,7 +67,7 @@ const generateEntityClientFields = ( dto, customDateType = 'dayjs.Dayjs', embedded = false, - clientFramework = ANGULAR, + clientFramework: string = ANGULAR, ) => { const variablesWithTypes = []; if (!embedded && primaryKey) { @@ -106,7 +106,7 @@ const generateEntityClientFields = ( relevantRelationships.forEach(relationship => { let fieldType; let fieldName; - const nullable = !relationship.relationshipValidateRules || !relationship.relationshipValidateRules.includes(REQUIRED); + const nullable = !relationship.relationshipValidateRules?.includes(REQUIRED); const relationshipType = relationship.relationshipType; if (relationshipType === 'one-to-many' || relationshipType === 'many-to-many') { fieldType = `I${relationship.otherEntityAngularName}[]`; diff --git a/generators/client/support/template-utils.ts b/generators/client/support/template-utils.ts index ab4cc4ce8bec..fd7a006b35a3 100644 --- a/generators/client/support/template-utils.ts +++ b/generators/client/support/template-utils.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -20,6 +19,7 @@ import path from 'path'; import { clientFrameworkTypes, fieldTypes } from '../../../jdl/jhipster/index.js'; +import type { PrimaryKey } from '../../../lib/types/application/entity.js'; import { getEntryIfTypeOrTypeAttribute } from './types-utils.js'; const { STRING: TYPE_STRING, UUID: TYPE_UUID } = fieldTypes.CommonDBTypes; @@ -100,7 +100,7 @@ export const generateEntityClientEnumImports = (fields, clientFramework) => { * @param {boolean} [wrapped=true] - wrapped values for required types. */ -export const generateTestEntityId = (primaryKey, index = 0, wrapped = true) => { +export const generateTestEntityId = (primaryKey: string | PrimaryKey, index: string | number = 0, wrapped = true) => { primaryKey = getEntryIfTypeOrTypeAttribute(primaryKey); let value; if (primaryKey === TYPE_STRING) { diff --git a/generators/client/support/types-utils.ts b/generators/client/support/types-utils.ts index 4b292fe59141..072361f554ff 100644 --- a/generators/client/support/types-utils.ts +++ b/generators/client/support/types-utils.ts @@ -17,6 +17,7 @@ * limitations under the License. */ import { fieldTypes } from '../../../jdl/jhipster/index.js'; +import type { PrimaryKey } from '../../../lib/types/application/entity.js'; import { fieldIsEnum } from '../../base-application/support/index.js'; const { @@ -36,7 +37,7 @@ const { * @param key * @returns {*} */ -export const getEntryIfTypeOrTypeAttribute = key => { +export const getEntryIfTypeOrTypeAttribute = (key: string | PrimaryKey) => { if (typeof key === 'object') { return key.type; } diff --git a/generators/client/types.d.ts b/generators/client/types.d.ts index b930fcf0d470..f34232071d53 100644 --- a/generators/client/types.d.ts +++ b/generators/client/types.d.ts @@ -15,6 +15,7 @@ export type ClientApplication = ApplicationClientProperties & CypressApplication & { webappLoginRegExp: string; webappEnumerationsDir?: string; + clientFrameworkBuiltIn?: boolean; }; export type ClientResources = { diff --git a/generators/docker/support/check-docker.ts b/generators/docker/support/check-docker.ts index e786d06a6ee3..fcb0766670ad 100644 --- a/generators/docker/support/check-docker.ts +++ b/generators/docker/support/check-docker.ts @@ -18,12 +18,13 @@ * limitations under the License. */ import chalk from 'chalk'; +import type CoreGenerator from '../../base-core/generator.js'; /** * Check that Docker exists. * @this {import('../../base-core/index.js').default} */ -export const checkDocker = async function () { +export const checkDocker = async function (this: CoreGenerator) { if (this.abort || this.skipChecks) return; const ret = await this.spawnCommand('docker -v', { reject: false, stdio: 'pipe' }); if (ret.exitCode !== 0) { diff --git a/generators/docker/utils.ts b/generators/docker/utils.ts index 76e66e7115bb..73a378d19ead 100644 --- a/generators/docker/utils.ts +++ b/generators/docker/utils.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -35,7 +34,7 @@ export function getDockerfileContainers(dockerfileContent) { let alias; if (instruction.getKeyword() === 'FROM') { imageWithTag = instruction.getArgumentsContent(); - const split = instruction.getArgumentsContent().split(':'); + const split = instruction.getArgumentsContent()!.split(':'); image = split[0]; tag = split[1]; containers[image] = imageWithTag; @@ -44,7 +43,7 @@ export function getDockerfileContainers(dockerfileContent) { alias = camelCase(image); } } else if (instruction.getKeyword() === 'LABEL') { - const split = instruction.getArgumentsContent().split('='); + const split = instruction.getArgumentsContent()!.split('='); if (split[0].toUpperCase() === 'ALIAS') { alias = camelCase(split[1]); } diff --git a/generators/entity/generator.ts b/generators/entity/generator.ts index a2bb964d156e..27a4153f20e0 100644 --- a/generators/entity/generator.ts +++ b/generators/entity/generator.ts @@ -23,19 +23,24 @@ import path from 'path'; import chalk from 'chalk'; import { upperFirst } from 'lodash-es'; +import type { Storage } from 'yeoman-generator'; import BaseApplicationGenerator from '../base-application/index.js'; import { JHIPSTER_CONFIG_DIR } from '../generator-constants.js'; import { applicationTypes, reservedKeywords } from '../../jdl/jhipster/index.js'; import { GENERATOR_ENTITIES } from '../generator-list.js'; import { getDBTypeFromDBValue, hibernateSnakeCase } from '../server/support/index.js'; +import type { Entity } from '../../lib/types/application/entity.js'; import prompts from './prompts.js'; const { GATEWAY, MICROSERVICE } = applicationTypes; const { isReservedClassName } = reservedKeywords; export default class EntityGenerator extends BaseApplicationGenerator { - name; - application = {}; + name!: string; + application: any = {}; + entityStorage!: Storage; + entityConfig!: Entity; + entityData!: { name: string; filename: string; configExisted: any; entityExisted: boolean; configurationFileExists: boolean }; constructor(args, options, features) { super(args, options, { unique: 'argument', ...features }); @@ -56,8 +61,8 @@ export default class EntityGenerator extends BaseApplicationGenerator { return this.asInitializingTaskGroup({ parseOptions() { const name = upperFirst(this.name).replace('.json', ''); - this.entityStorage = this.getEntityConfig(name, true); - this.entityConfig = this.entityStorage.createProxy(); + this.entityStorage = this.getEntityConfig(name, true)!; + this.entityConfig = this.entityStorage.createProxy() as Entity; const configExisted = this.entityStorage.existed; const filename = path.join(JHIPSTER_CONFIG_DIR, `${name}.json`); @@ -235,11 +240,11 @@ The entity ${entityName} is being created. // Public API method used by the getter and also by Blueprints get end() { - return { + return this.asEndTaskGroup({ end() { this.log.log(chalk.bold.green(`Entity ${this.entityData.entityNameCapitalized} generated successfully.`)); }, - }; + }); } get [BaseApplicationGenerator.END]() { diff --git a/generators/entity/prompts.ts b/generators/entity/prompts.ts index e1f15a6d0f0b..b4d19a2b8774 100644 --- a/generators/entity/prompts.ts +++ b/generators/entity/prompts.ts @@ -30,6 +30,7 @@ import { validations, } from '../../jdl/jhipster/index.js'; import { inputIsNumber, inputIsSignedDecimalNumber, inputIsSignedNumber } from './support/index.js'; +import type EntityGenerator from './generator.js'; const { isReservedPaginationWords, isReservedFieldName, isReservedTableName } = reservedKeywords; const { NO: NO_DATABASE, CASSANDRA, SQL } = databaseTypes; @@ -75,7 +76,7 @@ const getFieldNameUndercored = fields => }), ); -function askForMicroserviceJson() { +function askForMicroserviceJson(this: EntityGenerator) { const context = this.entityData; if (this.jhipsterConfig.applicationType !== GATEWAY || context.configExisted) { return undefined; @@ -115,7 +116,7 @@ function askForMicroserviceJson() { }); } -function askForUpdate() { +function askForUpdate(this: EntityGenerator) { const context = this.entityData; // ask only if running an existing entity without arg option --force or --regenerate const isForce = this.options.force || context.regenerate; @@ -212,7 +213,7 @@ function askForFieldsToRemove() { }); } -function askForRelationships(...args) { +function askForRelationships(this: EntityGenerator, ...args) { const context = this.entityData; // don't prompt if data is imported from a file if (context.useConfigurationFile && context.updateEntity !== 'add') { @@ -225,7 +226,7 @@ function askForRelationships(...args) { return askForRelationship.call(this, ...args); } -function askForRelationsToRemove() { +function askForRelationsToRemove(this: EntityGenerator) { const context = this.entityData; // prompt only if data is imported from a file if (!context.useConfigurationFile || context.updateEntity !== 'remove' || this.entityConfig.relationships.length === 0) { @@ -271,7 +272,7 @@ function askForRelationsToRemove() { }); } -function askForFiltering() { +function askForFiltering(this: EntityGenerator) { const context = this.entityData; // don't prompt if server is skipped, or the backend is not sql, or no service requested if (context.useConfigurationFile || context.skipServer || context.databaseType !== 'sql' || this.entityConfig.service === 'no') { @@ -300,7 +301,7 @@ function askForFiltering() { }); } -function askForReadOnly() { +function askForReadOnly(this: EntityGenerator) { const context = this.entityData; // don't prompt if data is imported from a file if (context.useConfigurationFile) { @@ -319,7 +320,7 @@ function askForReadOnly() { }); } -function askForDTO() { +function askForDTO(this: EntityGenerator) { const context = this.entityData; // don't prompt if data is imported from a file or server is skipped or if no service layer if (context.useConfigurationFile || context.skipServer || this.entityConfig.service === 'no') { @@ -348,7 +349,7 @@ function askForDTO() { }); } -function askForService() { +function askForService(this: EntityGenerator) { const context = this.entityData; // don't prompt if data is imported from a file or server is skipped if (context.useConfigurationFile || context.skipServer) { @@ -381,7 +382,7 @@ function askForService() { }); } -function askForPagination() { +function askForPagination(this: EntityGenerator) { const context = this.entityData; // don't prompt if data are imported from a file if (context.useConfigurationFile) { @@ -421,7 +422,7 @@ function askForPagination() { /** * ask question for a field creation */ -async function askForField() { +async function askForField(this: EntityGenerator) { const context = this.entityData; this.log.log(chalk.green(`\nGenerating field #${this.entityConfig.fields.length + 1}\n`)); const databaseType = context.databaseType; @@ -515,7 +516,7 @@ async function askForField() { if (!/^[A-Za-z0-9_]*$/.test(input)) { return 'Your enum name cannot contain special characters (allowed characters: A-Z, a-z, 0-9 and _)'; } - if (context.enums && context.enums.includes(input)) { + if (context.enums?.includes(input)) { context.existingEnum = true; } else if (context.enums) { context.enums.push(input); @@ -736,7 +737,7 @@ async function askForField() { /** * ask question for a relationship creation */ -async function askForRelationship(...args) { +async function askForRelationship(this: EntityGenerator, ...args) { const [{ application }] = args; const context = this.entityData; const name = context.name; @@ -889,7 +890,7 @@ async function askForRelationship(...args) { /** * Show the entity and it's fields and relationships in console */ -function logFieldsAndRelationships() { +function logFieldsAndRelationships(this: EntityGenerator) { const context = this.entityData; if (this.entityConfig.fields.length > 0 || this.entityConfig.relationships.length > 0) { this.log.log(chalk.red(chalk.white('\n================= ') + context.name + chalk.white(' ================='))); @@ -940,7 +941,7 @@ function logFieldsAndRelationships() { this.log.log(chalk.white('Relationships')); this.entityConfig.relationships.forEach(relationship => { const validationDetails = []; - if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes(REQUIRED)) { + if (relationship.relationshipValidateRules?.includes(REQUIRED)) { validationDetails.push(REQUIRED); } this.log.log( diff --git a/generators/entity/support/asserts.ts b/generators/entity/support/asserts.ts index 8790e41fe5cf..38e402980eca 100644 --- a/generators/entity/support/asserts.ts +++ b/generators/entity/support/asserts.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -27,7 +26,7 @@ * @param isDecimal - flag indicating whether to check for decimal number or not * @returns {number} parsed number if valid input; NaN otherwise */ -const filterNumber = (input, isSigned, isDecimal) => { +const filterNumber = (input: any, isSigned = false, isDecimal = false) => { const signed = isSigned ? '(-|+)?' : ''; const decimal = isDecimal ? '(.[0-9]+)?' : ''; const regex = new RegExp(`^${signed}([0-9]+${decimal})$`); @@ -42,7 +41,7 @@ const filterNumber = (input, isSigned, isDecimal) => { * @param {any} input input * @returns {boolean} true if input is number; false otherwise */ -const isNumber = input => { +const isNumber = (input: any): input is number => { return !isNaN(filterNumber(input)); }; @@ -51,7 +50,7 @@ const isNumber = input => { * @param {any} input input * @returns {boolean} true if input is a signed number; false otherwise */ -const isSignedNumber = input => { +const isSignedNumber = (input: any): boolean => { return !isNaN(filterNumber(input, true)); }; @@ -60,7 +59,7 @@ const isSignedNumber = input => { * @param {any} input input * @returns {boolean} true if input is a signed decimal number; false otherwise */ -const isSignedDecimalNumber = input => { +const isSignedDecimalNumber = (input: any): boolean => { return !isNaN(filterNumber(input, true, true)); }; diff --git a/generators/generate-blueprint/files.ts b/generators/generate-blueprint/files.ts index 7f18a96e8068..52f2e5c0f71d 100644 --- a/generators/generate-blueprint/files.ts +++ b/generators/generate-blueprint/files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -20,7 +19,7 @@ import { asWriteFilesSection } from '../base-application/support/index.js'; import { LOCAL_BLUEPRINT_OPTION } from './constants.js'; -export const files = asWriteFilesSection({ +export const files = asWriteFilesSection({ baseFiles: [ { condition: ctx => !ctx[LOCAL_BLUEPRINT_OPTION], @@ -94,7 +93,7 @@ export const generatorFiles = { path: 'generators/generator', to: ctx => `${ctx.application.blueprintsPath}${ctx.generator}`, condition(ctx) { - return (this.options.force || !ctx.written) && ctx.priorities.find(priority => priority.name === 'writing'); + return ((this as any).options.force || !ctx.written) && ctx.priorities.find(priority => priority.name === 'writing'); }, transform: false, templates: [ diff --git a/generators/generate-blueprint/generator.ts b/generators/generate-blueprint/generator.ts index 1152bac90061..59dd31e633d0 100644 --- a/generators/generate-blueprint/generator.ts +++ b/generators/generate-blueprint/generator.ts @@ -52,6 +52,8 @@ const { GENERATOR_PROJECT_NAME, GENERATOR_INIT } = GENERATOR_LIST; const defaultPublishedFiles = ['generators', '!**/__*', '!**/*.snap', '!**/*.spec.?(c|m)js']; export default class extends BaseGenerator { + application!: any; + async _beforeQueue() { if (!this.fromBlueprint) { await this.composeWithBlueprints(); @@ -80,7 +82,7 @@ export default class extends BaseGenerator { } get prompting() { - return { + return this.asPromptingTaskGroup({ async prompting() { await this.prompt(prompts(this), this.config); }, @@ -111,7 +113,7 @@ export default class extends BaseGenerator { await this.prompt(subGeneratorPrompts({ subGenerator, localBlueprint, additionalSubGenerator: true }), subGeneratorStorage); } }, - }; + }); } get [BaseGenerator.PROMPTING]() { @@ -119,7 +121,7 @@ export default class extends BaseGenerator { } get configuring() { - return { + return this.asConfiguringTaskGroup({ requiredConfig() { this.config.defaults(requiredConfig()); }, @@ -131,7 +133,7 @@ export default class extends BaseGenerator { }); } }, - }; + }); } get [BaseGenerator.CONFIGURING]() { @@ -139,13 +141,13 @@ export default class extends BaseGenerator { } get composing() { - return { + return this.asComposingTaskGroup({ async compose() { if (this.jhipsterConfig[LOCAL_BLUEPRINT_OPTION]) return; const initGenerator = await this.composeWithJHipster(GENERATOR_INIT, { generatorOptions: { packageJsonType: 'module' } }); initGenerator.generateReadme = false; }, - }; + }); } get [BaseGenerator.COMPOSING]() { @@ -336,7 +338,7 @@ export default class extends BaseGenerator { } get postInstall() { - return { + return this.asPostInstallTaskGroup({ async addSnapshot() { const { [LOCAL_BLUEPRINT_OPTION]: localBlueprint } = this.jhipsterConfig; const { @@ -365,7 +367,7 @@ This is a new blueprint, executing '${chalk.yellow('npm run update-snapshot')}' this.log.warn('Fail to generate snapshots'); } }, - }; + }); } get [BaseGenerator.POST_INSTALL]() { @@ -373,7 +375,7 @@ This is a new blueprint, executing '${chalk.yellow('npm run update-snapshot')}' } get end() { - return { + return this.asEndTaskGroup({ end() { if (this.jhipsterConfig[LOCAL_BLUEPRINT_OPTION]) return; @@ -389,7 +391,7 @@ To begin to work: - then, come back here, and begin to code! `); }, - }; + }); } get [BaseGenerator.END]() { diff --git a/generators/init/generator.ts b/generators/init/generator.ts index a4f3ca76702b..aa045f4f23c1 100644 --- a/generators/init/generator.ts +++ b/generators/init/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -21,10 +20,6 @@ import BaseApplicationGenerator from '../base-application/index.js'; import { GENERATOR_GIT } from '../generator-list.js'; import { files, readme } from './files.js'; -/** - * @class - * @extends {BaseApplicationGenerator} - */ export default class InitGenerator extends BaseApplicationGenerator { generateReadme = true; diff --git a/generators/java/support/checks/check-java.ts b/generators/java/support/checks/check-java.ts index 654f4544a835..dacca95d598b 100644 --- a/generators/java/support/checks/check-java.ts +++ b/generators/java/support/checks/check-java.ts @@ -28,11 +28,11 @@ export default (javaCompatibleVersions: string[]): ValidationResult & { javaVers try { const { exitCode, stderr } = execaCommandSync('java -version', { stdio: 'pipe' }); if (exitCode === 0 && stderr) { - const matchResult = stderr.match(/(?:java|openjdk)(?: version)? "?(.*)"? /s); + const matchResult = /(?:java|openjdk)(?: version)? "?(.*)"? /s.exec(stderr); if (matchResult && matchResult.length > 0) { const javaVersion = matchResult[1]; const debug = `Detected java version ${javaVersion}`; - if (javaCompatibleVersions && !javaVersion.match(new RegExp(`(${javaCompatibleVersions.map(ver => `^${ver}`).join('|')})`))) { + if (javaCompatibleVersions && !new RegExp(`(${javaCompatibleVersions.map(ver => `^${ver}`).join('|')})`).exec(javaVersion)) { const [latest, ...others] = javaCompatibleVersions.concat().reverse(); const humanizedVersions = `${others.reverse().join(', ')} or ${latest}`; const warning = `Java ${humanizedVersions} are not found on your computer. Your Java version is: ${chalk.yellow(javaVersion)}`; diff --git a/generators/javascript/generators/bootstrap/generator.ts b/generators/javascript/generators/bootstrap/generator.ts index 889cffdf8ffc..770a25f06449 100644 --- a/generators/javascript/generators/bootstrap/generator.ts +++ b/generators/javascript/generators/bootstrap/generator.ts @@ -80,7 +80,7 @@ export default class BootstrapGenerator extends BaseApplicationGenerator { } if (packageJsonNodeEngine) { this.packageJson.set('engines', { - ...((this.packageJson.get('engines') as object) ?? {}), + ...(this.packageJson.get('engines') ?? {}), node: typeof packageJsonNodeEngine === 'string' ? packageJsonNodeEngine : packageJson.engines.node, }); } diff --git a/generators/javascript/generators/eslint/support/tasks.ts b/generators/javascript/generators/eslint/support/tasks.ts index 07a2f6103136..4848e19ce711 100644 --- a/generators/javascript/generators/eslint/support/tasks.ts +++ b/generators/javascript/generators/eslint/support/tasks.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -18,10 +17,9 @@ * limitations under the License. */ import { asWritingTask } from '../../../../base-application/support/index.js'; -import type { WritingTaskParam } from '../../../../base-application/tasks.js'; import { clientRootTemplatesBlock } from '../../../../client/support/files.js'; -export const writeEslintClientRootConfigFile: WritingTaskParam = asWritingTask(async function writingEslintFile({ application }) { +export const writeEslintClientRootConfigFile = asWritingTask(async function writingEslintFile({ application }) { await this.writeFiles({ blocks: [ clientRootTemplatesBlock({ diff --git a/generators/jdl/internal/utils.ts b/generators/jdl/internal/utils.ts index 08768d05d21d..86837eed1a02 100644 --- a/generators/jdl/internal/utils.ts +++ b/generators/jdl/internal/utils.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -25,7 +24,8 @@ import { join } from 'path'; * @param {string} baseName * @return {boolean} */ -export const baseNameConfigExists = baseName => existsSync(baseName === undefined ? '.yo-rc.json' : join(baseName, '.yo-rc.json')); +export const baseNameConfigExists = (baseName?: string) => + existsSync(baseName === undefined ? '.yo-rc.json' : join(baseName, '.yo-rc.json')); /** * Check if every application is new. diff --git a/generators/kubernetes/prompts.ts b/generators/kubernetes/prompts.ts index e5e1e01e5c9a..d36fd19541aa 100644 --- a/generators/kubernetes/prompts.ts +++ b/generators/kubernetes/prompts.ts @@ -120,7 +120,7 @@ export async function askForIngressDomain() { if (!this.options.askAnswered && (this.regenerate || this.config.existed)) return; const kubernetesServiceType = this.kubernetesServiceType; const istio = this.istio; - this.ingressDomain = this.ingressDomain && this.ingressDomain.startsWith('.') ? this.ingressDomain.substring(1) : this.ingressDomain; + this.ingressDomain = this.ingressDomain?.startsWith('.') ? this.ingressDomain.substring(1) : this.ingressDomain; const istioIpCommand = "kubectl -n istio-system get svc istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}'"; let istioMessage = ''; diff --git a/generators/languages/entity-files.ts b/generators/languages/entity-files.ts index c89d8a3439b6..48e37ebd6dfa 100644 --- a/generators/languages/entity-files.ts +++ b/generators/languages/entity-files.ts @@ -17,7 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { getEnumInfo } from '../base-application/support/index.js'; +import { asWritingEntitiesTask, getEnumInfo } from '../base-application/support/index.js'; import { CLIENT_MAIN_SRC_DIR } from '../generator-constants.js'; /** @@ -63,7 +63,7 @@ export const enumClientI18nFiles = { export function writeEntityFiles() { return { - async writeEnumFiles({ entities, application }) { + writeEnumFiles: asWritingEntitiesTask(async function ({ entities, application }) { if (application.skipClient) return; const languagesToApply = application.enableTranslation ? this.languagesToApply : [...new Set([application.nativeLanguage, 'en'])]; entities = entities.filter(entity => !entity.skipClient && !entity.builtInUser); @@ -91,12 +91,12 @@ export function writeEntityFiles() { ) .flat(), ); - }, + }), - async writeClientFiles({ application, entities }) { + writeClientFiles: asWritingEntitiesTask(async function ({ application, entities }) { if (application.skipClient) return; const entitiesToWriteTranslationFor = entities.filter(entity => !entity.skipClient && !entity.builtInUser); - if (application.userManagement && application.userManagement.skipClient) { + if (application.userManagement?.skipClient) { entitiesToWriteTranslationFor.push(application.userManagement); } @@ -112,6 +112,6 @@ export function writeEntityFiles() { } } } - }, + }), }; } diff --git a/generators/languages/generator.ts b/generators/languages/generator.ts index 611edb19c1b6..42ea39fb4ae2 100644 --- a/generators/languages/generator.ts +++ b/generators/languages/generator.ts @@ -44,6 +44,7 @@ const { NO: NO_CLIENT_FRAMEWORK, ANGULAR } = clientFrameworkTypes; * @extends {BaseApplicationGenerator} */ export default class LanguagesGenerator extends BaseApplicationGenerator { + askForMoreLanguages!: boolean; translationData; supportedLanguages; languages; @@ -52,7 +53,7 @@ export default class LanguagesGenerator extends BaseApplicationGenerator { * Can be incremental or every language. */ languagesToApply; - composedBlueprints = []; + composedBlueprints!: string[] = []; languageCommand; writeJavaLanguageFiles; regenerateLanguages; @@ -380,7 +381,7 @@ export default class LanguagesGenerator extends BaseApplicationGenerator { if (languagesToMigrate[nativeLanguage]) { this.jhipsterConfig.nativeLanguage = languagesToMigrate[nativeLanguage]; } - if (languages && languages.some(lang => languagesToMigrate[lang])) { + if (languages?.some(lang => languagesToMigrate[lang])) { this.jhipsterConfig.languages = languages.map(lang => languagesToMigrate[lang] ?? lang); } } diff --git a/generators/languages/prompts.ts b/generators/languages/prompts.ts index a888305a1249..56e1e97d0edd 100644 --- a/generators/languages/prompts.ts +++ b/generators/languages/prompts.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,10 +16,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import type LanguagesGenerator from './generator.js'; import detectLanguage from './support/detect-language.js'; import { languagesAsChoices } from './support/languages.js'; -export async function askI18n() { +export async function askI18n(this: LanguagesGenerator) { if (!this.askForMoreLanguages) return; const nativeLanguage = this.jhipsterConfig.nativeLanguage; const answers = await this.prompt( @@ -47,7 +47,7 @@ export async function askI18n() { } } -export async function askForLanguages({ control }) { +export async function askForLanguages(this: LanguagesGenerator, { control }) { if (!this.askForMoreLanguages) { return; } diff --git a/generators/languages/support/translate.ts b/generators/languages/support/translate.ts index fda457bb9ea1..8a5c532833a6 100644 --- a/generators/languages/support/translate.ts +++ b/generators/languages/support/translate.ts @@ -54,7 +54,7 @@ export const replaceTranslationKeysWithText = ( let key = match.groups?.key; if (!key && keyPattern) { - const keyMatch = target.match(new RegExp(keyPattern)); + const keyMatch = new RegExp(keyPattern).exec(target); key = keyMatch?.groups?.key; } if (!key) { @@ -63,7 +63,7 @@ export const replaceTranslationKeysWithText = ( let interpolate = match.groups?.interpolate; if (!interpolate && interpolatePattern) { - const interpolateMatch = target.match(new RegExp(interpolatePattern)); + const interpolateMatch = new RegExp(interpolatePattern).exec(target); interpolate = interpolateMatch?.groups?.interpolate; } diff --git a/generators/liquibase/generator.ts b/generators/liquibase/generator.ts index c00b5a00cb72..9c82663bb602 100644 --- a/generators/liquibase/generator.ts +++ b/generators/liquibase/generator.ts @@ -489,7 +489,7 @@ export default class LiquibaseGenerator extends BaseEntityChangesGenerator { source.addGradleProperty?.({ property: 'liquibaseTaskPrefix', value: 'liquibase' }); source.addGradleProperty?.({ property: 'liquibasePluginVersion', value: gradleLiquibaseVersion }); - if (application.javaManagedProperties && application.javaManagedProperties['liquibase.version']) { + if (application.javaManagedProperties?.['liquibase.version']) { source.addGradleProperty?.({ property: 'liquibaseCoreVersion', value: application.javaManagedProperties['liquibase.version'] }); } diff --git a/generators/needle-api.ts b/generators/needle-api.ts index 8ea7f2bdb51f..ebeef04f0a73 100644 --- a/generators/needle-api.ts +++ b/generators/needle-api.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -24,6 +23,12 @@ import ClientReact from './react/needle-api/needle-client-react.js'; import ClientVue from './client/needle-api/needle-client-vue.js'; export default class NeedleApi { + base: Base; + client: Client; + clientAngular: ClientAngular; + clientReact: ClientReact; + clientVue: ClientVue; + constructor(generator) { this.base = new Base(generator); this.client = new Client(generator); diff --git a/generators/project-name/generator.ts b/generators/project-name/generator.ts index 9ef7e53d9900..740ec71bdf63 100644 --- a/generators/project-name/generator.ts +++ b/generators/project-name/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -35,8 +34,9 @@ export default class ProjectNameGenerator extends BaseApplicationGenerator { javaApplication; async beforeQueue() { - this.sharedData.getControl().existingProject = - this.options.defaults || this.options.applicationWithConfig || (this.jhipsterConfig.baseName !== undefined && this.config.existed); + this.sharedData.getControl().existingProject = Boolean( + this.options.defaults || this.options.applicationWithConfig || (this.jhipsterConfig.baseName !== undefined && this.config.existed), + ); if (!this.fromBlueprint) { await this.composeWithBlueprints(); @@ -63,7 +63,7 @@ export default class ProjectNameGenerator extends BaseApplicationGenerator { } get prompting() { - return { + return this.asPromptingTaskGroup({ async showPrompts() { await this.prompt( [ @@ -78,7 +78,7 @@ export default class ProjectNameGenerator extends BaseApplicationGenerator { this.config, ); }, - }; + }); } get [BaseApplicationGenerator.PROMPTING]() { diff --git a/generators/project-name/support/name-resolver.ts b/generators/project-name/support/name-resolver.ts index 790d5bf9110e..68348a226e3f 100644 --- a/generators/project-name/support/name-resolver.ts +++ b/generators/project-name/support/name-resolver.ts @@ -27,7 +27,7 @@ export const validateJavaApplicationName = (name: string) => { if (!/^([\w]*)$/.test(name)) { return 'Your base name cannot contain special characters or a blank space'; } - if (/_/.test(name)) { + if (name.includes('_')) { return 'Your base name cannot contain underscores as this does not meet the URI spec'; } if (name.toLowerCase() === 'application') { diff --git a/generators/react/cleanup.ts b/generators/react/cleanup.ts index d7aecf857949..aeb5cab540ea 100644 --- a/generators/react/cleanup.ts +++ b/generators/react/cleanup.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -18,11 +17,13 @@ * limitations under the License. */ +import { asWritingTask } from '../base-application/support/task-type-inference.js'; + /** * Removes files that where generated in previous JHipster versions and therefore * need to be removed. */ -export default function cleanupOldFilesTask({ application } = {}) { +export default asWritingTask(function cleanupOldFilesTask({ application }) { if (this.isJhipsterVersionLessThan('6.3.0')) { this.removeFile('tslint.json'); } @@ -75,4 +76,4 @@ export default function cleanupOldFilesTask({ application } = {}) { if (this.isJhipsterVersionLessThan('7.9.3')) { this.removeFile(`${application.clientSrcDir}app/config/translation-middleware.ts`); } -} +}); diff --git a/generators/react/entity-files-react.ts b/generators/react/entity-files-react.ts index 6505a1ab5b31..458c2193ce06 100644 --- a/generators/react/entity-files-react.ts +++ b/generators/react/entity-files-react.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asPostWritingEntitiesTask, asWritingEntitiesTask } from '../base-application/support/task-type-inference.js'; import { clientApplicationTemplatesBlock } from '../client/support/index.js'; export const reactFiles = { @@ -51,7 +51,7 @@ export const reactFiles = { ], }; -export async function writeEntitiesFiles({ control, application, entities }) { +export const writeEntitiesFiles = asWritingEntitiesTask(async function ({ control, application, entities }) { for (const entity of (control.filterEntitiesAndPropertiesForClient ?? (entities => entities))(entities).filter( entity => !entity.builtInUser, )) { @@ -60,24 +60,29 @@ export async function writeEntitiesFiles({ control, application, entities }) { context: { ...application, ...entity }, }); } -} +}); -export async function postWriteEntitiesFiles({ control, application, entities }) { +export const postWriteEntitiesFiles = asPostWritingEntitiesTask(async function ({ control, application, entities }) { for (const entity of (control.filterEntitiesForClient ?? (entities => entities))(entities).filter(entity => !entity.builtInUser)) { if (!entity.embedded) { const { entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName } = entity; const { applicationTypeMicroservice, clientSrcDir } = application; this.needleApi.clientReact.addEntityToModule(entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName, { - applicationTypeMicroservice, - clientSrcDir, + applicationTypeMicroservice: applicationTypeMicroservice!, + clientSrcDir: clientSrcDir!, }); - this.addEntityToMenu(entity.entityPage, application.enableTranslation, entity.entityTranslationKeyMenu, entity.entityClassHumanized); + (this as any).addEntityToMenu( + entity.entityPage, + application.enableTranslation, + entity.entityTranslationKeyMenu, + entity.entityClassHumanized, + ); } } -} +}); -export function cleanupEntitiesFiles({ control, application, entities }) { +export const cleanupEntitiesFiles = asWritingEntitiesTask(function cleanupEntitiesFiles({ control, application, entities }) { for (const entity of (control.filterEntitiesForClient ?? (entities => entities))(entities).filter(entity => !entity.builtInUser)) { const { entityFolderName, entityFileName } = entity; @@ -85,4 +90,4 @@ export function cleanupEntitiesFiles({ control, application, entities }) { this.removeFile(`${application.clientTestDir}spec/app/entities/${entityFolderName}/${entityFileName}-reducer.spec.ts`); } } -} +}); diff --git a/generators/react/files-react.ts b/generators/react/files-react.ts index eca623384fc3..69681c39ed1f 100644 --- a/generators/react/files-react.ts +++ b/generators/react/files-react.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { asWriteFilesSection } from '../base-application/support/index.js'; +import { asWriteFilesSection, asWritingTask } from '../base-application/support/index.js'; import { clientApplicationTemplatesBlock, clientRootTemplatesBlock, clientSrcTemplatesBlock } from '../client/support/files.js'; export const files = asWriteFilesSection({ @@ -308,11 +307,11 @@ export const files = asWriteFilesSection({ ], }); -export async function writeFiles({ application }) { +export const writeFiles = asWritingTask(async function writeFiles({ application }) { if (!application.clientFrameworkReact) return; await this.writeFiles({ sections: files, context: application, }); -} +}); diff --git a/generators/react/generator.ts b/generators/react/generator.ts index 0495d37fe1d8..2a8cc8a56951 100644 --- a/generators/react/generator.ts +++ b/generators/react/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -264,11 +263,11 @@ export default class ReactGenerator extends BaseApplicationGenerator { * @param {string} pageTitle - The translation key or the text for the page title in the browser */ addEntityToModule( - entityInstance = this.entityInstance, - entityClass = this.entityClass, - entityName = this.entityAngularName, - entityFolderName = this.entityFolderName, - entityFileName = this.entityFileName, + entityInstance, + entityClass, + entityName, + entityFolderName, + entityFileName, { applicationTypeMicroservice, clientSrcDir }, ) { this.needleApi.clientReact.addEntityToModule(entityInstance, entityClass, entityName, entityFolderName, entityFileName, { diff --git a/generators/react/support/translate-react.ts b/generators/react/support/translate-react.ts index f55ecccc46f8..dc553c806bf4 100644 --- a/generators/react/support/translate-react.ts +++ b/generators/react/support/translate-react.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -35,11 +34,13 @@ function getTranslationValue(getWebappTranslation, key, data) { return getWebappTranslation(key, data) || undefined; } +type Options = { keyPattern?: string; interpolatePattern?: string; wrapTranslation?: string | string[]; escapeHtml?: boolean }; + const replaceTranslationKeysWithText = ( getWebappTranslation, - body, - regexp, - { keyPattern, interpolatePattern, wrapTranslation, escapeHtml } = {}, + body: string, + regexp: string, + { keyPattern, interpolatePattern, wrapTranslation, escapeHtml }: Options = {}, ) => { const matches = body.matchAll(new RegExp(regexp, 'g')); if (typeof wrapTranslation === 'string') { @@ -48,19 +49,19 @@ const replaceTranslationKeysWithText = ( for (const match of matches) { const target = match[0]; - let key = match.groups && match.groups.key; + let key = match.groups?.key; if (!key && keyPattern) { - const keyMatch = target.match(new RegExp(keyPattern)); - key = keyMatch && keyMatch.groups && keyMatch.groups.key; + const keyMatch = new RegExp(keyPattern).exec(target); + key = keyMatch?.groups?.key; } if (!key) { throw new Error(`Translation key not found for ${target}`); } - let interpolate = match.groups && match.groups.interpolate; + let interpolate = match.groups?.interpolate; if (!interpolate && interpolatePattern) { - const interpolateMatch = target.match(new RegExp(interpolatePattern)); - interpolate = interpolateMatch && interpolateMatch.groups && interpolateMatch.groups.interpolate; + const interpolateMatch = new RegExp(interpolatePattern).exec(target); + interpolate = interpolateMatch?.groups?.interpolate; } let data; @@ -68,8 +69,8 @@ const replaceTranslationKeysWithText = ( const interpolateMatches = interpolate.matchAll(/(?[^{\s:,}]+)(?::\s*(?[^,}]+))?/g); data = {}; for (const interpolateMatch of interpolateMatches) { - const field = interpolateMatch.groups.field; - let value = interpolateMatch.groups.value; + const field = interpolateMatch?.groups?.field; + let value: string | number | undefined = interpolateMatch?.groups?.value; if (value === undefined) { value = key; } @@ -84,7 +85,7 @@ const replaceTranslationKeysWithText = ( // wrap expression value = `{${value}}`; } - data[field] = value; + data[field!] = value; } } @@ -110,8 +111,8 @@ const replaceTranslationKeysWithText = ( * @return {import('../../base/api.js').EditFileCallback} */ export const createTranslationReplacer = getWebappTranslation => - function replaceReactTranslations(body, filePath) { - if (/\.tsx$/.test(filePath)) { + function replaceReactTranslations(body: string, filePath: string) { + if (filePath.endsWith('.tsx')) { body = body.replace(new RegExp(TRANSLATE_IMPORT, 'g'), ''); body = replaceTranslationKeysWithText(getWebappTranslation, body, `\\{\\s*${TRANSLATE_FUNCTION}\\s*\\}`, { wrapTranslation: '"' }); body = replaceTranslationKeysWithText(getWebappTranslation, body, TRANSLATE_FUNCTION, { wrapTranslation: '"' }); diff --git a/generators/server/generator.ts b/generators/server/generator.ts index a1b50aedd342..df2d80098a54 100644 --- a/generators/server/generator.ts +++ b/generators/server/generator.ts @@ -336,7 +336,7 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator { const databaseType = entityConfig.databaseType ?? application.databaseType; // Validate entity json field content const fields = entityConfig.fields; - fields.forEach(field => { + fields!.forEach(field => { // Migration from JodaTime to Java Time if (field.fieldType === 'DateTime' || field.fieldType === 'Date') { field.fieldType = INSTANT; @@ -378,7 +378,7 @@ Hibernate JPA 2 Metamodel does not work with Bean Validation 2 for LOB fields, s configureRelationships({ entityConfig, entityName }) { // Validate entity json relationship content const relationships = entityConfig.relationships; - relationships.forEach(relationship => { + relationships!.forEach(relationship => { this._validateRelationship(entityName, relationship); if (relationship.relationshipName === undefined) { diff --git a/generators/server/support/prepare-entity.ts b/generators/server/support/prepare-entity.ts index 82b22189f868..c46049a326f1 100644 --- a/generators/server/support/prepare-entity.ts +++ b/generators/server/support/prepare-entity.ts @@ -109,7 +109,7 @@ export function preparePostEntityServerDerivedProperties(entity) { entity.uniqueEnums[field.fieldType] = field.fieldType; } }); - if (entity.primaryKey && entity.primaryKey.derived) { + if (entity.primaryKey?.derived) { entity.isUsingMapsId = true; entity.mapsIdAssoc = entity.relationships.find(rel => rel.id); } else { diff --git a/generators/spring-boot/entity-cleanup.ts b/generators/spring-boot/entity-cleanup.ts index b4774fcb45d8..42a1b42920e4 100644 --- a/generators/spring-boot/entity-cleanup.ts +++ b/generators/spring-boot/entity-cleanup.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import type { ApplicationType } from '../../lib/types/application/application.js'; +import type { Entity } from '../../lib/types/application/entity.js'; +import type CoreGenerator from '../base-core/generator.js'; + /** * Removes server files that where generated in previous JHipster versions and therefore * need to be removed. @@ -25,11 +28,13 @@ * @param {Object} application * @param {Object} entity */ - -export function cleanupOldFiles({ - application: { packageFolder, srcMainJava, srcTestJava, searchEngineElasticsearch }, - entity: { entityClass, entityAbsoluteFolder }, -}) { +export function cleanupOldFiles( + this: CoreGenerator, + { + application: { packageFolder, srcMainJava, srcTestJava, searchEngineElasticsearch }, + entity: { entityClass, entityAbsoluteFolder }, + }: { application: ApplicationType; entity: Entity }, +) { if (this.isJhipsterVersionLessThan('7.6.1')) { if (searchEngineElasticsearch) { this.removeFile(`${srcMainJava}${packageFolder}/repository/search/SortToFieldSortBuilderConverter.java`); diff --git a/generators/spring-boot/entity-files.ts b/generators/spring-boot/entity-files.ts index 3dbd3dc82d4d..a76c32c90bc9 100644 --- a/generators/spring-boot/entity-files.ts +++ b/generators/spring-boot/entity-files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -23,6 +22,7 @@ import chalk from 'chalk'; import { javaMainPackageTemplatesBlock, javaTestPackageTemplatesBlock, moveToJavaPackageSrcDir } from '../java/support/index.js'; import { SERVER_TEST_SRC_DIR } from '../generator-constants.js'; import { databaseTypes, entityOptions } from '../../jdl/jhipster/index.js'; +import { asWritingEntitiesTask } from '../base-application/support/task-type-inference.js'; import { cleanupOldFiles } from './entity-cleanup.js'; const { COUCHBASE, MONGODB, NEO4J, SQL } = databaseTypes; @@ -196,13 +196,13 @@ export const serverFiles = { export function writeFiles() { return { - cleanupOldServerFiles({ application, entities }) { + cleanupOldServerFiles: asWritingEntitiesTask(function ({ application, entities }) { for (const entity of entities.filter(entity => !entity.skipServer)) { cleanupOldFiles.call(this, { application, entity }); } - }, + }), - async writeServerFiles({ application, entities }) { + writeServerFiles: asWritingEntitiesTask(async function ({ application, entities }) { const rootTemplatesPath = application.reactive ? ['reactive', '', '../../server/templates/', '../../java/generators/domain/templates/'] : ['', '../../server/templates/', '../../java/generators/domain/templates/']; @@ -221,6 +221,6 @@ export function writeFiles() { }); } } - }, + }), }; } diff --git a/generators/spring-boot/prompts.ts b/generators/spring-boot/prompts.ts index f8452420ff32..652ed810786d 100644 --- a/generators/spring-boot/prompts.ts +++ b/generators/spring-boot/prompts.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -31,6 +30,7 @@ import { } from '../../jdl/jhipster/index.js'; import { MESSAGE_BROKER } from '../server/options/index.js'; import { R2DBC_DB_OPTIONS, SQL_DB_OPTIONS } from '../server/support/database.js'; +import type CoreGenerator from '../base-core/generator.js'; const { OptionNames } = applicationOptions; const { GATEWAY, MONOLITH } = applicationTypes; @@ -59,7 +59,7 @@ const { GATLING, CUCUMBER } = testFrameworkTypes; * @returns {boolean} true if option is in array and is set to 'true' */ const getOptionFromArray = (array, option) => { - let optionValue = false; + let optionValue: any = false; array.forEach(value => { if (includes(value, option)) { optionValue = value.split(':')[1]; @@ -69,138 +69,140 @@ const getOptionFromArray = (array, option) => { return optionValue; }; -export async function askForServerSideOpts({ control }) { +export async function askForServerSideOpts(this: CoreGenerator, { control }) { if (control.existingProject && !this.options.askAnswered) return; const { applicationType } = this.jhipsterConfigWithDefaults; - const prompts = [ - { - type: 'list', - name: DATABASE_TYPE, - message: `Which ${chalk.yellow('*type*')} of database would you like to use?`, - choices: answers => { - const opts = []; - if (!answers.reactive) { + + await this.prompt( + [ + { + type: 'list', + name: DATABASE_TYPE, + message: `Which ${chalk.yellow('*type*')} of database would you like to use?`, + choices: answers => { + const opts: any[] = []; + if (!answers.reactive) { + opts.push({ + value: SQL, + name: 'SQL (H2, PostgreSQL, MySQL, MariaDB, Oracle, MSSQL)', + }); + } else { + opts.push({ + value: SQL, + name: 'SQL (H2, PostgreSQL, MySQL, MariaDB, MSSQL)', + }); + } opts.push({ - value: SQL, - name: 'SQL (H2, PostgreSQL, MySQL, MariaDB, Oracle, MSSQL)', + value: MONGODB, + name: 'MongoDB', }); - } else { + if (answers.authenticationType !== OAUTH2) { + opts.push({ + value: CASSANDRA, + name: 'Cassandra', + }); + } opts.push({ - value: SQL, - name: 'SQL (H2, PostgreSQL, MySQL, MariaDB, MSSQL)', + value: 'couchbase', + name: '[BETA] Couchbase', }); - } - opts.push({ - value: MONGODB, - name: 'MongoDB', - }); - if (answers.authenticationType !== OAUTH2) { opts.push({ - value: CASSANDRA, - name: 'Cassandra', + value: NEO4J, + name: '[BETA] Neo4j', }); - } - opts.push({ - value: 'couchbase', - name: '[BETA] Couchbase', - }); - opts.push({ - value: NEO4J, - name: '[BETA] Neo4j', - }); - opts.push({ - value: NO_DATABASE, - name: 'No database', - }); - return opts; + opts.push({ + value: NO_DATABASE, + name: 'No database', + }); + return opts; + }, + default: this.jhipsterConfigWithDefaults.databaseType, }, - default: this.jhipsterConfigWithDefaults.databaseType, - }, - { - when: response => response.databaseType === SQL, - type: 'list', - name: PROD_DATABASE_TYPE, - message: `Which ${chalk.yellow('*production*')} database would you like to use?`, - choices: answers => (answers.reactive ? R2DBC_DB_OPTIONS : SQL_DB_OPTIONS), - default: this.jhipsterConfigWithDefaults.prodDatabaseType, - }, - { - when: response => response.databaseType === SQL, - type: 'list', - name: DEV_DATABASE_TYPE, - message: `Which ${chalk.yellow('*development*')} database would you like to use?`, - choices: response => - [SQL_DB_OPTIONS.find(it => it.value === response.prodDatabaseType)].concat([ + { + when: response => response.databaseType === SQL, + type: 'list', + name: PROD_DATABASE_TYPE, + message: `Which ${chalk.yellow('*production*')} database would you like to use?`, + choices: answers => (answers.reactive ? R2DBC_DB_OPTIONS : SQL_DB_OPTIONS), + default: this.jhipsterConfigWithDefaults.prodDatabaseType, + }, + { + when: response => response.databaseType === SQL, + type: 'list', + name: DEV_DATABASE_TYPE, + message: `Which ${chalk.yellow('*development*')} database would you like to use?`, + choices: response => + [SQL_DB_OPTIONS.find(it => it.value === response.prodDatabaseType)].concat([ + { + value: H2_DISK, + name: 'H2 with disk-based persistence', + }, + { + value: H2_MEMORY, + name: 'H2 with in-memory persistence', + }, + ]) as any, + default: this.jhipsterConfigWithDefaults.devDatabaseType, + }, + { + when: answers => !answers.reactive, + type: 'list', + name: CACHE_PROVIDER, + message: 'Which cache do you want to use? (Spring cache abstraction)', + choices: [ { - value: H2_DISK, - name: 'H2 with disk-based persistence', + value: EHCACHE, + name: 'Ehcache (local cache, for a single node)', }, { - value: H2_MEMORY, - name: 'H2 with in-memory persistence', + value: CAFFEINE, + name: 'Caffeine (local cache, for a single node)', }, - ]), - default: this.jhipsterConfigWithDefaults.devDatabaseType, - }, - { - when: answers => !answers.reactive, - type: 'list', - name: CACHE_PROVIDER, - message: 'Which cache do you want to use? (Spring cache abstraction)', - choices: [ - { - value: EHCACHE, - name: 'Ehcache (local cache, for a single node)', - }, - { - value: CAFFEINE, - name: 'Caffeine (local cache, for a single node)', - }, - { - value: HAZELCAST, - name: 'Hazelcast (distributed cache, for multiple nodes, supports rate-limiting for gateway applications)', - }, - { - value: INFINISPAN, - name: 'Infinispan (hybrid cache, for multiple nodes)', - }, - { - value: MEMCACHED, - name: 'Memcached (distributed cache) - Warning, when using an SQL database, this will disable the Hibernate 2nd level cache!', - }, - { - value: REDIS, - name: 'Redis (distributed cache)', - }, - { - value: NO_CACHE_PROVIDER, - name: 'No cache - Warning, when using an SQL database, this will disable the Hibernate 2nd level cache!', - }, - ], - default: this.jhipsterConfigWithDefaults.cacheProvider, - }, - { - when: answers => - ((answers.cacheProvider !== NO_CACHE_PROVIDER && answers.cacheProvider !== MEMCACHED) || applicationType === GATEWAY) && - answers.databaseType === SQL && - !answers.reactive, - type: 'confirm', - name: 'enableHibernateCache', - message: 'Do you want to use Hibernate 2nd level cache?', - default: this.jhipsterConfigWithDefaults.enableHibernateCache, - }, - ]; - - await this.prompt(prompts, this.config); + { + value: HAZELCAST, + name: 'Hazelcast (distributed cache, for multiple nodes, supports rate-limiting for gateway applications)', + }, + { + value: INFINISPAN, + name: 'Infinispan (hybrid cache, for multiple nodes)', + }, + { + value: MEMCACHED, + name: 'Memcached (distributed cache) - Warning, when using an SQL database, this will disable the Hibernate 2nd level cache!', + }, + { + value: REDIS, + name: 'Redis (distributed cache)', + }, + { + value: NO_CACHE_PROVIDER, + name: 'No cache - Warning, when using an SQL database, this will disable the Hibernate 2nd level cache!', + }, + ], + default: this.jhipsterConfigWithDefaults.cacheProvider, + }, + { + when: answers => + ((answers.cacheProvider !== NO_CACHE_PROVIDER && answers.cacheProvider !== MEMCACHED) || applicationType === GATEWAY) && + answers.databaseType === SQL && + !answers.reactive, + type: 'confirm', + name: 'enableHibernateCache', + message: 'Do you want to use Hibernate 2nd level cache?', + default: this.jhipsterConfigWithDefaults.enableHibernateCache, + }, + ], + this.config, + ); } -export async function askForOptionalItems({ control }) { +export async function askForOptionalItems(this: CoreGenerator, { control }) { if (control.existingProject && !this.options.askAnswered) return; const { applicationType, reactive, databaseType } = this.jhipsterConfigWithDefaults; - const choices = []; + const choices: any[] = []; const defaultChoice = []; if ([SQL, MONGODB, NEO4J].includes(databaseType)) { choices.push({ @@ -235,16 +237,14 @@ export async function askForOptionalItems({ control }) { value: 'enableSwaggerCodegen:true', }); - const PROMPTS = { - type: 'checkbox', - name: 'serverSideOptions', - message: 'Which other technologies would you like to use?', - choices, - default: defaultChoice, - }; - if (choices.length > 0) { - await this.prompt(PROMPTS).then(answers => { + await this.prompt({ + type: 'checkbox', + name: 'serverSideOptions', + message: 'Which other technologies would you like to use?', + choices, + default: defaultChoice, + }).then(answers => { this.jhipsterConfig.serverSideOptions = answers.serverSideOptions; this.jhipsterConfig.websocket = getOptionFromArray(answers.serverSideOptions, WEBSOCKET); this.jhipsterConfig.searchEngine = getOptionFromArray(answers.serverSideOptions, SEARCH_ENGINE); @@ -258,7 +258,7 @@ export async function askForOptionalItems({ control }) { } } -export async function askForServerTestOpts({ control }) { +export async function askForServerTestOpts(this: CoreGenerator, { control }) { if (control.existingProject && this.options.askAnswered !== true) return; const answers = await this.prompt([ diff --git a/generators/spring-data-cassandra/cleanup.ts b/generators/spring-data-cassandra/cleanup.ts index c1c3ffb5bc95..74e19e7ac1e0 100644 --- a/generators/spring-data-cassandra/cleanup.ts +++ b/generators/spring-data-cassandra/cleanup.ts @@ -1,4 +1,5 @@ -// @ts-nocheck +import { asWritingTask } from '../base-application/support/task-type-inference.js'; + /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,7 +18,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export default function cleanupCassandraFilesTask({ application }) { +export default asWritingTask(function cleanupCassandraFilesTask({ application }) { if (this.isJhipsterVersionLessThan('4.3.0')) { this.removeFile(`${application.javaPackageSrcDir}config/cassandra/CustomZonedDateTimeCodec.java`); } @@ -36,4 +37,4 @@ export default function cleanupCassandraFilesTask({ application }) { if (this.isJhipsterVersionLessThan('7.10.0')) { this.removeFile(`${application.javaPackageTestDir}config/TestContainersSpringContextCustomizerFactory.java`); } -} +}); diff --git a/generators/spring-data-cassandra/entity-files.ts b/generators/spring-data-cassandra/entity-files.ts index dade56022780..7abc40aac3d9 100644 --- a/generators/spring-data-cassandra/entity-files.ts +++ b/generators/spring-data-cassandra/entity-files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingEntitiesTask } from '../base-application/support/task-type-inference.js'; import { SERVER_MAIN_RES_DIR } from '../generator-constants.js'; import { javaMainPackageTemplatesBlock } from '../server/support/index.js'; @@ -55,11 +55,11 @@ export const entityFiles = { export function cleanupCassandraEntityFilesTask() {} -export default async function writeEntityCassandraFiles({ application, entities }) { +export default asWritingEntitiesTask(async function writeEntityCassandraFiles({ application, entities }) { for (const entity of entities.filter(entity => !entity.skipServer)) { await this.writeFiles({ sections: entity.builtIn ? { domainFiles } : entityFiles, context: { ...application, ...entity }, }); } -} +}); diff --git a/generators/spring-data-cassandra/files.ts b/generators/spring-data-cassandra/files.ts index c95935ad8702..015fdb6624ac 100644 --- a/generators/spring-data-cassandra/files.ts +++ b/generators/spring-data-cassandra/files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingTask } from '../base-application/support/task-type-inference.js'; import { SERVER_MAIN_RES_DIR, SERVER_MAIN_SRC_DIR, SERVER_TEST_SRC_DIR } from '../generator-constants.js'; import { moveToJavaPackageSrcDir, moveToJavaPackageTestDir } from '../server/support/index.js'; @@ -64,9 +64,9 @@ export const cassandraFiles = { ], }; -export default async function writeCassandraFilesTask({ application }) { +export default asWritingTask(async function writeCassandraFilesTask({ application }) { await this.writeFiles({ sections: cassandraFiles, context: application, }); -} +}); diff --git a/generators/spring-data-cassandra/generator.ts b/generators/spring-data-cassandra/generator.ts index 4d4481be2b6a..30f300bd23a5 100644 --- a/generators/spring-data-cassandra/generator.ts +++ b/generators/spring-data-cassandra/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -95,7 +94,7 @@ export default class CassandraGenerator extends BaseApplicationGenerator { { groupId: 'org.apache.cassandra', artifactId: 'java-driver-mapper-runtime' }, { groupId: 'commons-codec', artifactId: 'commons-codec' }, { groupId: 'org.springframework.boot', artifactId: cassandraStarter }, - { groupId: 'org.lz4', artifactId: 'lz4-java', version: javaDependencies['lz4-java'] }, + { groupId: 'org.lz4', artifactId: 'lz4-java', version: javaDependencies!['lz4-java'] }, { scope: 'test', groupId: 'org.testcontainers', artifactId: 'junit-jupiter' }, { scope: 'test', groupId: 'org.testcontainers', artifactId: 'testcontainers' }, { scope: 'test', groupId: 'org.testcontainers', artifactId: 'cassandra' }, diff --git a/generators/spring-data-couchbase/entity-files.ts b/generators/spring-data-couchbase/entity-files.ts index 2b42c277fa85..85e08ebe50fc 100644 --- a/generators/spring-data-couchbase/entity-files.ts +++ b/generators/spring-data-couchbase/entity-files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingEntitiesTask } from '../base-application/support/task-type-inference.js'; import { SERVER_MAIN_RES_DIR } from '../generator-constants.js'; import { javaMainPackageTemplatesBlock } from '../server/support/index.js'; @@ -64,7 +64,7 @@ export const entityFiles = { repositoryFiles, }; -export function cleanupCouchbaseEntityFilesTask({ application, entities }) { +export const cleanupCouchbaseEntityFilesTask = asWritingEntitiesTask(function ({ application, entities }) { for (const entity of entities.filter(entity => !entity.builtIn && !entity.skipServer)) { if (this.isJhipsterVersionLessThan('7.6.1')) { this.removeFile( @@ -72,13 +72,13 @@ export function cleanupCouchbaseEntityFilesTask({ application, entities }) { ); } } -} +}); -export default async function writeEntityCouchbaseFiles({ application, entities }) { +export default asWritingEntitiesTask(async function writeEntityCouchbaseFiles({ application, entities }) { for (const entity of entities.filter(entity => !entity.skipServer)) { await this.writeFiles({ sections: entityFiles, context: { ...application, ...entity }, }); } -} +}); diff --git a/generators/spring-data-couchbase/files.ts b/generators/spring-data-couchbase/files.ts index 0a65a0a91b56..4d3919482fff 100644 --- a/generators/spring-data-couchbase/files.ts +++ b/generators/spring-data-couchbase/files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingTask } from '../base-application/support/task-type-inference.js'; import { SERVER_MAIN_RES_DIR, SERVER_MAIN_SRC_DIR, SERVER_TEST_SRC_DIR } from '../generator-constants.js'; import { moveToJavaPackageSrcDir, moveToJavaPackageTestDir } from '../server/support/index.js'; @@ -72,7 +72,7 @@ export const couchbaseFiles = { ], }; -export function cleanupCouchbaseFilesTask({ application }) { +export const cleanupCouchbaseFilesTask = asWritingTask(function cleanupCouchbaseFilesTask({ application }) { if (this.isJhipsterVersionLessThan('7.1.1')) { this.removeFile(`${application.javaPackageSrcDir}repository/CustomReactiveCouchbaseRepository.java `); this.removeFile(`${application.javaPackageSrcDir}config/DatabaseConfigurationIT.java`); @@ -93,11 +93,11 @@ export function cleanupCouchbaseFilesTask({ application }) { this.removeFile(`${application.srcMainResources}config/couchmove/changelog/V0.1__initial_setup/user__admin.json`); this.removeFile(`${application.srcMainResources}config/couchmove/changelog/V0.1__initial_setup/user__user.json`); } -} +}); -export default async function writeCouchbaseFilesTask({ application }) { +export default asWritingTask(async function writeCouchbaseFilesTask({ application }) { await this.writeFiles({ sections: couchbaseFiles, context: application, }); -} +}); diff --git a/generators/spring-data-couchbase/generator.ts b/generators/spring-data-couchbase/generator.ts index b4f3025bee17..cd7f982e08a9 100644 --- a/generators/spring-data-couchbase/generator.ts +++ b/generators/spring-data-couchbase/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -58,7 +57,7 @@ export default class CouchbaseGenerator extends BaseApplicationGenerator { get postWriting() { return this.asPostWritingTaskGroup({ addTestSpringFactory({ source, application }) { - source.addTestSpringFactory({ + source.addTestSpringFactory!({ key: 'org.springframework.test.context.ContextCustomizerFactory', value: `${application.packageName}.config.TestContainersSpringContextCustomizerFactory`, }); diff --git a/generators/spring-data-elasticsearch/cleanup.ts b/generators/spring-data-elasticsearch/cleanup.ts index 027854404aa3..ee49d1a7e69f 100644 --- a/generators/spring-data-elasticsearch/cleanup.ts +++ b/generators/spring-data-elasticsearch/cleanup.ts @@ -1,4 +1,5 @@ -// @ts-nocheck +import { asWritingTask } from '../base-application/support/task-type-inference.js'; + /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,7 +18,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export default function cleanupElasticsearchFilesTask({ application }) { +export default asWritingTask(function cleanupElasticsearchFilesTask({ application }) { if (this.isJhipsterVersionLessThan('4.0.0')) { this.removeFile(`${application.javaPackageSrcDir}config/ElasticSearchConfiguration.java`); } @@ -37,4 +38,4 @@ export default function cleanupElasticsearchFilesTask({ application }) { this.removeFile(`${application.javaPackageTestDir}config/ElasticsearchReactiveTestConfiguration.java`); } } -} +}); diff --git a/generators/spring-data-elasticsearch/entity-files.ts b/generators/spring-data-elasticsearch/entity-files.ts index 43e48de9a5ef..27e7389ab72a 100644 --- a/generators/spring-data-elasticsearch/entity-files.ts +++ b/generators/spring-data-elasticsearch/entity-files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingEntitiesTask } from '../base-application/support/task-type-inference.js'; import { javaMainPackageTemplatesBlock } from '../server/support/index.js'; export const entityFiles = { @@ -36,11 +36,11 @@ export const entityFiles = { export function cleanupElasticsearchEntityFilesTask() {} -export default async function writeEntityElasticsearchFiles({ application, entities }) { - for (const entity of entities.filter(entity => !entity.skipServer && entity.searchEngineElasticsearch)) { +export default asWritingEntitiesTask(async function writeEntityElasticsearchFiles({ application, entities }) { + for (const entity of entities.filter(entity => !entity.skipServer && (entity as any).searchEngineElasticsearch)) { await this.writeFiles({ sections: entityFiles, context: { ...application, ...entity }, }); } -} +}); diff --git a/generators/spring-data-elasticsearch/files.ts b/generators/spring-data-elasticsearch/files.ts index b5eb89dc3d85..8e1a144346da 100644 --- a/generators/spring-data-elasticsearch/files.ts +++ b/generators/spring-data-elasticsearch/files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingTask } from '../base-application/support/task-type-inference.js'; import { SERVER_MAIN_SRC_DIR, SERVER_TEST_SRC_DIR } from '../generator-constants.js'; import { moveToJavaPackageSrcDir, moveToJavaPackageTestDir } from '../server/support/index.js'; @@ -50,9 +50,9 @@ export const files = { ], }; -export default async function writeElasticsearchFilesTask({ application }) { +export default asWritingTask(async function writeElasticsearchFilesTask({ application }) { await this.writeFiles({ sections: files, context: application, }); -} +}); diff --git a/generators/spring-data-elasticsearch/generator.ts b/generators/spring-data-elasticsearch/generator.ts index 9fda374e08b0..22ba3c244243 100644 --- a/generators/spring-data-elasticsearch/generator.ts +++ b/generators/spring-data-elasticsearch/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -74,7 +73,7 @@ export default class ElasticsearchGenerator extends BaseApplicationGenerator { get postWriting() { return this.asPostWritingTaskGroup({ addTestSpringFactory({ source, application }) { - source.addTestSpringFactory({ + source.addTestSpringFactory!({ key: 'org.springframework.test.context.ContextCustomizerFactory', value: `${application.packageName}.config.TestContainersSpringContextCustomizerFactory`, }); diff --git a/generators/spring-data-mongodb/cleanup.ts b/generators/spring-data-mongodb/cleanup.ts index 58d09c437c97..10cbaf5a8b79 100644 --- a/generators/spring-data-mongodb/cleanup.ts +++ b/generators/spring-data-mongodb/cleanup.ts @@ -1,4 +1,5 @@ -// @ts-nocheck +import { asWritingTask } from '../base-application/support/task-type-inference.js'; + /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,11 +18,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export default function cleanupMongodbFilesTask({ application }) { +export default asWritingTask(function cleanupMongodbFilesTask({ application }) { if (this.isJhipsterVersionLessThan('3.10.0')) { this.removeFile(`${application.javaPackageSrcDir}config/CloudMongoDbConfiguration.java`); } if (this.isJhipsterVersionLessThan('7.7.1')) { this.removeFile(`${application.javaPackageTestDir}MongoDbTestContainerExtension.java`); } -} +}); diff --git a/generators/spring-data-mongodb/entity-files.ts b/generators/spring-data-mongodb/entity-files.ts index 5587219abfa4..214a9e2db72c 100644 --- a/generators/spring-data-mongodb/entity-files.ts +++ b/generators/spring-data-mongodb/entity-files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingEntitiesTask } from '../base-application/support/task-type-inference.js'; import { javaMainPackageTemplatesBlock } from '../server/support/index.js'; const domainFiles = [ @@ -47,11 +47,11 @@ export const entityFiles = { export function cleanupMongodbEntityFilesTask() {} -export default async function writeEntityMongodbFiles({ application, entities }) { +export default asWritingEntitiesTask(async function writeEntityMongodbFiles({ application, entities }) { for (const entity of entities.filter(entity => !entity.skipServer)) { await this.writeFiles({ sections: entityFiles, context: { ...application, ...entity }, }); } -} +}); diff --git a/generators/spring-data-mongodb/files.ts b/generators/spring-data-mongodb/files.ts index a8cf0cbff7f3..a541487b9b37 100644 --- a/generators/spring-data-mongodb/files.ts +++ b/generators/spring-data-mongodb/files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingTask } from '../base-application/support/task-type-inference.js'; import { SERVER_MAIN_SRC_DIR, SERVER_TEST_SRC_DIR } from '../generator-constants.js'; import { moveToJavaPackageSrcDir, moveToJavaPackageTestDir } from '../server/support/index.js'; @@ -41,9 +41,9 @@ export const mongoDbFiles = { ], }; -export default async function writeMongodbFilesTask({ application }) { +export default asWritingTask(async function writeMongodbFilesTask({ application }) { await this.writeFiles({ sections: mongoDbFiles, context: application, }); -} +}); diff --git a/generators/spring-data-mongodb/generator.ts b/generators/spring-data-mongodb/generator.ts index 006f9fd388f6..22d66145d9df 100644 --- a/generators/spring-data-mongodb/generator.ts +++ b/generators/spring-data-mongodb/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -59,7 +58,7 @@ export default class MongoDBGenerator extends BaseApplicationGenerator { get postWriting() { return this.asPostWritingTaskGroup({ addTestSpringFactory({ source, application }) { - source.addTestSpringFactory({ + source.addTestSpringFactory!({ key: 'org.springframework.test.context.ContextCustomizerFactory', value: `${application.packageName}.config.TestContainersSpringContextCustomizerFactory`, }); @@ -67,7 +66,7 @@ export default class MongoDBGenerator extends BaseApplicationGenerator { addDependencies({ application, source }) { const { reactive, javaDependencies } = application; source.addJavaDependencies?.([ - { groupId: 'io.mongock', artifactId: 'mongock-bom', type: 'pom', version: javaDependencies['mongock-bom'], scope: 'import' }, + { groupId: 'io.mongock', artifactId: 'mongock-bom', type: 'pom', version: javaDependencies!['mongock-bom'], scope: 'import' }, { groupId: 'io.mongock', artifactId: 'mongock-springboot-v3' }, { groupId: 'org.springframework.boot', artifactId: `spring-boot-starter-data-mongodb${reactive ? '-reactive' : ''}` }, { groupId: 'io.mongock', artifactId: reactive ? 'mongodb-reactive-driver' : 'mongodb-springdata-v4-driver' }, @@ -88,7 +87,7 @@ export default class MongoDBGenerator extends BaseApplicationGenerator { blockhound({ application, source }) { const { reactive } = application; if (reactive) { - source.addAllowBlockingCallsInside({ classPath: 'com.mongodb.internal.Locks', method: 'checkedWithLock' }); + source.addAllowBlockingCallsInside!({ classPath: 'com.mongodb.internal.Locks', method: 'checkedWithLock' }); } }, }); diff --git a/generators/spring-data-relational/entity-files.ts b/generators/spring-data-relational/entity-files.ts index d39b6b01aee1..7147d7dbcb63 100644 --- a/generators/spring-data-relational/entity-files.ts +++ b/generators/spring-data-relational/entity-files.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { asWritingEntitiesTask } from '../base-application/support/task-type-inference.js'; import { javaMainPackageTemplatesBlock } from '../java/support/index.js'; const domainFiles = [ @@ -89,7 +89,7 @@ const sqlFiles = { export function cleanupEntitiesTask() {} -export default async function writeEntitiesTask({ application, entities }) { +export default asWritingEntitiesTask(async function writeEntitiesTask({ application, entities }) { for (const entity of entities.filter(entity => !entity.skipServer)) { if (entity.builtInUser) { await this.writeFiles({ @@ -109,4 +109,4 @@ export default async function writeEntitiesTask({ application, entities }) { }); } } -} +}); diff --git a/generators/spring-data-relational/generator.ts b/generators/spring-data-relational/generator.ts index 01cb766e3a04..759b005dbf14 100644 --- a/generators/spring-data-relational/generator.ts +++ b/generators/spring-data-relational/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -18,11 +17,11 @@ * limitations under the License. */ +import assert from 'assert'; import BaseApplicationGenerator from '../base-application/index.js'; import { GENERATOR_LIQUIBASE } from '../generator-list.js'; import { isReservedTableName } from '../../jdl/jhipster/reserved-keywords.js'; import { databaseTypes } from '../../jdl/jhipster/index.js'; -import type { GeneratorDefinition as SpringBootGeneratorDefinition } from '../server/index.js'; import writeTask from './files.js'; import cleanupTask from './cleanup.js'; import writeEntitiesTask, { cleanupEntitiesTask } from './entity-files.js'; @@ -31,7 +30,7 @@ import { getDatabaseDriverForDatabase, getDatabaseTypeMavenDefinition, getH2Mave const { SQL } = databaseTypes; -export default class SqlGenerator extends BaseApplicationGenerator { +export default class SqlGenerator extends BaseApplicationGenerator { async beforeQueue() { if (!this.fromBlueprint) { await this.composeWithBlueprints(); @@ -61,7 +60,7 @@ export default class SqlGenerator extends BaseApplicationGenerator entities))(entities).filter(entity => !entity.builtInUser)) { const { entityFolderName, entityFileName } = entity; if (this.isJhipsterVersionLessThan('8.0.0-beta.3')) { diff --git a/generators/vue/files-vue.ts b/generators/vue/files-vue.ts index 079e6018c8da..e70af0479916 100644 --- a/generators/vue/files-vue.ts +++ b/generators/vue/files-vue.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -18,7 +17,7 @@ * limitations under the License. */ -import { asWritingTask } from '../base-application/support/index.js'; +import { asWritingEntitiesTask, asWritingTask } from '../base-application/support/index.js'; import { clientApplicationTemplatesBlock, clientRootTemplatesBlock, clientSrcTemplatesBlock } from '../client/support/files.js'; export const vueFiles = { @@ -303,7 +302,7 @@ export const writeFiles = asWritingTask(async function writeFiles({ application }); }); -export const writeEntitiesFiles = asWritingTask(async function writeEntitiesFiles({ application, entities }) { +export const writeEntitiesFiles = asWritingEntitiesTask(async function writeEntitiesFiles({ application, entities }) { entities = entities.filter(entity => !entity.skipClient && !entity.builtInUser); await this.writeFiles({ sections: entitiesFiles, diff --git a/generators/vue/generator.ts b/generators/vue/generator.ts index 7c17526fca02..2ce14d7dedf1 100644 --- a/generators/vue/generator.ts +++ b/generators/vue/generator.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /** * Copyright 2013-2024 the original author or authors from the JHipster project. * @@ -17,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { relative } from 'path'; +import assert from 'node:assert'; import chalk from 'chalk'; import { isFileStateModified } from 'mem-fs-editor/state'; import { camelCase, startCase } from 'lodash-es'; @@ -109,24 +108,14 @@ export default class VueGenerator extends BaseApplicationGenerator { return this.delegateTasksToBlueprint(() => this.preparing); } - get preparingEachEntity() { - return this.asPreparingEachEntityTaskGroup({ - prepareEntityForTemplates({ entity }) { - // Can be dropped if tests are moved near implementation - entity.relativeToEntityFolderName = relative(entity.entityFolderName, '.'); - }, - }); - } - - get [BaseApplicationGenerator.PREPARING_EACH_ENTITY]() { - return this.delegateTasksToBlueprint(() => this.preparingEachEntity); - } - get default() { return this.asDefaultTaskGroup({ async queueTranslateTransform({ control, application }) { const { enableTranslation, clientSrcDir } = application; const { getWebappTranslation } = control; + + assert.ok(getWebappTranslation, 'getWebappTranslation is required'); + this.queueTransformStream( { name: 'translating vue application', @@ -187,11 +176,11 @@ export default class VueGenerator extends BaseApplicationGenerator { return this.asPostWritingTaskGroup({ addIndexAsset({ source, application }) { if (application.microfrontend) return; - source.addExternalResourceToRoot({ + source.addExternalResourceToRoot!({ resource: '', comment: 'Workaround https://github.com/axios/axios/issues/5622', }); - source.addExternalResourceToRoot({ + source.addExternalResourceToRoot!({ resource: ``, comment: 'Load vue main', }); @@ -263,17 +252,7 @@ export default class VueGenerator extends BaseApplicationGenerator { * @param {boolean} readOnly - If the entity is read-only or not * @param {string} pageTitle - The translation key or the text for the page title in the browser */ - addEntityToModule( - entityInstance = this.entityInstance, - entityClass = this.entityClass, - entityName = this.entityAngularName, - entityFolderName = this.entityFolderName, - entityFileName = this.entityFileName, - _entityUrl = this.entityUrl, - _microserviceName = this.microserviceName, - readOnly = this.readOnly, - _pageTitle = this.enableTranslation ? `${this.i18nKeyPrefix}.home.title` : this.entityClassPlural, - ) { + addEntityToModule(entityInstance, entityClass, entityName, entityFolderName, entityFileName, _entityUrl, _microserviceName, readOnly) { this.needleApi.clientVue.addEntityToRouterImport(entityName, entityFileName, entityFolderName, readOnly); this.needleApi.clientVue.addEntityToRouter(entityInstance, entityName, entityFileName, readOnly); this.needleApi.clientVue.addEntityServiceToEntitiesComponentImport(entityName, entityClass, entityFileName, entityFolderName); diff --git a/generators/workspaces/generator.ts b/generators/workspaces/generator.ts index 4aa3afcdb816..a7f796abc523 100644 --- a/generators/workspaces/generator.ts +++ b/generators/workspaces/generator.ts @@ -25,12 +25,6 @@ import { GENERATOR_ANGULAR, GENERATOR_BOOTSTRAP_WORKSPACES, GENERATOR_GIT } from import BaseWorkspacesGenerator from '../base-workspaces/index.js'; import { packageJson } from '../../lib/index.js'; -/** - * Base class for a generator that can be extended through a blueprint. - * - * @class - * @extends {BaseWorkspacesGenerator} - */ export default class WorkspacesGenerator extends BaseWorkspacesGenerator { workspaces; generateApplications; @@ -38,6 +32,7 @@ export default class WorkspacesGenerator extends BaseWorkspacesGenerator { entrypointGenerator; generateWorkspaces; + workspacesConfig!: Record; async beforeQueue() { if (!this.fromBlueprint) { diff --git a/jdl/basic-types/json-entity.ts b/jdl/basic-types/json-entity.ts index abcb72d24697..3c87f796e974 100644 --- a/jdl/basic-types/json-entity.ts +++ b/jdl/basic-types/json-entity.ts @@ -45,7 +45,7 @@ class JSONEntity { * - clientRootFolder */ constructor(args: Partial) { - if (!args || !args.entityName) { + if (!args?.entityName) { throw new Error('At least an entity name must be passed.'); } const merged: Partial = merge(getDefaults(args.entityName), args); diff --git a/jdl/built-in-options/binary-options.ts b/jdl/built-in-options/binary-options.ts index 703e12034187..f27cbc0f4b47 100644 --- a/jdl/built-in-options/binary-options.ts +++ b/jdl/built-in-options/binary-options.ts @@ -59,7 +59,7 @@ const DefaultValues = { }; function getOptionName(optionValue): string | undefined { - return optionNames.find(optionName => Values[optionName] && Values[optionName][optionValue]); + return optionNames.find(optionName => Values[optionName]?.[optionValue]); } const OptionValues = { diff --git a/jdl/converters/parsed-jdl-to-jdl-object/option-converter.ts b/jdl/converters/parsed-jdl-to-jdl-object/option-converter.ts index 0087833f2996..85a1f9e01287 100644 --- a/jdl/converters/parsed-jdl-to-jdl-object/option-converter.ts +++ b/jdl/converters/parsed-jdl-to-jdl-object/option-converter.ts @@ -49,7 +49,7 @@ function convertUnaryOptions(parsedOptions: Record): JD const convertedUnaryOptions: JDLUnaryOption[] = []; unaryOptions.forEach((unaryOptionName: string) => { const parsedUnaryOption = parsedOptions[unaryOptionName]; - if (!parsedUnaryOption || !parsedUnaryOption.list || parsedUnaryOption.list.length === 0) { + if (!parsedUnaryOption?.list || parsedUnaryOption.list.length === 0) { return; } convertedUnaryOptions.push( diff --git a/jdl/exporters/jhipster-entity-exporter.ts b/jdl/exporters/jhipster-entity-exporter.ts index 868845088386..12d7b8474159 100644 --- a/jdl/exporters/jhipster-entity-exporter.ts +++ b/jdl/exporters/jhipster-entity-exporter.ts @@ -52,7 +52,7 @@ export default function exportEntities(passedConfiguration: JhipsterJSONJDLExpor } function init(passedConfiguration: JhipsterJSONJDLExporterWrapper) { - if (!passedConfiguration || !passedConfiguration.entities) { + if (!passedConfiguration?.entities) { throw new Error('Entities have to be passed to be exported.'); } configuration = passedConfiguration; diff --git a/jdl/jdl-importer.ts b/jdl/jdl-importer.ts index f1fdda310c45..ada8eff6697d 100644 --- a/jdl/jdl-importer.ts +++ b/jdl/jdl-importer.ts @@ -170,7 +170,7 @@ function checkForErrors(jdlObject: JDLObject, configuration, logger = console) { let applicationType = configuration.applicationType; let databaseType = configuration.databaseType; let blueprints = configuration.blueprints; - if (application && application[GENERATOR_JHIPSTER]) { + if (application?.[GENERATOR_JHIPSTER]) { if (applicationType === undefined) { applicationType = application[GENERATOR_JHIPSTER].applicationType; } @@ -203,7 +203,7 @@ function importOnlyEntities(jdlObject: JDLObject, configuration) { if (!configuration.application && doesFileExist('.yo-rc.json')) { application = readJSONFile('.yo-rc.json'); } - if (application && application[GENERATOR_JHIPSTER]) { + if (application?.[GENERATOR_JHIPSTER]) { if (applicationType === undefined) { applicationType = application[GENERATOR_JHIPSTER].applicationType; } diff --git a/jdl/linters/entity-linter.ts b/jdl/linters/entity-linter.ts index c86769f2e231..8fd2255f8181 100644 --- a/jdl/linters/entity-linter.ts +++ b/jdl/linters/entity-linter.ts @@ -76,7 +76,7 @@ function checkForDuplicatedEntities(entityDeclarations: EntityDeclaration[]) { function checkForUselessEntityBraces(entityDeclaration: EntityDeclaration) { const entityBody = entityDeclaration.children.entityBody; - const nextTokensAfterRelationshipType = entityBody && entityBody[0].children; + const nextTokensAfterRelationshipType = entityBody?.[0].children; const onlyCurlyBracesAsRelationshipBody = entityBody && Object.keys(nextTokensAfterRelationshipType).length === 2; if (onlyCurlyBracesAsRelationshipBody) { issues.push( diff --git a/jdl/linters/issues/abstract-issue.ts b/jdl/linters/issues/abstract-issue.ts index 59551a206955..2ad37fbe0560 100644 --- a/jdl/linters/issues/abstract-issue.ts +++ b/jdl/linters/issues/abstract-issue.ts @@ -23,7 +23,7 @@ export default class AbstractIssue { ruleName: string; constructor(args: AbstractIssueArgs) { - if (!args || !args.ruleName) { + if (!args?.ruleName) { throw new Error('An issue must at least have a rule name.'); } this.ruleName = args.ruleName; diff --git a/jdl/linters/jdl-linter.ts b/jdl/linters/jdl-linter.ts index 876b7e0be44a..9a3c7bc21350 100644 --- a/jdl/linters/jdl-linter.ts +++ b/jdl/linters/jdl-linter.ts @@ -130,7 +130,7 @@ function getAllFieldDeclarations(entityDeclarations: EntityDeclaration[]) { function getFieldDeclarationsFromEntity(entityDeclaration: EntityDeclaration) { const entityBody = entityDeclaration.children.entityBody; - const entityFields = entityBody && entityBody[0].children.fieldDeclaration; + const entityFields = entityBody?.[0].children.fieldDeclaration; if (entityBody && entityFields) { return entityFields; } diff --git a/jdl/linters/rule.ts b/jdl/linters/rule.ts index 17424969c2d5..af4e892c57f1 100644 --- a/jdl/linters/rule.ts +++ b/jdl/linters/rule.ts @@ -39,7 +39,7 @@ export default class Rule { * - comment: a possible comment for the rule */ constructor(args: { name: any; level: RuleLevel; comment: any }) { - if (!args || !args.name) { + if (!args?.name) { throw new Error('A rule must at least have a name.'); } const merged = merge(defaults(), args) as any; diff --git a/jdl/matchers/entity-matcher.ts b/jdl/matchers/entity-matcher.ts index 948f5ab90e7f..ffdf2dfd959d 100644 --- a/jdl/matchers/entity-matcher.ts +++ b/jdl/matchers/entity-matcher.ts @@ -1,3 +1,3 @@ export default function matchEntity(jdlEntity) { - return jdlEntity && jdlEntity.name && jdlEntity.fields; + return jdlEntity?.name && jdlEntity.fields; } diff --git a/jdl/matchers/field-matcher.ts b/jdl/matchers/field-matcher.ts index 5d328084fa1f..50d9b50b6411 100644 --- a/jdl/matchers/field-matcher.ts +++ b/jdl/matchers/field-matcher.ts @@ -1,3 +1,3 @@ export default function matchField(jdlField) { - return jdlField && jdlField.name && jdlField.type && jdlField.validations && jdlField.options; + return jdlField?.name && jdlField.type && jdlField.validations && jdlField.options; } diff --git a/jdl/models/jdl-deployment.ts b/jdl/models/jdl-deployment.ts index 710a3da933c8..180fc0cf90f4 100644 --- a/jdl/models/jdl-deployment.ts +++ b/jdl/models/jdl-deployment.ts @@ -39,7 +39,7 @@ export default class JDLDeployment { clusteredDbApps?: string[]; constructor(args: ParsedJDLDeployment) { - if (!args || !args.deploymentType) { + if (!args?.deploymentType) { throw new Error('The deploymentType is mandatory to create a deployment.'); } const merged = merge(defaults(args.deploymentType), args); diff --git a/jdl/models/jdl-object.ts b/jdl/models/jdl-object.ts index 517d6198757a..fab49a86e46c 100644 --- a/jdl/models/jdl-object.ts +++ b/jdl/models/jdl-object.ts @@ -221,7 +221,7 @@ export default class JDLObject { } addOption(option: AbstractJDLOption): void { - if (!option || !option.getType) { + if (!option?.getType) { throw new Error("Can't add nil option."); } this.options.addOption(option); diff --git a/jdl/models/jdl-options.ts b/jdl/models/jdl-options.ts index b3d01fdcd7d8..cb32f1996de0 100644 --- a/jdl/models/jdl-options.ts +++ b/jdl/models/jdl-options.ts @@ -30,7 +30,7 @@ export default class JDLOptions { } addOption(option: AbstractJDLOption): void { - if (!option || !option.getType) { + if (!option?.getType) { throw new Error("Can't add nil option."); } if (option.getType() === 'UNARY') { diff --git a/jdl/parsing/validator.ts b/jdl/parsing/validator.ts index df8646f34ed9..1dbad7e47505 100644 --- a/jdl/parsing/validator.ts +++ b/jdl/parsing/validator.ts @@ -184,7 +184,7 @@ export default function performAdditionalSyntaxChecks(cst, runtime: JDLRuntime) // A Boolean is allowed as a single name as it is a keyword. // Other keywords do not need special handling as they do not explicitly appear in the rule // of config values - if (fqnCstNode.tokenType && fqnCstNode.tokenType.CATEGORIES.includes(this.tokens.BOOLEAN)) { + if (fqnCstNode.tokenType?.CATEGORIES.includes(this.tokens.BOOLEAN)) { return false; } @@ -305,7 +305,7 @@ export default function performAdditionalSyntaxChecks(cst, runtime: JDLRuntime) throw Error(`Got an invalid deployment config property: '${propertyName}'.`); } - if (this.checkExpectedValueType(validation.type, value) && validation.pattern && value.children && value.children.NAME) { + if (this.checkExpectedValueType(validation.type, value) && validation.pattern && value.children?.NAME) { value.children.NAME.forEach(nameTok => this.checkNameSyntax(nameTok, validation.pattern, validation.msg)); } else if (value.image && validation.pattern) { this.checkNameSyntax(value, validation.pattern, validation.msg); diff --git a/jdl/utils/format-utils.ts b/jdl/utils/format-utils.ts index 231119c33725..b07247356bc4 100644 --- a/jdl/utils/format-utils.ts +++ b/jdl/utils/format-utils.ts @@ -29,7 +29,7 @@ export default function formatComment(comment?: string): string | undefined { return undefined; } const parts = comment.trim().split('\n'); - if (parts.length === 1 && parts[0].indexOf('*') !== 0) { + if (parts.length === 1 && !parts[0].startsWith('*')) { return parts[0]; } return parts.reduce((previousValue, currentValue) => { diff --git a/jdl/validators/jdl-with-application-validator.ts b/jdl/validators/jdl-with-application-validator.ts index ea289708d44f..17527e090550 100644 --- a/jdl/validators/jdl-with-application-validator.ts +++ b/jdl/validators/jdl-with-application-validator.ts @@ -71,7 +71,7 @@ export default function createValidator(jdlObject: JDLObject, logger: any = cons function checkForNamespaceConfigErrors(jdlApplication: JDLApplication): void { jdlApplication.forEachNamespaceConfiguration(config => { const blueprints: JDLApplicationConfigurationOption | undefined = jdlApplication.config.getOption('blueprints'); - if (!blueprints || !blueprints.getValue().some(blueprint => blueprint === config.namespace)) { + if (!blueprints?.getValue().some(blueprint => blueprint === config.namespace)) { throw new Error(`Blueprint namespace config ${config.namespace} requires the blueprint ${config.namespace}`); } }); diff --git a/lib/types/application/entity.d.ts b/lib/types/application/entity.d.ts index b133a359c0de..8716a2ec3cfa 100644 --- a/lib/types/application/entity.d.ts +++ b/lib/types/application/entity.d.ts @@ -30,21 +30,24 @@ type AngularEntity = { entityAngularReadAuthorities?: string; }; +export type PrimaryKey = { + name: string; + fields: F[]; + derivedFields: F[]; + type: string; + composite: boolean; + derived: boolean; + javaValueGenerator?: string; + javaBuildSpecification?: string; +}; + export interface Entity extends Omit>, 'relationships'>, SpringEntity, AngularEntity { relationships: (IsNever extends true ? Relationship> : R)[]; - primaryKey?: { - fields: F[]; - derivedFields: F[]; - type: string; - composite: boolean; - derived: boolean; - javaValueGenerator?: string; - javaBuildSpecification?: string; - }; + primaryKey?: PrimaryKey; builtIn?: boolean; builtInUser?: boolean; @@ -62,6 +65,7 @@ export interface Entity extends BaseRelationship { +type RelationshipProperties = DerivedPropertiesOnlyOf< + 'relationship', + 'LeftSide' | 'RightSide' | 'ManyToOne' | 'OneToMany' | 'OneToOne' | 'ManyToMany' +>; + +export interface Relationship extends BaseRelationship, RelationshipProperties { propertyName: string; relationshipNameCapitalized: string; + otherEntity: E; + collection: boolean; skipClient?: boolean; skipServer?: boolean; @@ -13,11 +21,16 @@ export interface Relationship extends BaseRelationshi */ persistableRelationship: boolean; - otherEntity: E; - + id?: boolean; ownerSide?: boolean; relationshipEagerLoad?: boolean; propertyJavaBeanName?: string; propertyDtoJavaType?: string; + + onDelete?: boolean; + onUpdate?: boolean; + + /* TODO check motivation */ + relationshipSqlSafeName?: string; } diff --git a/lib/types/application/tasks.d.ts b/lib/types/application/tasks.d.ts index a1297bdd48df..f9987a9274ae 100644 --- a/lib/types/application/tasks.d.ts +++ b/lib/types/application/tasks.d.ts @@ -54,9 +54,9 @@ type LoadingEntitiesTaskParam> = TaskParamWit /** Entity storage */ entityStorage: Storage; /** Proxy object for the entitystorage */ - entityConfig: Record; + entityConfig: BaseEntity; /** Initial entity object */ - entityBootstrap: Record; + entityBootstrap: Entity; }[]; }; diff --git a/lib/types/base/field.d.ts b/lib/types/base/field.d.ts index 2cf809db416f..fa9c4e54334d 100644 --- a/lib/types/base/field.d.ts +++ b/lib/types/base/field.d.ts @@ -20,4 +20,5 @@ export type Field = { fieldName: string; fieldType: string; + options?: Record; }; diff --git a/lib/types/base/relationship.d.ts b/lib/types/base/relationship.d.ts index 8f14c149e134..762426a4b651 100644 --- a/lib/types/base/relationship.d.ts +++ b/lib/types/base/relationship.d.ts @@ -19,4 +19,12 @@ export type Relationship = { relationshipName: string; + otherEntityName: string; + relationshipType: string; + + relationshipSide?: 'left' | 'right'; + otherEntityRelationshipName?: string; + otherEntityField?: string; + + options?: Record; }; diff --git a/lib/types/utils/derived-properties.d.ts b/lib/types/utils/derived-properties.d.ts index c0be8c7d309b..e173b97ad011 100644 --- a/lib/types/utils/derived-properties.d.ts +++ b/lib/types/utils/derived-properties.d.ts @@ -1,5 +1,9 @@ import type { Simplify, ValueOf } from 'type-fest'; +export type DerivedPropertiesOnlyOf = Simplify<{ + [K in Choices as `${Property}${Capitalize}`]: boolean; +}>; + /* * @example * ```ts @@ -10,7 +14,7 @@ import type { Simplify, ValueOf } from 'type-fest'; export type DerivedPropertiesOf = Simplify< { [K in Choices as `${Property}${Capitalize}`]: boolean; - } & Record & + } & Record & Record<`${Property}Any`, boolean> >; diff --git a/lib/utils/yo-rc.ts b/lib/utils/yo-rc.ts index 1165ac3ddc1e..2935969d653c 100644 --- a/lib/utils/yo-rc.ts +++ b/lib/utils/yo-rc.ts @@ -1,4 +1,4 @@ -export const YO_RC_CONFIG_KEY = 'generator-jhipster' as const; +export const YO_RC_CONFIG_KEY = 'generator-jhipster'; type YoRcContent = Record;