Skip to content

Commit

Permalink
Type adjusts (#27194)
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima authored Sep 6, 2024
1 parent 031e60c commit 375f730
Show file tree
Hide file tree
Showing 110 changed files with 541 additions and 484 deletions.
18 changes: 8 additions & 10 deletions generators/angular/generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @ts-nocheck
/**
* Copyright 2013-2024 the original author or authors from the JHipster project.
*
Expand All @@ -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';
Expand All @@ -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';
Expand Down Expand Up @@ -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<Parameters<typeof addRoute>[0], 'needle'>) =>
Expand Down Expand Up @@ -394,18 +392,18 @@ 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 });

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);
}

Expand Down
6 changes: 3 additions & 3 deletions generators/angular/support/needles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 => {
Expand All @@ -73,7 +73,7 @@ export const addEntitiesRoute = asPostWritingEntitiesTask(function addEntitiesRo
});
}),
);
});
}

type MenuItem = {
jhiPrefix: string;
Expand Down
4 changes: 2 additions & 2 deletions generators/angular/support/translate-angular.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
}
}
Expand Down
2 changes: 2 additions & 0 deletions generators/app/__snapshots__/generator.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions generators/base-application/support/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,23 +47,23 @@ 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 => {
if (!doesTheEnumValueHaveACustomValue(enumValue)) {
return {
name: enumValue.trim(),
value: enumValue.trim(),
comment: comments && comments[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4),
comment: comments?.[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4),
};
}

const matched = /\s*(.+?)\s*\((.+?)\)/.exec(enumValue);
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),
};
});
};
Expand Down
8 changes: 4 additions & 4 deletions generators/base-application/support/prepare-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
});
Expand Down
10 changes: 5 additions & 5 deletions generators/base-application/support/prepare-field.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @ts-nocheck
/**
* Copyright 2013-2024 the original author or authors from the JHipster project.
*
Expand All @@ -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';

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -264,7 +264,7 @@ export default function prepareField(entityWithConfig, field, generator) {
prepareServerFieldForTemplates(entityWithConfig, field, generator);
}

prepareClientFieldForTemplates(entityWithConfig, field, generator);
prepareClientFieldForTemplates(entityWithConfig, field);
return field;
}

Expand Down Expand Up @@ -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],
};
});
}
Expand Down
17 changes: 13 additions & 4 deletions generators/base-application/support/prepare-relationship.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-nocheck
/**
* Copyright 2013-2024 the original author or authors from the JHipster project.
*
Expand All @@ -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;
Expand All @@ -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<Entity>,
generator: CoreGenerator,
ignoreMissingRequiredRelationship = false,
) {
const entityName = entityWithConfig.name;
const { otherEntityName, relationshipSide, relationshipType, relationshipName } = relationship;

Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion generators/base-application/support/relationship.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}.`);
Expand Down
10 changes: 6 additions & 4 deletions generators/base-core/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<const G extends string>(gen: G, options?: ComposeOptions<BaseApplicationGenerator>) {
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)) {
Expand Down Expand Up @@ -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<BaseApplicationGenerator>) {
return this.composeWithJHipster(generator, {
...options,
schedule: false,
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion generators/base-workspaces/internal/docker-prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`));
Expand Down
5 changes: 4 additions & 1 deletion generators/base/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@ export type ApplicationWithConfig = {
export type JHipsterGeneratorOptions = BaseOptions & {
/* cli options */
commandName: string;
programName: string;
positionalArguments?: unknown[];
createEnvBuilder?: any;

/* yeoman options */
skipYoResolve?: boolean;
sharedData: any;
force?: boolean;

/* base options */
defaults?: boolean;
applicationId?: string;
applicationWithConfig?: ApplicationWithConfig;
/**
Expand Down Expand Up @@ -191,7 +194,7 @@ export type WriteFileOptions<DataType = ApplicationType<Entity>, Generator = Cor
}
| {
/** templates to be written */
templates: WriteFileTemplate<DataType, Generator>;
templates: WriteFileTemplate<DataType, Generator>[];
}
| {
/** blocks to be written */
Expand Down
4 changes: 2 additions & 2 deletions generators/base/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ export default class JHipsterBaseBlueprintGenerator<TaskTypes extends BaseTaskTy
protected async composeWithBlueprints(subGen?: string, options?: ComposeOptions) {
if (subGen === undefined) {
const { namespace } = this.options;
if (!namespace || !namespace.startsWith('jhipster:')) {
if (!namespace?.startsWith('jhipster:')) {
throw new Error(`Generator is not blueprintable ${namespace}`);
}
subGen = namespace.substring('jhipster:'.length);
Expand Down Expand Up @@ -653,7 +653,7 @@ export default class JHipsterBaseBlueprintGenerator<TaskTypes extends BaseTaskTy
*/
private _findBlueprintVersion(blueprintPkgName) {
const blueprintPackageJson = this._findBlueprintPackageJson(blueprintPkgName);
if (!blueprintPackageJson || !blueprintPackageJson.version) {
if (!blueprintPackageJson?.version) {
this.log.warn(`Could not retrieve version of blueprint '${blueprintPkgName}'`);
return undefined;
}
Expand Down
4 changes: 2 additions & 2 deletions generators/base/internal/blueprint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { requireNamespace } from '@yeoman/namespace';
*/
export function loadBlueprintsFromConfiguration(config) {
// handle both config based on yeoman's Storage object, and direct configuration loaded from .yo-rc.json
const configuration = config && config.getAll && typeof config.getAll === 'function' ? config.getAll() || {} : config;
const configuration = config?.getAll && typeof config.getAll === 'function' ? config.getAll() || {} : config;
// load blueprints from config file
const blueprints = configuration.blueprints || [];

Expand Down Expand Up @@ -134,7 +134,7 @@ export function normalizeBlueprintName(blueprint) {
return ns.with({ unscoped: `generator-jhipster-${ns.unscoped}` }).toString();
// eslint-disable-next-line no-empty
} catch {}
if (blueprint && blueprint.startsWith('@')) {
if (blueprint?.startsWith('@')) {
return blueprint;
}
if (blueprint && !blueprint.startsWith('generator-jhipster')) {
Expand Down
2 changes: 1 addition & 1 deletion generators/base/support/basename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { camelCase } from 'lodash-es';
*/
export const getFrontendAppName = ({ baseName }: { baseName: string }) => {
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 }) => {
Expand Down
Loading

0 comments on commit 375f730

Please sign in to comment.