Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/taefi/rename-ts-packages' into t…
Browse files Browse the repository at this point in the history
…aefi/rename-ts-packages
  • Loading branch information
taefi committed Jan 11, 2024
2 parents 31f903a + dce5983 commit 988ca13
Show file tree
Hide file tree
Showing 12 changed files with 66 additions and 65 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ packages/ts/*/.coverage
packages/ts/*/.vite
packages/ts/*/types/**
!packages/ts/*/.lintstagedrc.js
scripts/generator/results/
scripts/prepare/results/
packages/java/hilla/*.json
packages/java/hilla-react/*.json
packages/java/hilla/src/main/java/com/vaadin/hilla/theme/
Expand All @@ -50,7 +50,7 @@ packages/java/hilla-react/src/main/java/com/vaadin/hilla/theme/
packages/ts/*/*.tgz

# temporary scripts from platform for preparations
scripts/generator/src/
scripts/prepare/src/

# backup files from some editors
*~
4 changes: 2 additions & 2 deletions packages/ts/generator-cli/src/GeneratorIO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export default class GeneratorIO {
await Promise.all(
[...filesToDelete].map(async (filename) => {
const resolved = this.resolveGeneratedFile(filename);
if (await this.exists(resolved)) {
if (await GeneratorIO.exists(resolved)) {
this.#logger.global.debug(`Deleting file ${filename}.`);
await rm(resolved);
}
Expand Down Expand Up @@ -112,7 +112,7 @@ export default class GeneratorIO {
* @param path - the file path to check
*/
// eslint-disable-next-line class-methods-use-this
async exists(path: string): Promise<boolean> {
static async exists(path: string): Promise<boolean> {
try {
await access(path, constants.F_OK);
return true;
Expand Down
18 changes: 11 additions & 7 deletions packages/ts/generator-cli/test/GeneratorIO.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,20 @@ describe('Testing GeneratorIO', function (this: Mocha.Suite) {
describe('Testing GeneratorIO.exists', () => {
it('should detect that a file exists', async () => {
const path = join(tmpDir, generatedFilenames[0]);
await expect(io.exists(path)).to.eventually.be.true;
await expect(GeneratorIO.exists(path)).to.eventually.be.true;
});

it("should detect that a file doesn't exist", async () => {
const path = join(tmpDir, 'nobody-created-me');
await expect(io.exists(path)).to.eventually.be.false;
await expect(GeneratorIO.exists(path)).to.eventually.be.false;
});
});

describe('Testing GeneratorIO.createIndex', () => {
it('should create file index with right content', async () => {
await io.createFileIndex(generatedFilenames);
const indexPath = join(tmpDir, GeneratorIO.INDEX_FILENAME);
await expect(io.exists(indexPath)).to.eventually.be.true;
await expect(GeneratorIO.exists(indexPath)).to.eventually.be.true;
const content = await io.read(indexPath);
generatedFilenames.forEach((name) => expect(content).to.contain(name));
});
Expand All @@ -62,7 +62,7 @@ describe('Testing GeneratorIO', function (this: Mocha.Suite) {
await Promise.all(
generatedFilenames.map(async (name) => {
const path = join(tmpDir, name);
await expect(io.exists(path)).to.eventually.be.true;
await expect(GeneratorIO.exists(path)).to.eventually.be.true;
}),
);
});
Expand All @@ -84,7 +84,9 @@ describe('Testing GeneratorIO', function (this: Mocha.Suite) {
await expect(
io.cleanOutputDir([generatedFilenames[0], generatedFilenames[1]], new Set(generatedFilenames)),
).to.eventually.have.property('size', generatedFilenames.length - 2);
const existenceResults = await Promise.all(generatedFilenames.map(async (name) => io.exists(join(tmpDir, name))));
const existenceResults = await Promise.all(
generatedFilenames.map(async (name) => GeneratorIO.exists(join(tmpDir, name))),
);
expect(existenceResults).to.be.deep.equal([true, true, false]);
});

Expand All @@ -94,7 +96,9 @@ describe('Testing GeneratorIO', function (this: Mocha.Suite) {
'size',
generatedFilenames.length,
);
const existenceResults = await Promise.all(generatedFilenames.map(async (name) => io.exists(join(tmpDir, name))));
const existenceResults = await Promise.all(
generatedFilenames.map(async (name) => GeneratorIO.exists(join(tmpDir, name))),
);
expect(existenceResults).to.be.deep.equal([false, false, false]);
});

Expand All @@ -106,7 +110,7 @@ describe('Testing GeneratorIO', function (this: Mocha.Suite) {
'size',
generatedFilenames.length,
);
await expect(io.exists(join(tmpDir, name))).to.eventually.be.true;
await expect(GeneratorIO.exists(join(tmpDir, name))).to.eventually.be.true;
});
});
describe('Testing GeneratorIO.writeChangedFiles', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,7 @@ export class EntityClassModelProcessor extends EntityModelProcessor {
if (decomposed.length > 2) {
logger.debug(
this.#component,
`The schema for a class component ${
this.#fullyQualifiedName
} has more than two components. This plugin will ignore it.`,
`The schema for a class component ${this.#fullyQualifiedName} has more than two components. This plugin will ignore it.`,
);
return undefined;
}
Expand Down
67 changes: 32 additions & 35 deletions packages/ts/generator-plugin-model/src/MetadataProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,44 @@ export type SchemaWithMetadata = Schema & {
'x-java-type'?: string;
};

export class MetadataProcessor {
process(schema: Schema): ObjectLiteralExpression | null {
const schemaWithMetadata = schema as SchemaWithMetadata;
function createAnnotationsProperty(schema: SchemaWithMetadata): PropertyAssignment | null {
const annotations = schema['x-annotations'];
const hasAnnotations = annotations && annotations.length > 0;
if (!hasAnnotations) {
return null;
}

const properties = [
this.#createAnnotationsProperty(schemaWithMetadata),
this.#createJavaTypeProperty(schemaWithMetadata),
].filter(Boolean) as PropertyAssignment[];
const annotationLiterals = annotations.map((annotation) =>
ts.factory.createObjectLiteralExpression([
ts.factory.createPropertyAssignment('name', ts.factory.createStringLiteral(annotation.name)),
]),
);

if (properties.length === 0) {
return null;
}
return ts.factory.createPropertyAssignment(
'annotations',
ts.factory.createArrayLiteralExpression(annotationLiterals),
);
}

return ts.factory.createObjectLiteralExpression(properties);
function createJavaTypeProperty(schema: SchemaWithMetadata): PropertyAssignment | null {
const javaType = schema['x-java-type'];
if (!javaType) {
return null;
}

#createAnnotationsProperty(schema: SchemaWithMetadata): PropertyAssignment | null {
const annotations = schema['x-annotations'];
const hasAnnotations = annotations && annotations.length > 0;
if (!hasAnnotations) {
return null;
}

const annotationLiterals = annotations.map((annotation) =>
ts.factory.createObjectLiteralExpression([
ts.factory.createPropertyAssignment('name', ts.factory.createStringLiteral(annotation.name)),
]),
);

return ts.factory.createPropertyAssignment(
'annotations',
ts.factory.createArrayLiteralExpression(annotationLiterals),
);
}
return ts.factory.createPropertyAssignment('javaType', ts.factory.createStringLiteral(javaType));
}

export function process(schema: Schema): ObjectLiteralExpression | null {
const schemaWithMetadata = schema as SchemaWithMetadata;

#createJavaTypeProperty(schema: SchemaWithMetadata): PropertyAssignment | null {
const javaType = schema['x-java-type'];
if (!javaType) {
return null;
}
const properties = [createAnnotationsProperty(schemaWithMetadata), createJavaTypeProperty(schemaWithMetadata)].filter(
Boolean,
) as PropertyAssignment[];

return ts.factory.createPropertyAssignment('javaType', ts.factory.createStringLiteral(javaType));
if (properties.length === 0) {
return null;
}

return ts.factory.createObjectLiteralExpression(properties);
}
10 changes: 4 additions & 6 deletions packages/ts/generator-plugin-model/src/ModelSchemaProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import ts, {
type TypeNode,
type TypeReferenceNode,
} from 'typescript';
import { MetadataProcessor } from './MetadataProcessor.js';
import { process } from './MetadataProcessor.js';
import { createModelBuildingCallback, importBuiltInFormModel } from './utils.js';
import { hasValidationConstraints, ValidationConstraintProcessor } from './ValidationConstraintProcessor.js';

Expand Down Expand Up @@ -225,14 +225,12 @@ export class ModelSchemaTypeProcessor extends ModelSchemaPartProcessor<TypeRefer

export class ModelSchemaExpressionProcessor extends ModelSchemaPartProcessor<readonly Expression[]> {
readonly #validationConstraintProcessor: ValidationConstraintProcessor;
readonly #metadataProcessor: MetadataProcessor;

constructor(schema: Schema, dependencies: DependencyManager) {
super(schema, dependencies);
this.#validationConstraintProcessor = new ValidationConstraintProcessor((name) =>
importBuiltInFormModel(name, dependencies),
);
this.#metadataProcessor = new MetadataProcessor();
}

override process(): readonly ts.Expression[] {
Expand All @@ -242,7 +240,7 @@ export class ModelSchemaExpressionProcessor extends ModelSchemaPartProcessor<rea

const modelOptionsProperties = [
this.#createValidatorsProperty(originalSchema),
this.#createMetadataProperty(originalSchema),
ModelSchemaExpressionProcessor.#createMetadataProperty(originalSchema),
].filter(Boolean) as PropertyAssignment[];

if (modelOptionsProperties.length > 0) {
Expand Down Expand Up @@ -300,8 +298,8 @@ export class ModelSchemaExpressionProcessor extends ModelSchemaPartProcessor<rea
return ts.factory.createPropertyAssignment('validators', ts.factory.createArrayLiteralExpression(constraints));
}

#createMetadataProperty(schema: Schema): PropertyAssignment | null {
const metadata = this.#metadataProcessor.process(schema);
static #createMetadataProperty(schema: Schema): PropertyAssignment | null {
const metadata = process(schema);
return metadata ? ts.factory.createPropertyAssignment('meta', metadata) : null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ export class ValidationConstraintProcessor {
return ts.factory.createNewExpression(
this.#importer(constraint.simpleName),
undefined,
constraint.attributes ? [this.#processAttributes(constraint.attributes)] : [],
constraint.attributes ? [ValidationConstraintProcessor.#processAttributes(constraint.attributes)] : [],
);
}

#processAttributes(attributes: Record<string, unknown>): Expression {
static #processAttributes(attributes: Record<string, unknown>): Expression {
const names = Object.keys(attributes);
const tpl = JSON.stringify(names.includes('value') && names.length === 1 ? attributes.value : attributes);

Expand Down
12 changes: 6 additions & 6 deletions packages/ts/generator-plugin-push/src/PushProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export class PushProcessor {
);

if (importHillaCore) {
const updatedImportStatement = this.#removeInitImport(importHillaCore as ts.ImportDeclaration);
const updatedImportStatement = PushProcessor.#removeInitImport(importHillaCore as ts.ImportDeclaration);

if (updatedImportStatement) {
importStatements = importStatements.map((statement) => {
Expand All @@ -74,15 +74,15 @@ export class PushProcessor {
return createSourceFile(updatedStatements, this.#source.fileName);
}

#doesInitParameterExist(parameters: ts.NodeArray<ts.ParameterDeclaration>): boolean {
static #doesInitParameterExist(parameters: ts.NodeArray<ts.ParameterDeclaration>): boolean {
const last = parameters[parameters.length - 1];
const lastType = last.type as ts.TypeReferenceNode;
const lastTypeName = lastType.typeName as ts.Identifier;

return lastTypeName.text === initParameterTypeName;
}

#removeInitImport(importStatement: ts.ImportDeclaration): ts.Statement | undefined {
static #removeInitImport(importStatement: ts.ImportDeclaration): ts.Statement | undefined {
const namedImports = importStatement.importClause?.namedBindings;
if (namedImports && ts.isNamedImports(namedImports)) {
const updatedElements = namedImports.elements.filter((element) => element.name.text !== 'EndpointRequestInit');
Expand Down Expand Up @@ -119,7 +119,7 @@ export class PushProcessor {

#updateFunction(declaration: ts.FunctionDeclaration): ts.FunctionDeclaration {
const { parameters } = declaration;
const doesInitParameterExist = this.#doesInitParameterExist(parameters);
const doesInitParameterExist = PushProcessor.#doesInitParameterExist(parameters);

return ts.factory.createFunctionDeclaration(
undefined, // no async
Expand All @@ -129,11 +129,11 @@ export class PushProcessor {
// Remove the `init` parameter
doesInitParameterExist ? parameters.slice(0, -1) : parameters,
this.#replacePromiseType(declaration),
this.#updateFunctionBody(declaration, doesInitParameterExist),
PushProcessor.#updateFunctionBody(declaration, doesInitParameterExist),
);
}

#updateFunctionBody(declaration: ts.FunctionDeclaration, doesInitParameterExist: boolean): ts.Block {
static #updateFunctionBody(declaration: ts.FunctionDeclaration, doesInitParameterExist: boolean): ts.Block {
const returnStatement = declaration.body!.statements[0] as ts.ReturnStatement;
const { arguments: args, expression, typeArguments } = returnStatement.expression! as ts.CallExpression;
const call = expression as ts.PropertyAccessExpression;
Expand Down
2 changes: 2 additions & 0 deletions packages/ts/lit-form/src/BinderRoot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,8 @@ export class BinderRoot<M extends AbstractModel = AbstractModel> extends BinderN
* @param elm - the bound element
* @param model - the bound model
*/
// eslint ignored to allow overriding
// eslint-disable-next-line @typescript-eslint/class-methods-use-this
getFieldStrategy<TField>(elm: HTMLElement, model?: AbstractModel<TField>): FieldStrategy {
return getDefaultFieldStrategy(elm as FieldElement, model);
}
Expand Down
2 changes: 2 additions & 0 deletions packages/ts/react-crud/src/data-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ export abstract class DataProvider<TItem> {
}

export class InfiniteDataProvider<TItem> extends DataProvider<TItem> {
// cannot be static, otherwise it does not implement superclass
// eslint-disable-next-line @typescript-eslint/class-methods-use-this
protected fetchTotalCount(): undefined {
return undefined;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/ts/react-crud/test/GridController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export default class GridController {
return cells.map((cell) => (getCellContent(cell) as HTMLElement).innerText);
}

generateColumnHeaders(paths: readonly string[]): readonly string[] {
static generateColumnHeaders(paths: readonly string[]): readonly string[] {
return paths.map((path) =>
path
.substring(path.lastIndexOf('.') + 1)
Expand Down
2 changes: 1 addition & 1 deletion packages/ts/react-crud/test/autogrid.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export async function nextFrame(): Promise<void> {
async function assertColumnsOrder(grid: GridController, ...ids: string[]) {
const columns = await grid.getColumns();
expect(columns).to.have.length(ids.length);
await expect(grid.getHeaderCellContents()).to.eventually.deep.equal(grid.generateColumnHeaders(ids));
await expect(grid.getHeaderCellContents()).to.eventually.deep.equal(GridController.generateColumnHeaders(ids));
}

async function assertColumns(grid: GridController, ...ids: string[]) {
Expand Down

0 comments on commit 988ca13

Please sign in to comment.