Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: transform bauta into an ESM module #165

Draft
wants to merge 31 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
675d850
fix(bautajs): transform to esm
Xavier-Redondo May 8, 2024
f319021
fix(bautajs): still does not work
Xavier-Redondo May 10, 2024
9d2713d
fix(bautajs): yes, it does not work yet
Xavier-Redondo May 10, 2024
0c2aaa9
fix(bautajs): still not working
Xavier-Redondo May 13, 2024
8b849a3
fix(bautajs): no
Xavier-Redondo May 13, 2024
4615726
fix(bautajs): almost, but this is hard
Xavier-Redondo May 13, 2024
38a66f9
fix(bautajs): now at least it works with fastify
Xavier-Redondo May 13, 2024
80e8236
Merge branch 'main' of https://github.com/axa-group/bauta.js into fea…
Xavier-Redondo May 13, 2024
a2841a3
fix(bautajs-core): change ts jest configuration to test with esm
Xavier-Redondo May 22, 2024
0eccbf6
Merge branch 'main' of https://github.com/axa-group/bauta.js into fea…
Xavier-Redondo May 22, 2024
8614c88
fix(bautajs-core): fix tests to run with esm
Xavier-Redondo May 22, 2024
be97623
Merge branch 'main' of https://github.com/axa-group/bauta.js into fea…
Xavier-Redondo May 27, 2024
a17349f
fix(bautajs-core): fix typing in certain tests that prevent build
Xavier-Redondo May 27, 2024
4621819
fix(bautajs-core): bauta core tests with esm pass... finally
Xavier-Redondo May 27, 2024
4df5dec
fix(bautajs-fastify): adapt bauta fastify to esm
Xavier-Redondo May 27, 2024
e57d24c
fix(bautajs-datasource-rest): fix tests with esm modules
Xavier-Redondo May 27, 2024
3bdc7dd
fix(bautajs-datasource-rest): fix tests with esm modules
Xavier-Redondo May 27, 2024
8697ce4
fix(bautajs-datasource-rest): remove document from test
Xavier-Redondo May 27, 2024
bd3ae5c
fix(bautajs-express-example): pass express example to esm
Xavier-Redondo May 28, 2024
6221f08
fix(bautajs-express): transform it to esm
Xavier-Redondo May 28, 2024
d2bad4c
fix(bautajs-fastify-example): add esm to bautajs-fastify-example
Xavier-Redondo May 28, 2024
d4619fe
fix(bautajs-express): we need to bootstrap bauta before applying expr…
Xavier-Redondo May 28, 2024
0d6a260
fix(bautajs-express): we need to bootstrap bauta before applying expr…
Xavier-Redondo May 28, 2024
f2fe320
fix(bautajs-express-example): add const declaration since esm is stri…
Xavier-Redondo May 28, 2024
4c767bd
fix(bautajs-core): remove a ton of console logs
Xavier-Redondo May 28, 2024
b2f8af0
fix(bautajs-fastify-versioning-example): transform it to use esm
Xavier-Redondo May 29, 2024
91935c7
fix(ci): test with a npm script to prepare release local
Xavier-Redondo Jun 6, 2024
74fa8cd
fix(ci): test with a npm script to prepare release local
Xavier-Redondo Jun 6, 2024
808dcfb
v4.0.0-alpha.0
Xavier-Redondo Jun 6, 2024
9ffde82
fix(ci): create experimental task to create beta releases, please do …
Xavier-Redondo Jun 6, 2024
8ee1c8f
fix(ci): test with a npm script to prepare release local improved
Xavier-Redondo Jun 6, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,5 @@ coverage/
test-report.xml

.turbo

.vscode
2 changes: 1 addition & 1 deletion lerna.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@
}
},
"useWorkspaces": true,
"version": "3.1.0"
"version": "4.0.0-alpha.0"
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"proxy",
"multipart"
],
"type": "module",
"workspaces": [
"packages/*"
],
Expand All @@ -31,6 +32,8 @@
"lint": "eslint \"*/**/*.{ts,js}\"",
"test": "turbo run test",
"release": "lerna changed && lerna publish --no-changelog --yes --no-commit-hooks",
"release:beta:prepare": "lerna version --conventional-prerelease --no-changelog --no-git-tag-version --no-private --no-push",
"release:beta:publish": "lerna publish from-package --no-changelog --yes --no-commit-hooks",
"checkDeps": "npx npm-check-updates -u && npm run lerna exec -- npx npm-check-updates -u",
"build": "turbo run build",
"prepare": "husky install"
Expand Down
11 changes: 6 additions & 5 deletions packages/bautajs-core/package.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
{
"name": "@axa/bautajs-core",
"version": "3.1.0",
"version": "4.0.0-alpha.0",
"description": "Bauta.js is an add-on for your Node.js applications such as Express.js or Fastify.",
"main": "dist",
"exports": "./dist/index.js",
"types": "dist",
"type": "module",
"files": [
"dist"
],
"scripts": {
"tsc": "tsc",
"build": "tsc --build",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
"test": "jest"
"test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js"
},
"bugs": {
"url": "https://github.com/axa-group/bauta.js/issues"
Expand All @@ -38,7 +39,7 @@
"@apidevtools/swagger-parser": "^10.1.0",
"ajv": "^8.12.0",
"ajv-formats": "^2.1.1",
"fast-glob": "^3.2.12",
"fast-glob": "^3.3.0",
"fast-safe-stringify": "^2.1.1",
"hyperid": "^3.1.1",
"openapi-types": "^12.1.0",
Expand All @@ -47,6 +48,6 @@
"quick-lru-cjs": "^5.2.1"
},
"devDependencies": {
"@axa/bautajs-dev-config": "^3.0.1"
"@axa/bautajs-dev-config": "^4.0.0-alpha.0"
}
}
93 changes: 64 additions & 29 deletions packages/bautajs-core/src/bauta.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import fastGlob from 'fast-glob';
import { resolve } from 'path';
import { resolve } from 'node:path';
import { OpenAPIV2 } from 'openapi-types';
import { OperationBuilder } from './core/operation';
import { defaultLogger } from './default-logger';
import { OperationBuilder } from './core/operation.js';
import { defaultLogger } from './default-logger.js';
import {
BautaJSInstance,
BautaJSOptions,
Document,
Logger,
Operations,
BasicOperation,
Validator
} from './types';
import { isLoggerValid } from './utils/logger-validator';
import Parser from './open-api/parser';
import { decorate } from './utils/decorate';
import { AjvValidator } from './open-api/ajv-validator';
Validator,
Resolver
} from './types.js';
import { isLoggerValid } from './utils/logger-validator.js';
import Parser from './open-api/parser.js';
import { decorate } from './utils/decorate.js';
import { AjvValidator } from './open-api/ajv-validator.js';

interface API {
version: string;
Expand Down Expand Up @@ -87,6 +88,13 @@ export class BautaJS implements BautaJSInstance {

private bootstrapped = false;

// to not load the resolvers twice (only relevant for versioning operations)
private resolversAlreadyLoaded = false;

private readonly resolversPath: string | string[] | undefined;

private resolvers: Resolver[] | undefined;

constructor({
apiDefinition,
staticConfig,
Expand All @@ -106,6 +114,7 @@ export class BautaJS implements BautaJSInstance {
this.staticConfig = staticConfig;

this.logger = logger || defaultLogger('@axa/bautajs-core');

if (!isLoggerValid(this.logger)) {
throw new Error(
'Logger is not valid. Must be compliant with basic logging levels(trace, debug, info, warn, error, fatal)'
Expand All @@ -123,24 +132,37 @@ export class BautaJS implements BautaJSInstance {
this.validator = new AjvValidator(customValidationFormats, validatorOptions);
this.operations = this.registerOperations(requestValidation, responseValidation, api);

// Load custom resolvers and operations modifiers
if (resolvers) {
resolvers.forEach(resolver => {
resolver(this.operations);
});
} else {
BautaJS.requireAll<[Operations]>(
resolversPath || './server/resolvers/**/*resolver.js',
true,
[this.operations]
);
// This is required for loadResolvers, done this way to not modify the bauta.js construction interface which would be a big clusterluck
this.resolvers = resolvers;
this.resolversPath = resolversPath;
}

public async loadResolvers(): Promise<void> {
if (this.resolversAlreadyLoaded === false) {
// Load custom resolvers and operations modifiers
if (this.resolvers) {
this.resolvers.forEach(resolver => {
resolver(this.operations);
});
} else {
await BautaJS.requireAll<[Operations]>(
this.resolversPath || './server/resolvers/**/*resolver.js',
true,
[this.operations]
);
}

this.resolversAlreadyLoaded = true;
}
}

public async bootstrap(): Promise<void> {
if (this.bootstrapped === true) {
throw new Error('The instance has already being bootstrapped.');
}

await this.loadResolvers();

if (this.apiDefinition) {
const parser = new Parser(this.logger);
const parsedApiDefinition = await parser.asyncParse(this.apiDefinition);
Expand Down Expand Up @@ -233,12 +255,16 @@ export class BautaJS implements BautaJSInstance {
*
* const files = requireAll('./my/path/to/datasources/*.js', true, {someVar:123});
*/
static requireAll<T>(folder: string | string[], execute = true, vars?: T) {
const execFiles = (folderPath: string) => {
static async requireAll<T>(folder: string | string[], execute = true, vars?: T) {
const execFiles = async (folderPath: string) => {
const result: any = [];
fastGlob.sync(folderPath.replace(/\\/g, '/')).forEach((file: string) => {
// eslint-disable-next-line global-require, import/no-dynamic-require, @typescript-eslint/no-var-requires
let data = require(resolve(file));
const files = await fastGlob.async(folderPath.replace(/\\/g, '/'));

for (let i = 0; i < files.length; i++) {
const file = files[i];

let data = await import(resolve(file));

if (data.default) {
data = data.default;
}
Expand All @@ -247,28 +273,37 @@ export class BautaJS implements BautaJSInstance {
}

result.push(data);
});
}

return result;
};

let files = [];
if (Array.isArray(folder)) {
files = folder.map(folderPath => execFiles(folderPath));
for (let i = 0; i < folder.length; i++) {
const folderPath = folder[i];
files.push(await execFiles(folderPath));
}
} else {
files = execFiles(folder);
files = await execFiles(folder);
}

return files;
}

public inheritOperationsFrom(bautajsInstance: BautaJSInstance) {
public async inheritOperationsFrom(bautajsInstance: BautaJSInstance) {
if (!(bautajsInstance instanceof BautaJS)) {
throw new Error('A bautaJS instance must be provided.');
}

if (this.bootstrapped === true) {
throw new Error('Operation inherit should be done before bootstrap the BautaJS instance.');
}

// We need to do this before the overriding of the operations
// When we do not version, this is done in bootstrap, but when we version, we need to do it here
await bautajsInstance.loadResolvers();

if (bautajsInstance.bootstrapped === false) {
this.logger.warn(
'The given instance is not bootstrapped, thus operation schema will be no inherited.'
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/core/cancelable-token.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CancelableToken, OnCancel } from '../types';
import { CancelableToken, OnCancel } from '../types.js';

export class CancelableTokenBuilder implements CancelableToken {
private cancelStack: OnCancel[] = [];
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/core/not-found-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class NotFoundError extends Error {
}

private formatStack() {
return `${this.name}: ${this.message} \n ${fastSafeStringify(this, undefined, 2)}`;
return `${this.name}: ${this.message} \n ${fastSafeStringify.default(this, undefined, 2)}`;
}

public toJSON() {
Expand Down
10 changes: 5 additions & 5 deletions packages/bautajs-core/src/core/operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import {
Pipeline,
Request,
RawData
} from '../types';
import { buildDefaultStep } from '../utils/default-step';
import { createContext } from '../utils/create-context';
import { isPromise } from '../utils/is-promise';
import { ValidationError } from './validation-error';
} from '../types.js';
import { buildDefaultStep } from '../utils/default-step.js';
import { createContext } from '../utils/create-context.js';
import { isPromise } from '../utils/is-promise.js';
import { ValidationError } from './validation-error.js';

export class OperationBuilder implements Operation {
public static create(id: string, bautajs: BautaJSInstance): Operation {
Expand Down
4 changes: 2 additions & 2 deletions packages/bautajs-core/src/core/validation-error.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fastSafeStringify from 'fast-safe-stringify';
import { IValidationError, LocationError } from '../types';
import { IValidationError, LocationError } from '../types.js';

export class ValidationError extends Error implements IValidationError {
public errors: LocationError[];
Expand All @@ -20,7 +20,7 @@ export class ValidationError extends Error implements IValidationError {
}

private formatStack() {
return `${this.name}: ${this.message} \n ${fastSafeStringify(this, undefined, 2)}`;
return `${this.name}: ${this.message} \n ${fastSafeStringify.default(this, undefined, 2)}`;
}

public toJSON() {
Expand Down
4 changes: 2 additions & 2 deletions packages/bautajs-core/src/decorators/as-promise.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { promisify } from 'util';
import { BautaJSInstance, Context, GenericError, Pipeline } from '../types';
import { promisify } from 'node:util';
import { BautaJSInstance, Context, GenericError, Pipeline } from '../types.js';

export type StepFunctionCallback<TIn, TOut> = (
prev: TIn,
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/as-value.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Pipeline } from '../types';
import { Pipeline } from '../types.js';

/**
*
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import nodeObjectHash from 'node-object-hash';
import QuickLRU, { Options } from 'quick-lru-cjs';
import { BautaJSInstance, Context, Pipeline } from '../types';
import { BautaJSInstance, Context, Pipeline } from '../types.js';

export interface Normalizer<TIn, CacheKey> {
(prev: TIn, ctx: Context, bautajs: BautaJSInstance): CacheKey;
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/iif.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BautaJSInstance, Context, Pipeline } from '../types';
import { BautaJSInstance, Context, Pipeline } from '../types.js';
/**
* @deprecated This function is deprecated and will be removed in future releases
*
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/map.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BautaJSInstance, Context } from '../types';
import { BautaJSInstance, Context } from '../types.js';
/**
* Decorator that allows to loop over the given selected array and map each item.
*
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/match.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BautaJSInstance, Context, Pipeline } from '../types';
import { BautaJSInstance, Context, Pipeline } from '../types.js';

/**
* Resolve the given predicate an execute the pipeline for that condition
Expand Down
4 changes: 2 additions & 2 deletions packages/bautajs-core/src/decorators/pairwise.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Pipeline } from '../types';
import { isPromise } from '../utils/is-promise';
import { Pipeline } from '../types.js';
import { isPromise } from '../utils/is-promise.js';
/**
* Decorator that returns the previous and current value as array
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Pipeline } from '../types';
import { Pipeline } from '../types.js';

export function parallelAllSettled<TIn, TOut1, TOut2>(
fn1: Pipeline.StepFunction<TIn, TOut1>,
Expand Down
4 changes: 2 additions & 2 deletions packages/bautajs-core/src/decorators/parallel-map.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BautaJSInstance, Context, Pipeline } from '../types';
import { map } from './map';
import { BautaJSInstance, Context, Pipeline } from '../types.js';
import { map } from './map.js';

/**
* Loop over the selected array and create a promise for each array item with the given mapFn, then it will resolve everything in parallel.
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/parallel.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Pipeline } from '../types';
import { Pipeline } from '../types.js';

export function parallel<TIn, TOut1, TOut2>(
fn1: Pipeline.StepFunction<TIn, TOut1>,
Expand Down
4 changes: 2 additions & 2 deletions packages/bautajs-core/src/decorators/pipeline.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BautaJSInstance, Context, GenericError, Pipeline } from '../types';
import { isPromise } from '../utils/is-promise';
import { BautaJSInstance, Context, GenericError, Pipeline } from '../types.js';
import { isPromise } from '../utils/is-promise.js';

export function compose<T, R>(
f1: Pipeline.StepFunction<T, R>,
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/resolver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Resolver } from '../types';
import { Resolver } from '../types.js';

export function resolver(fn: Resolver) {
return fn;
Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/retry-when.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Pipeline } from '../types';
import { Pipeline } from '../types.js';

const sleep = async (ms: number) => new Promise(resolve => setTimeout(resolve, ms).unref());

Expand Down
2 changes: 1 addition & 1 deletion packages/bautajs-core/src/decorators/step.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Pipeline } from '../types';
import { Pipeline } from '../types.js';

export function step<TIn, TOut>(fn: Pipeline.StepFunction<TIn, TOut>) {
return fn;
Expand Down
6 changes: 3 additions & 3 deletions packages/bautajs-core/src/decorators/tap.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { GenericError, Pipeline, Context, BautaJSInstance } from '../types';
import { isPromise } from '../utils/is-promise';
import { compose } from './pipeline';
import { GenericError, Pipeline, Context, BautaJSInstance } from '../types.js';
import { isPromise } from '../utils/is-promise.js';
import { compose } from './pipeline.js';

const defaultErrorHandler: Pipeline.CatchError<GenericError> = e => {
throw e;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BautaJSInstance, createContext, pipe } from '../../index';
import { asPromise } from '../as-promise';
import { BautaJSInstance, createContext, pipe } from '../../index.js';
import { asPromise } from '../as-promise.js';

describe('callback decorator', () => {
test('should execute as a callback', async () => {
Expand Down
Loading
Loading