diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..b9470778 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,2 @@ +node_modules/ +dist/ diff --git a/.eslintrc.json b/.eslintrc.json index 734ab0c7..b160b72b 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -22,10 +22,7 @@ "unused-imports" ], "rules": { - "indent": [ - "error", - 2 - ], + "indent": "off", // prettier takes care of this (yarn format) "quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }], "quote-props": ["error", "as-needed"], "semi": ["error", "always"], diff --git a/.prettierrc.json b/.prettierrc.json index f0eb61e0..0a725205 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -2,5 +2,5 @@ "trailingComma": "es5", "tabWidth": 2, "semi": true, - "singleQuote": false + "singleQuote": true } diff --git a/package.json b/package.json index 23ac74ab..a11b5869 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "build": "lerna run build --stream", "test": "lerna run test --stream", "lint": "lerna run lint --parallel", + "format": "lerna run format --parallel", "symlink": "symlink-workspace --logLevel error", "postinstall": "yarn symlink" }, @@ -22,7 +23,7 @@ "@typescript-eslint/parser": "^7.10.0", "copyfiles": "^2.4.1", "eslint": "^8.56.0", - "eslint-config-prettier": "^9.1.0", + "eslint-config-prettier": "^10.1.5", "eslint-plugin-simple-import-sort": "^12.1.0", "eslint-plugin-unused-imports": "^4.0.0", "glob": "8.0.3", @@ -30,7 +31,7 @@ "jest-in-case": "^1.0.2", "lerna": "^6", "mkdirp": "1.0.2", - "prettier": "^3.0.2", + "prettier": "^3.6.0", "rimraf": "4.4.1", "strip-ansi": "^6", "symlink-workspace": "^1.9.0", diff --git a/packages/ast/.eslintignore b/packages/ast/.eslintignore new file mode 120000 index 00000000..86039baf --- /dev/null +++ b/packages/ast/.eslintignore @@ -0,0 +1 @@ +../../.eslintignore \ No newline at end of file diff --git a/packages/ast/__tests__/babel/babel.test.ts b/packages/ast/__tests__/babel/babel.test.ts index 7117e1ec..d60c3fbc 100644 --- a/packages/ast/__tests__/babel/babel.test.ts +++ b/packages/ast/__tests__/babel/babel.test.ts @@ -7,7 +7,7 @@ import { classDeclaration, classProperty, promiseTypeAnnotation, - typedIdentifier + typedIdentifier, } from '../../src/utils/babel'; import { expectCode } from '../../test-utils'; @@ -54,12 +54,12 @@ it('interfaces', async () => { 'limit', t.tsTypeAnnotation(t.tsStringKeyword()), true - ) + ), ], promiseTypeAnnotation('TokensResponse') ) ) - ) + ), ]) ) ), @@ -73,7 +73,7 @@ it('interfaces', async () => { [ t.tSExpressionWithTypeArguments( t.identifier('SG721ReadOnlyInstance') - ) + ), ], t.tSInterfaceBody([ // contract address @@ -101,15 +101,15 @@ it('interfaces', async () => { typedIdentifier( 'prop3', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], promiseTypeAnnotation('ExecuteResult') ) ) - ) + ), ]) ) - ) + ), ]) ); }); @@ -149,7 +149,7 @@ it('readonly classes', async () => { typedIdentifier( 'contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], t.blockStatement([ // client/contract set @@ -178,7 +178,7 @@ it('readonly classes', async () => { bindMethod('approval'), bindMethod('otherProp'), bindMethod('hello'), - bindMethod('mintme') + bindMethod('mintme'), ]) ), @@ -196,7 +196,7 @@ it('readonly classes', async () => { typedIdentifier( 'spender', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], t.blockStatement([ t.returnStatement( @@ -227,31 +227,31 @@ it('readonly classes', async () => { t.identifier('spender'), false, true - ) - ]) + ), + ]), ] ) - ) + ), ]), t.tsTypeAnnotation( t.tsTypeReference( t.identifier('Promise'), t.tsTypeParameterInstantiation([ - t.tSTypeReference(t.identifier('ApprovalResponse')) + t.tSTypeReference(t.identifier('ApprovalResponse')), ]) ) ), true ) - ) + ), ], [ t.tSExpressionWithTypeArguments( t.identifier('SG721ReadOnlyInstance') - ) + ), ] ) - ) + ), ]) ); }); @@ -291,14 +291,14 @@ it('mutation classes', async () => { typedIdentifier( 'contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], t.blockStatement([ // super() t.expressionStatement( t.callExpression(t.super(), [ t.identifier('client'), - t.identifier('contractAddress') + t.identifier('contractAddress'), ]) ), @@ -328,7 +328,7 @@ it('mutation classes', async () => { bindMethod('approval'), bindMethod('otherProp'), bindMethod('hello'), - bindMethod('mintme') + bindMethod('mintme'), ]) ), @@ -353,7 +353,7 @@ it('mutation classes', async () => { typedIdentifier( 'token_uri', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], t.blockStatement([ t.returnStatement( @@ -391,37 +391,37 @@ it('mutation classes', async () => { t.objectProperty( t.identifier('expression'), t.objectExpression([]) - ) + ), ]) - ) + ), ]), - t.stringLiteral('auto') + t.stringLiteral('auto'), ] ) ) - ) + ), ]), // return type t.tsTypeAnnotation( t.tsTypeReference( t.identifier('Promise'), t.tsTypeParameterInstantiation([ - t.tSTypeReference(t.identifier('ExecuteResult')) + t.tSTypeReference(t.identifier('ExecuteResult')), ]) ) ), true ) - ) + ), ], [ t.tSExpressionWithTypeArguments( t.identifier('SG721ReadOnlyInstance') - ) + ), ], t.identifier('SG721QueryClient') ) - ) + ), ]) ); }); @@ -439,7 +439,7 @@ it('object parms', () => { t.identifier('tokenId'), false, true - ) + ), ]); obj.typeAnnotation = t.tsTypeAnnotation( t.tsTypeLiteral([ @@ -450,7 +450,7 @@ it('object parms', () => { t.tsPropertySignature( t.identifier('tokenId'), t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ]) ); expectCode( @@ -471,13 +471,13 @@ it('object parms', () => { t.tsTypeReference( t.identifier('Promise'), t.tsTypeParameterInstantiation([ - t.tsTypeReference(t.identifier('OwnerOfResponse')) + t.tsTypeReference(t.identifier('OwnerOfResponse')), ]) ) ) ) ) - ) + ), ]) ); }); diff --git a/packages/ast/__tests__/client/ts-client.account-nfts.test.ts b/packages/ast/__tests__/client/ts-client.account-nfts.test.ts index cb411426..aec60e76 100644 --- a/packages/ast/__tests__/client/ts-client.account-nfts.test.ts +++ b/packages/ast/__tests__/client/ts-client.account-nfts.test.ts @@ -5,7 +5,7 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; import { expectCode, makeContext } from '../../test-utils'; diff --git a/packages/ast/__tests__/client/ts-client.arrays-item-tuples.test.ts b/packages/ast/__tests__/client/ts-client.arrays-item-tuples.test.ts index 9c60d6c3..5a768d0d 100644 --- a/packages/ast/__tests__/client/ts-client.arrays-item-tuples.test.ts +++ b/packages/ast/__tests__/client/ts-client.arrays-item-tuples.test.ts @@ -1,40 +1,34 @@ import { createExecuteClass, createExecuteInterface, - createQueryClass} from '../../src'; -import { expectCode, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; + createQueryClass, +} from '../../src'; +import { + expectCode, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; const queryMsg = getMsgQueryLegacyFixture('misc/schema', '/arrays.json'); const execMsg = getMsgExecuteLegacyFixture('misc/schema', '/arrays.json'); const ctx = makeContext(queryMsg, { types: { - itemsUseTuples: true - } + itemsUseTuples: true, + }, }); it('query classes', () => { - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsg - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', queryMsg) + ); }); it('execute classes array types', () => { - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - execMsg - )); + expectCode(createExecuteInterface(ctx, 'SG721Instance', null, execMsg)); }); diff --git a/packages/ast/__tests__/client/ts-client.arrays-ref.test.ts b/packages/ast/__tests__/client/ts-client.arrays-ref.test.ts index ed996007..7387fd0b 100644 --- a/packages/ast/__tests__/client/ts-client.arrays-ref.test.ts +++ b/packages/ast/__tests__/client/ts-client.arrays-ref.test.ts @@ -2,46 +2,35 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; +import { + expectCode, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; const queryMsg = getMsgQueryLegacyFixture('misc/schema', '/arrays-ref.json'); const execMsg = getMsgExecuteLegacyFixture('misc/schema', '/arrays-ref.json'); const ctx = makeContext(queryMsg); it('execute_msg_for__empty', () => { - expectCode(createTypeInterface( - ctx, - queryMsg - )); + expectCode(createTypeInterface(ctx, queryMsg)); }); - it('query classes', () => { - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsg - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', queryMsg) + ); }); it('execute classes array types', () => { - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - execMsg - )); + expectCode(createExecuteInterface(ctx, 'SG721Instance', null, execMsg)); }); diff --git a/packages/ast/__tests__/client/ts-client.arrays.test.ts b/packages/ast/__tests__/client/ts-client.arrays.test.ts index 1827d813..8fbaf2c1 100644 --- a/packages/ast/__tests__/client/ts-client.arrays.test.ts +++ b/packages/ast/__tests__/client/ts-client.arrays.test.ts @@ -2,10 +2,15 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; import { getPropertyType } from '../../src/utils'; -import { expectCode, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; +import { + expectCode, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; const queryMsg = getMsgQueryLegacyFixture('misc/schema', '/arrays.json'); const execMsg = getMsgExecuteLegacyFixture('misc/schema', '/arrays.json'); const ctx = makeContext(queryMsg); @@ -22,37 +27,21 @@ it('getPropertyType', () => { }); it('execute_msg_for__empty', () => { - expectCode(createTypeInterface( - ctx, - queryMsg - )); + expectCode(createTypeInterface(ctx, queryMsg)); }); - it('query classes', () => { - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsg - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', queryMsg) + ); }); it('execute classes array types', () => { - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - execMsg - )); + expectCode(createExecuteInterface(ctx, 'SG721Instance', null, execMsg)); }); diff --git a/packages/ast/__tests__/client/ts-client.cw-named-groups.test.ts b/packages/ast/__tests__/client/ts-client.cw-named-groups.test.ts index a7476c47..18265842 100644 --- a/packages/ast/__tests__/client/ts-client.cw-named-groups.test.ts +++ b/packages/ast/__tests__/client/ts-client.cw-named-groups.test.ts @@ -2,45 +2,40 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; -const execMsg = getMsgExecuteLegacyFixture('daodao/cw-named-groups', '/execute_msg.json'); -const queryMsg = getMsgQueryLegacyFixture('daodao/cw-named-groups', '/execute_msg.json'); +import { + expectCode, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; +const execMsg = getMsgExecuteLegacyFixture( + 'daodao/cw-named-groups', + '/execute_msg.json' +); +const queryMsg = getMsgQueryLegacyFixture( + 'daodao/cw-named-groups', + '/execute_msg.json' +); const ctx = makeContext(execMsg); it('execute_msg', () => { - expectCode(createTypeInterface( - ctx, - execMsg - )); + expectCode(createTypeInterface(ctx, execMsg)); }); - it('query classes', () => { - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsg - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', queryMsg) + ); }); it('execute classes array types', () => { - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - execMsg - )); + expectCode(createExecuteInterface(ctx, 'SG721Instance', null, execMsg)); }); diff --git a/packages/ast/__tests__/client/ts-client.cw-proposal-single.test.ts b/packages/ast/__tests__/client/ts-client.cw-proposal-single.test.ts index 62f4e3b7..b8b4761a 100644 --- a/packages/ast/__tests__/client/ts-client.cw-proposal-single.test.ts +++ b/packages/ast/__tests__/client/ts-client.cw-proposal-single.test.ts @@ -2,49 +2,44 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; +import { + expectCode, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; -const execMsg = getMsgExecuteLegacyFixture('daodao/cw-proposal-single', '/execute_msg.json'); -const queryMsg = getMsgQueryLegacyFixture('daodao/cw-proposal-single', '/query_msg.json'); +const execMsg = getMsgExecuteLegacyFixture( + 'daodao/cw-proposal-single', + '/execute_msg.json' +); +const queryMsg = getMsgQueryLegacyFixture( + 'daodao/cw-proposal-single', + '/query_msg.json' +); it('execute_msg_for', () => { const ctx = makeContext(execMsg); - expectCode(createTypeInterface( - ctx, - execMsg - )); + expectCode(createTypeInterface(ctx, execMsg)); }); - it('query classes', () => { const ctx = makeContext(queryMsg); - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsg - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', queryMsg) + ); }); it('execute classes array types', () => { const ctx = makeContext(execMsg); - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('execute interfaces no extends', () => { const ctx = makeContext(execMsg); - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - execMsg - )); + expectCode(createExecuteInterface(ctx, 'SG721Instance', null, execMsg)); }); diff --git a/packages/ast/__tests__/client/ts-client.declare.test.ts b/packages/ast/__tests__/client/ts-client.declare.test.ts index 99262cf8..124528f3 100644 --- a/packages/ast/__tests__/client/ts-client.declare.test.ts +++ b/packages/ast/__tests__/client/ts-client.declare.test.ts @@ -1,67 +1,70 @@ +import { createExecuteClass } from '../../src'; import { - createExecuteClass -} from '../../src'; -import { expectCode, getMsgExecuteLegacyFixture, makeContext } from '../../test-utils'; + expectCode, + getMsgExecuteLegacyFixture, + makeContext, +} from '../../test-utils'; -const execMsg = getMsgExecuteLegacyFixture('sg721', '/execute_msg_for__empty.json'); +const execMsg = getMsgExecuteLegacyFixture( + 'sg721', + '/execute_msg_for__empty.json' +); const ctx = makeContext(execMsg); it('noDeclare, execExtends, noExtendsClass', () => { ctx.options.client.useDeclareKeyword = false; ctx.options.client.execExtendsQuery = true; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('noDeclare, execExtends, ExtendsClass', () => { ctx.options.client.useDeclareKeyword = false; ctx.options.client.execExtendsQuery = true; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - 'ExtendsClassName', - execMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + 'ExtendsClassName', + execMsg + ) + ); }); it('useDeclare, execExtends, ExtendsClass', () => { ctx.options.client.useDeclareKeyword = true; ctx.options.client.execExtendsQuery = true; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - 'ExtendsClassName', - execMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + 'ExtendsClassName', + execMsg + ) + ); }); it('useDeclare, noExecExtends, ExtendsClass', () => { ctx.options.client.useDeclareKeyword = true; ctx.options.client.execExtendsQuery = false; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - 'ExtendsClassName', - execMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + 'ExtendsClassName', + execMsg + ) + ); }); it('useDeclare, noExecExtends, noExtendsClass', () => { ctx.options.client.useDeclareKeyword = true; ctx.options.client.execExtendsQuery = false; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); diff --git a/packages/ast/__tests__/client/ts-client.empty-enums.test.ts b/packages/ast/__tests__/client/ts-client.empty-enums.test.ts index 6b703788..faa14ba7 100644 --- a/packages/ast/__tests__/client/ts-client.empty-enums.test.ts +++ b/packages/ast/__tests__/client/ts-client.empty-enums.test.ts @@ -1,27 +1,22 @@ +import { createQueryClass, createQueryInterface } from '../../src'; import { - createQueryClass, - createQueryInterface -} from '../../src'; -import { expectCode, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; + expectCode, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; -const queryMsg = getMsgQueryLegacyFixture('daodao/cw-admin-factory', '/query_msg.json'); +const queryMsg = getMsgQueryLegacyFixture( + 'daodao/cw-admin-factory', + '/query_msg.json' +); const ctx = makeContext(queryMsg); it('query classes', () => { - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsg - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', queryMsg) + ); }); it('query interface', () => { - expectCode( - createQueryInterface( - ctx, - 'ReadOnlyInstance', - queryMsg - ) - ); + expectCode(createQueryInterface(ctx, 'ReadOnlyInstance', queryMsg)); }); diff --git a/packages/ast/__tests__/client/ts-client.issue-101.test.ts b/packages/ast/__tests__/client/ts-client.issue-101.test.ts index 713519f5..1f4498b1 100644 --- a/packages/ast/__tests__/client/ts-client.issue-101.test.ts +++ b/packages/ast/__tests__/client/ts-client.issue-101.test.ts @@ -3,28 +3,32 @@ import { ExecuteMsg } from '@cosmwasm/ts-codegen-types'; import { createExecuteClass, createExecuteInterface } from '../../src'; import { expectCode, globLegacyContracts, makeContext } from '../../test-utils'; -const contract = globLegacyContracts('basic').find(c => c.name === '/ownership.json')!; +const contract = globLegacyContracts('basic').find( + (c) => c.name === '/ownership.json' +)!; const ownership = contract.content; it('execute interfaces no extends', () => { const ctx = makeContext(ownership); - expectCode(createExecuteInterface( - ctx, - 'OwnershipInstance', - null, - ownership as ExecuteMsg - )); + expectCode( + createExecuteInterface( + ctx, + 'OwnershipInstance', + null, + ownership as ExecuteMsg + ) + ); }); it('ownership client with tuple', () => { const ctx = makeContext(ownership); - expectCode(createExecuteClass( - ctx, - 'OwnershipClient', - 'OwnershipInstance', - null, - ownership as ExecuteMsg - )); + expectCode( + createExecuteClass( + ctx, + 'OwnershipClient', + 'OwnershipInstance', + null, + ownership as ExecuteMsg + ) + ); }); - - diff --git a/packages/ast/__tests__/client/ts-client.issue-103.test.ts b/packages/ast/__tests__/client/ts-client.issue-103.test.ts index 526aef67..59c943f1 100644 --- a/packages/ast/__tests__/client/ts-client.issue-103.test.ts +++ b/packages/ast/__tests__/client/ts-client.issue-103.test.ts @@ -2,14 +2,15 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; import { expectCode, globLegacyContracts, makeContext } from '../../test-utils'; -const globbed = globLegacyContracts('issues/103').find(c => c.name === '/schema.json')!; +const globbed = globLegacyContracts('issues/103').find( + (c) => c.name === '/schema.json' +)!; const contract = globbed.content; - // @ts-ignore const queryMessage = contract.query; // @ts-ignore @@ -19,93 +20,72 @@ const executeCtx = makeContext(executeMessage); describe('query', () => { it('execute_msg_for__empty', () => { - expectCode(createTypeInterface( - queryCtx, - queryMessage - )); + expectCode(createTypeInterface(queryCtx, queryMessage)); }); - it('query classes', () => { - expectCode(createQueryClass( - queryCtx, - 'QueryClient', - 'ReadOnlyInstance', - queryMessage - )); + expectCode( + createQueryClass( + queryCtx, + 'QueryClient', + 'ReadOnlyInstance', + queryMessage + ) + ); }); it('query classes response', () => { - expectCode(createTypeInterface( - queryCtx, - queryMessage - )); + expectCode(createTypeInterface(queryCtx, queryMessage)); }); it('execute classes array types', () => { - expectCode(createExecuteClass( - queryCtx, - 'Client', - 'Instance', - null, - queryMessage - )); + expectCode( + createExecuteClass(queryCtx, 'Client', 'Instance', null, queryMessage) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - queryCtx, - 'SG721Instance', - null, - queryMessage - )); + expectCode( + createExecuteInterface(queryCtx, 'SG721Instance', null, queryMessage) + ); }); - }); describe('execute', () => { it('execute_msg_for__empty', () => { - expectCode(createTypeInterface( - executeCtx, - executeMessage - )); + expectCode(createTypeInterface(executeCtx, executeMessage)); }); - it('query classes', () => { - expectCode(createQueryClass( - executeCtx, - 'QueryClient', - 'ReadOnlyInstance', - executeMessage - )); + expectCode( + createQueryClass( + executeCtx, + 'QueryClient', + 'ReadOnlyInstance', + executeMessage + ) + ); }); it('query classes response', () => { - expectCode(createTypeInterface( - executeCtx, - // @ts-ignore - queryMessage - )); + expectCode( + createTypeInterface( + executeCtx, + // @ts-ignore + queryMessage + ) + ); }); it('execute classes array types', () => { - expectCode(createExecuteClass( - executeCtx, - 'Client', - 'Instance', - null, - executeMessage - )); + expectCode( + createExecuteClass(executeCtx, 'Client', 'Instance', null, executeMessage) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - executeCtx, - 'SG721Instance', - null, - executeMessage - )); + expectCode( + createExecuteInterface(executeCtx, 'SG721Instance', null, executeMessage) + ); }); - }); diff --git a/packages/ast/__tests__/client/ts-client.issue-71.test.ts b/packages/ast/__tests__/client/ts-client.issue-71.test.ts index 087d46c6..e43a16e2 100644 --- a/packages/ast/__tests__/client/ts-client.issue-71.test.ts +++ b/packages/ast/__tests__/client/ts-client.issue-71.test.ts @@ -5,49 +5,67 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; import { globLegacyContracts, makeContext } from '../../test-utils'; import { expectCode } from '../../test-utils'; const contracts = globLegacyContracts('issues/71'); -cases('execute_msg_for__empty', async opts => { - const ctx = makeContext(opts.content); - expectCode(createTypeInterface( - ctx, - opts.content - )); -}, contracts); +cases( + 'execute_msg_for__empty', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode(createTypeInterface(ctx, opts.content)); + }, + contracts +); -cases('query classes', async opts => { - const ctx = makeContext(opts.content); - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', +cases( + 'query classes', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode( + createQueryClass( + ctx, + 'SG721QueryClient', + 'SG721ReadOnlyInstance', opts.content as QueryMsg - )); -}, contracts); + ) + ); + }, + contracts +); -cases('execute class', async opts => { - const ctx = makeContext(opts.content); - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, +cases( + 'execute class', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + null, opts.content as ExecuteMsg - )); -}, contracts); + ) + ); + }, + contracts +); -cases('execute interface', async opts => { - const ctx = makeContext(opts.content); - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, +cases( + 'execute interface', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode( + createExecuteInterface( + ctx, + 'SG721Instance', + null, opts.content as ExecuteMsg - )); -}, contracts); - + ) + ); + }, + contracts +); diff --git a/packages/ast/__tests__/client/ts-client.issue-98.test.ts b/packages/ast/__tests__/client/ts-client.issue-98.test.ts index 509ed900..25b5dbc2 100644 --- a/packages/ast/__tests__/client/ts-client.issue-98.test.ts +++ b/packages/ast/__tests__/client/ts-client.issue-98.test.ts @@ -4,30 +4,29 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode, globIdlBasedContracts,makeContext } from '../../test-utils'; +import { + expectCode, + globIdlBasedContracts, + makeContext, +} from '../../test-utils'; -const contract = globIdlBasedContracts('issues/98').find(c => c.name === '/schema.json')!; +const contract = globIdlBasedContracts('issues/98').find( + (c) => c.name === '/schema.json' +)!; const message = contract.content.query; const ctx = makeContext(message); it('execute_msg_for__empty', () => { - expectCode(createTypeInterface( - ctx, - message - )); + expectCode(createTypeInterface(ctx, message)); }); - it('query classes', () => { - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - message - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', message) + ); }); // it('query classes response', () => { @@ -38,22 +37,26 @@ it('query classes', () => { // }); it('execute classes array types', () => { - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - // @ts-ignore - message as ExecuteMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + null, + // @ts-ignore + message as ExecuteMsg + ) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - // @ts-ignore - message - )); + expectCode( + createExecuteInterface( + ctx, + 'SG721Instance', + null, + // @ts-ignore + message + ) + ); }); diff --git a/packages/ast/__tests__/client/ts-client.issues.test.ts b/packages/ast/__tests__/client/ts-client.issues.test.ts index d6d58df4..973e4fb9 100644 --- a/packages/ast/__tests__/client/ts-client.issues.test.ts +++ b/packages/ast/__tests__/client/ts-client.issues.test.ts @@ -5,49 +5,66 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode,globLegacyContracts, makeContext } from '../../test-utils'; +import { expectCode, globLegacyContracts, makeContext } from '../../test-utils'; const contracts = globLegacyContracts('issues/55'); +cases( + 'execute_msg_for__empty', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode(createTypeInterface(ctx, opts.content)); + }, + contracts +); -cases('execute_msg_for__empty', async opts => { - const ctx = makeContext(opts.content); - expectCode(createTypeInterface( - ctx, - opts.content - )); -}, contracts); - -cases('query classes', async opts => { - const ctx = makeContext(opts.content); - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', +cases( + 'query classes', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode( + createQueryClass( + ctx, + 'SG721QueryClient', + 'SG721ReadOnlyInstance', opts.content as QueryMsg - )); -}, contracts); + ) + ); + }, + contracts +); -cases('execute class', async opts => { - const ctx = makeContext(opts.content); - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, +cases( + 'execute class', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + null, opts.content as ExecuteMsg - )); -}, contracts); + ) + ); + }, + contracts +); -cases('execute interface', async opts => { - const ctx = makeContext(opts.content); - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, +cases( + 'execute interface', + async (opts) => { + const ctx = makeContext(opts.content); + expectCode( + createExecuteInterface( + ctx, + 'SG721Instance', + null, opts.content as ExecuteMsg - )); -}, contracts); - + ) + ); + }, + contracts +); diff --git a/packages/ast/__tests__/client/ts-client.overrides.test.ts b/packages/ast/__tests__/client/ts-client.overrides.test.ts index 6b28f5b4..dcbfaad5 100644 --- a/packages/ast/__tests__/client/ts-client.overrides.test.ts +++ b/packages/ast/__tests__/client/ts-client.overrides.test.ts @@ -1,67 +1,70 @@ +import { createExecuteClass } from '../../src'; import { - createExecuteClass -} from '../../src'; -import { expectCode, getMsgExecuteLegacyFixture, makeContext } from '../../test-utils'; + expectCode, + getMsgExecuteLegacyFixture, + makeContext, +} from '../../test-utils'; -const execMsg = getMsgExecuteLegacyFixture('sg721', '/execute_msg_for__empty.json'); +const execMsg = getMsgExecuteLegacyFixture( + 'sg721', + '/execute_msg_for__empty.json' +); const ctx = makeContext(execMsg); it('Impl, execExtends, noExtendsClass', () => { ctx.options.client.noImplicitOverride = false; ctx.options.client.execExtendsQuery = true; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('Impl, execExtends, ExtendsClass', () => { ctx.options.client.noImplicitOverride = false; ctx.options.client.execExtendsQuery = true; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - 'ExtendsClassName', - execMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + 'ExtendsClassName', + execMsg + ) + ); }); it('noImpl, execExtends, ExtendsClass', () => { ctx.options.client.noImplicitOverride = true; ctx.options.client.execExtendsQuery = true; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - 'ExtendsClassName', - execMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + 'ExtendsClassName', + execMsg + ) + ); }); it('noImpl, noExecExtends, ExtendsClass', () => { ctx.options.client.noImplicitOverride = true; ctx.options.client.execExtendsQuery = false; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - 'ExtendsClassName', - execMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + 'ExtendsClassName', + execMsg + ) + ); }); it('noImpl, noExecExtends, noExtendsClass', () => { ctx.options.client.noImplicitOverride = true; ctx.options.client.execExtendsQuery = false; - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); diff --git a/packages/ast/__tests__/client/ts-client.sg721.test.ts b/packages/ast/__tests__/client/ts-client.sg721.test.ts index 41eca6ce..01ba6870 100644 --- a/packages/ast/__tests__/client/ts-client.sg721.test.ts +++ b/packages/ast/__tests__/client/ts-client.sg721.test.ts @@ -2,46 +2,41 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; +import { + expectCode, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; -const execMsg = getMsgExecuteLegacyFixture('sg721', '/execute_msg_for__empty.json'); -const queryMsg = getMsgQueryLegacyFixture('sg721', '/execute_msg_for__empty.json'); +const execMsg = getMsgExecuteLegacyFixture( + 'sg721', + '/execute_msg_for__empty.json' +); +const queryMsg = getMsgQueryLegacyFixture( + 'sg721', + '/execute_msg_for__empty.json' +); const ctx = makeContext(execMsg); it('execute_msg_for__empty', () => { - expectCode(createTypeInterface( - ctx, - execMsg - )); + expectCode(createTypeInterface(ctx, execMsg)); }); - it('query classes', () => { - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsg - )); + expectCode( + createQueryClass(ctx, 'SG721QueryClient', 'SG721ReadOnlyInstance', queryMsg) + ); }); it('execute classes array types', () => { - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - execMsg - )); + expectCode( + createExecuteClass(ctx, 'SG721Client', 'SG721Instance', null, execMsg) + ); }); it('execute interfaces no extends', () => { - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - execMsg - )); + expectCode(createExecuteInterface(ctx, 'SG721Instance', null, execMsg)); }); diff --git a/packages/ast/__tests__/client/ts-client.test.ts b/packages/ast/__tests__/client/ts-client.test.ts index 8a5d098a..779e393d 100644 --- a/packages/ast/__tests__/client/ts-client.test.ts +++ b/packages/ast/__tests__/client/ts-client.test.ts @@ -3,164 +3,170 @@ import { createExecuteInterface, createQueryClass, createQueryInterface, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode, getLegacyFixture, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; +import { + expectCode, + getLegacyFixture, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; -const daodaoCwNamedGroupsExecuteMsg = getMsgExecuteLegacyFixture('daodao/cw-named-groups', '/execute_msg.json'); +const daodaoCwNamedGroupsExecuteMsg = getMsgExecuteLegacyFixture( + 'daodao/cw-named-groups', + '/execute_msg.json' +); const queryMsgData = getMsgQueryLegacyFixture('basic', '/query_msg.json'); -const executeMsgData = getMsgExecuteLegacyFixture('basic', '/execute_msg_for__empty.json'); -const approvalResponseData = getLegacyFixture('basic', '/approval_response.json'); -const allNftInfoResponseData = getLegacyFixture('basic', '/all_nft_info_response.json'); -const approvalsResponseData = getLegacyFixture('basic', '/approvals_response.json'); -const collectionInfoResponseData = getLegacyFixture('basic', '/collection_info_response.json'); -const contractInfoResponseData = getLegacyFixture('basic', '/contract_info_response.json'); +const executeMsgData = getMsgExecuteLegacyFixture( + 'basic', + '/execute_msg_for__empty.json' +); +const approvalResponseData = getLegacyFixture( + 'basic', + '/approval_response.json' +); +const allNftInfoResponseData = getLegacyFixture( + 'basic', + '/all_nft_info_response.json' +); +const approvalsResponseData = getLegacyFixture( + 'basic', + '/approvals_response.json' +); +const collectionInfoResponseData = getLegacyFixture( + 'basic', + '/collection_info_response.json' +); +const contractInfoResponseData = getLegacyFixture( + 'basic', + '/contract_info_response.json' +); const instantiateMsgData = getLegacyFixture('basic', '/instantiate_msg.json'); -const nftInfoResponseData = getLegacyFixture('basic', '/nft_info_response.json'); -const numTokensResponseData = getLegacyFixture('basic', '/num_tokens_response.json'); -const operatorsResponseData = getLegacyFixture('basic', '/operators_response.json'); -const ownerOfResponseData = getLegacyFixture('basic', '/owner_of_response.json'); +const nftInfoResponseData = getLegacyFixture( + 'basic', + '/nft_info_response.json' +); +const numTokensResponseData = getLegacyFixture( + 'basic', + '/num_tokens_response.json' +); +const operatorsResponseData = getLegacyFixture( + 'basic', + '/operators_response.json' +); +const ownerOfResponseData = getLegacyFixture( + 'basic', + '/owner_of_response.json' +); const tokensResponseData = getLegacyFixture('basic', '/tokens_response.json'); - it('approval_response', () => { const ctx = makeContext(approvalResponseData); - expectCode(createTypeInterface( - ctx, - approvalResponseData - )); + expectCode(createTypeInterface(ctx, approvalResponseData)); }); it('all_nft_info_response', () => { const ctx = makeContext(allNftInfoResponseData); - expectCode(createTypeInterface( - ctx, - allNftInfoResponseData - )); + expectCode(createTypeInterface(ctx, allNftInfoResponseData)); }); it('approvals_response', () => { const ctx = makeContext(approvalsResponseData); - expectCode(createTypeInterface( - ctx, - approvalsResponseData - )); + expectCode(createTypeInterface(ctx, approvalsResponseData)); }); it('collection_info_response', () => { const ctx = makeContext(collectionInfoResponseData); - expectCode(createTypeInterface( - ctx, - collectionInfoResponseData - )); + expectCode(createTypeInterface(ctx, collectionInfoResponseData)); }); it('contract_info_response', () => { const ctx = makeContext(contractInfoResponseData); - expectCode(createTypeInterface( - ctx, - contractInfoResponseData - )); + expectCode(createTypeInterface(ctx, contractInfoResponseData)); }); it('instantiate_msg', () => { const ctx = makeContext(instantiateMsgData); - expectCode(createTypeInterface( - ctx, - instantiateMsgData - )); + expectCode(createTypeInterface(ctx, instantiateMsgData)); }); it('nft_info_response', () => { const ctx = makeContext(nftInfoResponseData); - expectCode(createTypeInterface( - ctx, - nftInfoResponseData - )); + expectCode(createTypeInterface(ctx, nftInfoResponseData)); }); it('num_tokens_response', () => { const ctx = makeContext(numTokensResponseData); - expectCode(createTypeInterface( - ctx, - numTokensResponseData - )); + expectCode(createTypeInterface(ctx, numTokensResponseData)); }); it('operators_response', () => { const ctx = makeContext(operatorsResponseData); - expectCode(createTypeInterface( - ctx, - operatorsResponseData - )); + expectCode(createTypeInterface(ctx, operatorsResponseData)); }); it('owner_of_response', () => { const ctx = makeContext(ownerOfResponseData); - expectCode(createTypeInterface( - ctx, - ownerOfResponseData - )); + expectCode(createTypeInterface(ctx, ownerOfResponseData)); }); it('tokens_response', () => { const ctx = makeContext(tokensResponseData); - expectCode(createTypeInterface( - ctx, - tokensResponseData - )); + expectCode(createTypeInterface(ctx, tokensResponseData)); }); it('query classes', () => { const ctx = makeContext(queryMsgData); - expectCode(createQueryClass( - ctx, - 'SG721QueryClient', - 'SG721ReadOnlyInstance', - queryMsgData - )); + expectCode( + createQueryClass( + ctx, + 'SG721QueryClient', + 'SG721ReadOnlyInstance', + queryMsgData + ) + ); }); it('execute classes', () => { const ctx = makeContext(executeMsgData); - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - 'SG721QueryClient', - executeMsgData - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + 'SG721QueryClient', + executeMsgData + ) + ); }); it('execute classes no extends', () => { const ctx = makeContext(executeMsgData); - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - executeMsgData - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + null, + executeMsgData + ) + ); }); it('execute classes array types', () => { const ctx = makeContext(daodaoCwNamedGroupsExecuteMsg); - expectCode(createExecuteClass( - ctx, - 'SG721Client', - 'SG721Instance', - null, - daodaoCwNamedGroupsExecuteMsg - )); + expectCode( + createExecuteClass( + ctx, + 'SG721Client', + 'SG721Instance', + null, + daodaoCwNamedGroupsExecuteMsg + ) + ); }); it('execute interfaces no extends', () => { const ctx = makeContext(executeMsgData); - expectCode(createExecuteInterface( - ctx, - 'SG721Instance', - null, - executeMsgData - )); + expectCode( + createExecuteInterface(ctx, 'SG721Instance', null, executeMsgData) + ); }); it('query interfaces', () => { const ctx = makeContext(queryMsgData); - expectCode(createQueryInterface( - ctx, - 'SG721ReadOnlyInstance', - queryMsgData - )); + expectCode(createQueryInterface(ctx, 'SG721ReadOnlyInstance', queryMsgData)); }); diff --git a/packages/ast/__tests__/client/ts-client.vectis.test.ts b/packages/ast/__tests__/client/ts-client.vectis.test.ts index ba1e0ec9..619e2de2 100644 --- a/packages/ast/__tests__/client/ts-client.vectis.test.ts +++ b/packages/ast/__tests__/client/ts-client.vectis.test.ts @@ -4,19 +4,30 @@ import { createExecuteClass, createExecuteInterface, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { - expectCode, - getLegacyFixture, - makeContext, -} from '../../test-utils'; +import { expectCode, getLegacyFixture, makeContext } from '../../test-utils'; -const vectisCanExecuteRelayResponse = getLegacyFixture('vectis/govec', '/can_execute_relay_response.json'); -const vectisCosmosMsgForEmpty = getLegacyFixture('vectis/govec', '/cosmos_msg_for__empty.json'); -const vectisExecuteMsgForEmpty = getLegacyFixture('vectis/govec', '/execute_msg_for__empty.json'); -const vectisInfoResponse = getLegacyFixture('vectis/govec', '/info_response.json'); -const vectisRelayTransaction = getLegacyFixture('vectis/govec', '/relay_transaction.json'); +const vectisCanExecuteRelayResponse = getLegacyFixture( + 'vectis/govec', + '/can_execute_relay_response.json' +); +const vectisCosmosMsgForEmpty = getLegacyFixture( + 'vectis/govec', + '/cosmos_msg_for__empty.json' +); +const vectisExecuteMsgForEmpty = getLegacyFixture( + 'vectis/govec', + '/execute_msg_for__empty.json' +); +const vectisInfoResponse = getLegacyFixture( + 'vectis/govec', + '/info_response.json' +); +const vectisRelayTransaction = getLegacyFixture( + 'vectis/govec', + '/relay_transaction.json' +); it('cosmos_msg_for__empty', () => { const ctx = makeContext(vectisCosmosMsgForEmpty); diff --git a/packages/ast/__tests__/client/ts-client.wager.test.ts b/packages/ast/__tests__/client/ts-client.wager.test.ts index 767158bb..47430e99 100644 --- a/packages/ast/__tests__/client/ts-client.wager.test.ts +++ b/packages/ast/__tests__/client/ts-client.wager.test.ts @@ -1,45 +1,49 @@ import { createExecuteClass, createQueryClass, - createTypeInterface + createTypeInterface, } from '../../src'; -import { expectCode, globIdlBasedContracts, makeContext } from '../../test-utils'; +import { + expectCode, + globIdlBasedContracts, + makeContext, +} from '../../test-utils'; -const globbed = globIdlBasedContracts('wager').find(c => c.name === '/cw-wager.json')!; +const globbed = globIdlBasedContracts('wager').find( + (c) => c.name === '/cw-wager.json' +)!; const wagerJson = globbed.content; const queryCtx = makeContext(wagerJson.query); const executeCtx = makeContext(wagerJson.execute); it('query', () => { - expectCode(createTypeInterface( - queryCtx, - wagerJson.query - )); + expectCode(createTypeInterface(queryCtx, wagerJson.query)); }); it('execute', () => { - expectCode(createTypeInterface( - executeCtx, - wagerJson.execute - )); + expectCode(createTypeInterface(executeCtx, wagerJson.execute)); }); it('query classes', () => { - expectCode(createQueryClass( - queryCtx, - 'WagerQueryClient', - 'WagerReadOnlyInstance', - wagerJson.query - )); + expectCode( + createQueryClass( + queryCtx, + 'WagerQueryClient', + 'WagerReadOnlyInstance', + wagerJson.query + ) + ); }); it('execute classes', () => { - expectCode(createExecuteClass( - executeCtx, - 'WagerClient', - 'WagerInstance', - null, - wagerJson.execute - )); + expectCode( + createExecuteClass( + executeCtx, + 'WagerClient', + 'WagerInstance', + null, + wagerJson.execute + ) + ); }); diff --git a/packages/ast/__tests__/message-builder/message-builder.test.ts b/packages/ast/__tests__/message-builder/message-builder.test.ts index 31fddd16..501f7b33 100644 --- a/packages/ast/__tests__/message-builder/message-builder.test.ts +++ b/packages/ast/__tests__/message-builder/message-builder.test.ts @@ -1,19 +1,24 @@ +import { createMessageBuilderClass } from '../../src'; import { - createMessageBuilderClass, -} from '../../src'; -import { expectCode, getLegacyFixture, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; + expectCode, + getLegacyFixture, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; const queryMsg = getMsgQueryLegacyFixture('basic', '/query_msg.json'); -const execMsg = getMsgExecuteLegacyFixture('basic', '/execute_msg_for__empty.json'); +const execMsg = getMsgExecuteLegacyFixture( + 'basic', + '/execute_msg_for__empty.json' +); const ownership = getLegacyFixture('basic', '/ownership.json'); - it('execute class', () => { const ctx = makeContext(execMsg); expectCode(createMessageBuilderClass(ctx, 'SG721MessageBuilder', execMsg)); }); - it('query class', () => { const ctx = makeContext(queryMsg); expectCode(createMessageBuilderClass(ctx, 'SG721MessageBuilder', queryMsg)); diff --git a/packages/ast/__tests__/message-composer/message-composer.test.ts b/packages/ast/__tests__/message-composer/message-composer.test.ts index 021736d6..911954f2 100644 --- a/packages/ast/__tests__/message-composer/message-composer.test.ts +++ b/packages/ast/__tests__/message-composer/message-composer.test.ts @@ -2,12 +2,19 @@ import { createMessageComposerClass, createMessageComposerInterface, } from '../../src'; -import { expectCode, getLegacyFixture, getMsgExecuteLegacyFixture, makeContext } from '../../test-utils'; +import { + expectCode, + getLegacyFixture, + getMsgExecuteLegacyFixture, + makeContext, +} from '../../test-utils'; -const execMsg = getMsgExecuteLegacyFixture('basic', '/execute_msg_for__empty.json'); +const execMsg = getMsgExecuteLegacyFixture( + 'basic', + '/execute_msg_for__empty.json' +); const ownership = getLegacyFixture('basic', '/ownership.json'); - it('execute classes', () => { const ctx = makeContext(execMsg); expectCode( diff --git a/packages/ast/__tests__/provider/provider.test.ts b/packages/ast/__tests__/provider/provider.test.ts index 271b641c..d67ce713 100644 --- a/packages/ast/__tests__/provider/provider.test.ts +++ b/packages/ast/__tests__/provider/provider.test.ts @@ -1,36 +1,35 @@ import { createGettingProviders, createIContractsContext, - createProvider + createProvider, } from '../../src/provider/provider'; import { PROVIDER_TYPES } from '../../src/utils/constants'; import { expectCode } from '../../test-utils'; - // Use 'typeof PROVIDER_TYPES[keyof typeof PROVIDER_TYPES]' to extract the values of PROVIDER_TYPES. -type ProviderTypes = typeof PROVIDER_TYPES[keyof typeof PROVIDER_TYPES]; +type ProviderTypes = (typeof PROVIDER_TYPES)[keyof typeof PROVIDER_TYPES]; interface TestProviderInfo { classname: string; } // Use the values from PROVIDER_TYPES as the keys for TestProviderInfos type ProviderInfos = { - [key in ProviderTypes]: TestProviderInfo + [key in ProviderTypes]: TestProviderInfo; }; it('execute class', () => { const info: ProviderInfos = {} as ProviderInfos; info[PROVIDER_TYPES.SIGNING_CLIENT_TYPE] = { - classname: 'WhitelistClient' + classname: 'WhitelistClient', }; info[PROVIDER_TYPES.QUERY_CLIENT_TYPE] = { - classname: 'WhitelistQueryClient' + classname: 'WhitelistQueryClient', }; info[PROVIDER_TYPES.MESSAGE_COMPOSER_TYPE] = { - classname: 'WhitelistMessageComposer' + classname: 'WhitelistMessageComposer', }; // @ts-ignore @@ -41,11 +40,11 @@ it('execute class without message composer', () => { const info: ProviderInfos = {}; info[PROVIDER_TYPES.SIGNING_CLIENT_TYPE] = { - classname: 'WhitelistClient' + classname: 'WhitelistClient', }; info[PROVIDER_TYPES.QUERY_CLIENT_TYPE] = { - classname: 'WhitelistQueryClient' + classname: 'WhitelistQueryClient', }; // @ts-ignore @@ -55,19 +54,19 @@ it('execute class without message composer', () => { it('create IContractsContext', () => { const info: any = { Whitelist: {}, - Marketplace: {} + Marketplace: {}, }; info['Whitelist'][PROVIDER_TYPES.SIGNING_CLIENT_TYPE] = { - classname: 'WhitelistClient' + classname: 'WhitelistClient', }; info['Whitelist'][PROVIDER_TYPES.QUERY_CLIENT_TYPE] = { - classname: 'WhitelistQueryClient' + classname: 'WhitelistQueryClient', }; info['Marketplace'][PROVIDER_TYPES.SIGNING_CLIENT_TYPE] = { - classname: 'MarketplaceClient' + classname: 'MarketplaceClient', }; expectCode(createIContractsContext(info)); @@ -76,19 +75,19 @@ it('create IContractsContext', () => { it('create getProviders', () => { const info: any = { Whitelist: {}, - Marketplace: {} + Marketplace: {}, }; info['Whitelist'][PROVIDER_TYPES.SIGNING_CLIENT_TYPE] = { - classname: 'WhitelistClient' + classname: 'WhitelistClient', }; info['Whitelist'][PROVIDER_TYPES.QUERY_CLIENT_TYPE] = { - classname: 'WhitelistQueryClient' + classname: 'WhitelistQueryClient', }; info['Marketplace'][PROVIDER_TYPES.SIGNING_CLIENT_TYPE] = { - classname: 'MarketplaceClient' + classname: 'MarketplaceClient', }; expectCode(createGettingProviders(info)); diff --git a/packages/ast/__tests__/react-query/react-query.test.ts b/packages/ast/__tests__/react-query/react-query.test.ts index a4ea0ce0..050b0c69 100644 --- a/packages/ast/__tests__/react-query/react-query.test.ts +++ b/packages/ast/__tests__/react-query/react-query.test.ts @@ -4,68 +4,80 @@ import { createReactQueryHooks, createReactQueryMutationHooks, } from '../../src'; -import { expectCode, getLegacyFixture, getMsgExecuteLegacyFixture, getMsgQueryLegacyFixture, makeContext } from '../../test-utils'; +import { + expectCode, + getLegacyFixture, + getMsgExecuteLegacyFixture, + getMsgQueryLegacyFixture, + makeContext, +} from '../../test-utils'; const queryMsg = getMsgQueryLegacyFixture('basic', '/query_msg.json'); -const execMsg = getMsgExecuteLegacyFixture('basic', '/execute_msg_for__empty.json'); +const execMsg = getMsgExecuteLegacyFixture( + 'basic', + '/execute_msg_for__empty.json' +); const ownership = getLegacyFixture('basic', '/ownership.json'); - it('createReactQueryHooks', () => { - expectCode(t.program( - createReactQueryHooks( - { + expectCode( + t.program( + createReactQueryHooks({ context: makeContext(queryMsg, { reactQuery: { version: 'v3', - } + }, }), queryMsg: queryMsg, contractName: 'Sg721', - QueryClient: 'Sg721QueryClient' - } - ))); - expectCode(t.program( - createReactQueryHooks( - { + QueryClient: 'Sg721QueryClient', + }) + ) + ); + expectCode( + t.program( + createReactQueryHooks({ context: makeContext(queryMsg, { reactQuery: { version: 'v3', - optionalClient: true - } + optionalClient: true, + }, }), queryMsg: queryMsg, contractName: 'Sg721', - QueryClient: 'Sg721QueryClient' - } - ))); - expectCode(t.program( - createReactQueryHooks( - { + QueryClient: 'Sg721QueryClient', + }) + ) + ); + expectCode( + t.program( + createReactQueryHooks({ context: makeContext(queryMsg, { reactQuery: { - version: 'v4' - } + version: 'v4', + }, }), queryMsg: queryMsg, contractName: 'Sg721', - QueryClient: 'Sg721QueryClient' - } - ))); - expectCode(t.program( - createReactQueryHooks( - { + QueryClient: 'Sg721QueryClient', + }) + ) + ); + expectCode( + t.program( + createReactQueryHooks({ context: makeContext(queryMsg, { reactQuery: { optionalClient: true, - version: 'v4' - } + version: 'v4', + }, }), queryMsg: queryMsg, contractName: 'Sg721', - QueryClient: 'Sg721QueryClient' - } - ))); + QueryClient: 'Sg721QueryClient', + }) + ) + ); expectCode( t.program( createReactQueryHooks({ @@ -74,45 +86,45 @@ it('createReactQueryHooks', () => { optionalClient: true, version: 'v4', queryKeys: true, - queryFactory: true - } + queryFactory: true, + }, }), queryMsg: queryMsg, contractName: 'Sg721', - QueryClient: 'Sg721QueryClient' + QueryClient: 'Sg721QueryClient', }) ) ); - expectCode(t.program( - createReactQueryMutationHooks( - { + expectCode( + t.program( + createReactQueryMutationHooks({ context: makeContext(execMsg, { reactQuery: { - version: 'v3' - } + version: 'v3', + }, }), execMsg: execMsg, contractName: 'Sg721', ExecuteClient: 'Sg721Client', - } - ))); + }) + ) + ); }); it('ownership', () => { - expectCode(t.program( - createReactQueryMutationHooks( - { + expectCode( + t.program( + createReactQueryMutationHooks({ context: makeContext(ownership, { reactQuery: { - version: 'v3' - } + version: 'v3', + }, }), // @ts-ignore execMsg: ownership, contractName: 'Ownership', ExecuteClient: 'OwnershipClient', - } - ))); + }) + ) + ); }); - - diff --git a/packages/ast/__tests__/recoil/recoil.test.ts b/packages/ast/__tests__/recoil/recoil.test.ts index 779ae3d3..3bde3683 100644 --- a/packages/ast/__tests__/recoil/recoil.test.ts +++ b/packages/ast/__tests__/recoil/recoil.test.ts @@ -4,11 +4,13 @@ import { QueryMsg } from '@cosmwasm/ts-codegen-types'; import { createRecoilQueryClient, createRecoilSelector, - createRecoilSelectors + createRecoilSelectors, } from '../../src/recoil/recoil'; import { expectCode, globLegacyContracts, makeContext } from '../../test-utils'; -const globbed = globLegacyContracts('basic').find(c => c.name === '/query_msg.json'); +const globbed = globLegacyContracts('basic').find( + (c) => c.name === '/query_msg.json' +); const queryMsg = globbed.content as QueryMsg; const ctx = makeContext(queryMsg); @@ -26,9 +28,7 @@ it('selector', () => { it('selectors', () => { expectCode( - t.program( - createRecoilSelectors(ctx, 'SG721', 'SG721QueryClient', queryMsg) - ) + t.program(createRecoilSelectors(ctx, 'SG721', 'SG721QueryClient', queryMsg)) ); }); diff --git a/packages/ast/__tests__/types/interfaces.test.ts b/packages/ast/__tests__/types/interfaces.test.ts index 9328086d..bca86298 100644 --- a/packages/ast/__tests__/types/interfaces.test.ts +++ b/packages/ast/__tests__/types/interfaces.test.ts @@ -1,31 +1,23 @@ - import { createTypeOrInterface } from '../../src'; import { expectCode, getLegacyFixture, makeContext } from '../../test-utils'; const topLevel = getLegacyFixture('misc/schema', '/arrays-top-level.json'); const nested = getLegacyFixture('misc/schema', '/arrays-nested.json'); - it('top level', async () => { - expectCode( - createTypeOrInterface(makeContext(topLevel), 'Type', topLevel) - ); + expectCode(createTypeOrInterface(makeContext(topLevel), 'Type', topLevel)); }); it('nested', async () => { const ctx = makeContext(nested); - expectCode( - createTypeOrInterface(ctx, 'Type', nested) - ); + expectCode(createTypeOrInterface(ctx, 'Type', nested)); }); it('nested ctx', async () => { const ctx = makeContext(nested, { types: { - itemsUseTuples: true - } + itemsUseTuples: true, + }, }); - expectCode( - createTypeOrInterface(ctx, 'Type', nested) - ); + expectCode(createTypeOrInterface(ctx, 'Type', nested)); }); diff --git a/packages/ast/package.json b/packages/ast/package.json index 28d074dc..a93ef7d7 100644 --- a/packages/ast/package.json +++ b/packages/ast/package.json @@ -19,6 +19,7 @@ "codegen": "ts-node ./scripts/build.ts", "build": "npm run clean; tsc; tsc -p tsconfig.esm.json; npm run copy", "lint": "eslint . --fix", + "format": "prettier --write --log-level warn \"./**/*.ts\"", "test": "jest", "test:watch": "jest --watch", "test:ast": "ts-node scripts/test-ast.ts", diff --git a/packages/ast/scripts/test-ast.ts b/packages/ast/scripts/test-ast.ts index 52fab414..837250b6 100644 --- a/packages/ast/scripts/test-ast.ts +++ b/packages/ast/scripts/test-ast.ts @@ -10,13 +10,13 @@ const main = async () => { 'asyncGenerators', 'decorators-legacy', 'typescript', - 'dynamicImport' + 'dynamicImport', ]; const ast = parse(readFileSync(__dirname + '/fixture.ts', 'utf-8'), { sourceType: 'module', // @ts-ignore - plugins + plugins, }); writeFileSync(__dirname + '/test-output.json', stringify(ast, null, 2)); diff --git a/packages/ast/src/client/client.ts b/packages/ast/src/client/client.ts index a659ded9..59dad222 100644 --- a/packages/ast/src/client/client.ts +++ b/packages/ast/src/client/client.ts @@ -13,15 +13,15 @@ import { getTypeOrRef, OPTIONAL_FUNDS_PARAM, promiseTypeAnnotation, - typedIdentifier + typedIdentifier, } from '../utils'; import { identifier, propertySignature } from '../utils/babel'; +import { OPTIONAL_MEMO_PARAM } from '../utils/constants'; import { createTypedObjectParams, getPropertyType, - getResponseType + getResponseType, } from '../utils/types'; -import { OPTIONAL_MEMO_PARAM } from "../utils/constants"; export const CONSTANT_EXEC_PARAMS = [ t.assignmentPattern( @@ -31,7 +31,7 @@ export const CONSTANT_EXEC_PARAMS = [ t.tsUnionType([ t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), - t.tsLiteralType(t.stringLiteral('auto')) + t.tsLiteralType(t.stringLiteral('auto')), ]) ), false @@ -39,7 +39,7 @@ export const CONSTANT_EXEC_PARAMS = [ t.stringLiteral('auto') ), OPTIONAL_MEMO_PARAM, - OPTIONAL_FUNDS_PARAM + OPTIONAL_FUNDS_PARAM, ]; export const createWasmQueryMethod = ( @@ -83,16 +83,16 @@ export const createWasmQueryMethod = ( t.thisExpression(), t.identifier('contractAddress') ), - t.objectExpression([t.objectProperty(msgAction, msgActionValue)]) + t.objectExpression([t.objectProperty(msgAction, msgActionValue)]), ] ) - ) + ), ]), t.tsTypeAnnotation( t.tsTypeReference( t.identifier('Promise'), t.tsTypeParameterInstantiation([ - t.tSTypeReference(t.identifier(responseType)) + t.tSTypeReference(t.identifier(responseType)), ]) ) ), @@ -149,7 +149,7 @@ export const createQueryClass = ( typedIdentifier( 'contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], t.blockStatement([ // client/contract set @@ -171,11 +171,11 @@ export const createQueryClass = ( ) ), - ...bindings + ...bindings, ]) ), - ...methods + ...methods, ], [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))] ) @@ -245,10 +245,10 @@ export const createWasmExecMethod = ( arrowFunctionExpression( param ? [ - // props - param, - ...CONSTANT_EXEC_PARAMS - ] + // props + param, + ...CONSTANT_EXEC_PARAMS, + ] : CONSTANT_EXEC_PARAMS, t.blockStatement([ t.returnStatement( @@ -265,22 +265,22 @@ export const createWasmExecMethod = ( t.identifier('contractAddress') ), t.objectExpression([ - t.objectProperty(msgAction, msgActionValue) + t.objectProperty(msgAction, msgActionValue), ]), t.identifier('fee_'), t.identifier('memo_'), - t.identifier('funds_') + t.identifier('funds_'), ] ) ) - ) + ), ]), // return type t.tsTypeAnnotation( t.tsTypeReference( t.identifier('Promise'), t.tsTypeParameterInstantiation([ - t.tSTypeReference(t.identifier('ExecuteResult')) + t.tSTypeReference(t.identifier('ExecuteResult')), ]) ) ), @@ -316,37 +316,42 @@ export const createExecuteClass = ( t.expressionStatement( t.callExpression(t.super(), [ t.identifier('client'), - t.identifier('contractAddress') + t.identifier('contractAddress'), ]) ) ); } - blockStmt.push(...[ - // client/contract set - t.expressionStatement( - t.assignmentExpression( - '=', - t.memberExpression(t.thisExpression(), t.identifier('client')), - t.identifier('client') - ) - ), - t.expressionStatement( - t.assignmentExpression( - '=', - t.memberExpression(t.thisExpression(), t.identifier('sender')), - t.identifier('sender') - ) - ), - t.expressionStatement( - t.assignmentExpression( - '=', - t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), - t.identifier('contractAddress') - ) - ), - ...bindings - ]); + blockStmt.push( + ...[ + // client/contract set + t.expressionStatement( + t.assignmentExpression( + '=', + t.memberExpression(t.thisExpression(), t.identifier('client')), + t.identifier('client') + ) + ), + t.expressionStatement( + t.assignmentExpression( + '=', + t.memberExpression(t.thisExpression(), t.identifier('sender')), + t.identifier('sender') + ) + ), + t.expressionStatement( + t.assignmentExpression( + '=', + t.memberExpression( + t.thisExpression(), + t.identifier('contractAddress') + ), + t.identifier('contractAddress') + ) + ), + ...bindings, + ] + ); const noImplicitOverride = context.options.client.noImplicitOverride && @@ -402,11 +407,11 @@ export const createExecuteClass = ( typedIdentifier( 'contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], t.blockStatement(blockStmt) ), - ...methods + ...methods, ], [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))], extendsClassName ? t.identifier(extendsClassName) : null @@ -453,7 +458,7 @@ export const createExecuteInterface = ( t.tsTypeAnnotation(t.tsStringKeyword()) ), - ...methods + ...methods, ]) ) ); @@ -470,7 +475,7 @@ export const createPropertyFunctionWithObjectParams = ( const func = { type: 'TSFunctionType', typeAnnotation: promiseTypeAnnotation(responseType), - parameters: obj ? [obj] : [] + parameters: obj ? [obj] : [], }; return t.tSPropertySignature( @@ -495,7 +500,7 @@ export const createPropertyFunctionWithObjectParamsForExec = ( const func = { type: 'TSFunctionType', typeAnnotation: promiseTypeAnnotation(responseType), - parameters: obj ? [obj, ...FIXED_EXECUTE_PARAMS] : FIXED_EXECUTE_PARAMS + parameters: obj ? [obj, ...FIXED_EXECUTE_PARAMS] : FIXED_EXECUTE_PARAMS, }; return t.tSPropertySignature( @@ -534,7 +539,7 @@ export const createQueryInterface = ( t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword()) ), - ...methods + ...methods, ]) ) ); @@ -564,11 +569,7 @@ export const createTypeOrInterface = ( // Use getTypeOrRef to handle string, array of strings, or $ref const typeAnnotation = getTypeOrRef(jsonschema); return t.exportNamedDeclaration( - t.tsTypeAliasDeclaration( - t.identifier(Type), - null, - typeAnnotation - ) + t.tsTypeAliasDeclaration(t.identifier(Type), null, typeAnnotation) ); } // Handle object type schemas @@ -582,9 +583,7 @@ export const createTypeOrInterface = ( t.identifier(Type), null, [], - t.tsInterfaceBody( - [...props] - ) + t.tsInterfaceBody([...props]) ) ); }; diff --git a/packages/ast/src/client/index.ts b/packages/ast/src/client/index.ts index 5c6a6381..4f1cce44 100644 --- a/packages/ast/src/client/index.ts +++ b/packages/ast/src/client/index.ts @@ -1 +1 @@ -export * from './client'; \ No newline at end of file +export * from './client'; diff --git a/packages/ast/src/context/context.ts b/packages/ast/src/context/context.ts index 7f927f7c..dce5496f 100644 --- a/packages/ast/src/context/context.ts +++ b/packages/ast/src/context/context.ts @@ -5,19 +5,35 @@ import { basename, extname } from 'path'; import { ContractInfo, ProviderInfo, RenderOptions } from '../types'; import { refLookup } from '../utils'; -import { convertUtilsToImportList, getImportStatements, UtilMapping } from './imports'; +import { + convertUtilsToImportList, + getImportStatements, + UtilMapping, +} from './imports'; export interface IContext { refLookup($ref: string): JSONSchema; addUtil(util: string): void; - getImports(registeredUtils?: UtilMapping, filepath?: string): (t.ImportNamespaceSpecifier | t.ImportDeclaration | t.ImportDefaultSpecifier)[]; + getImports( + registeredUtils?: UtilMapping, + filepath?: string + ): ( + | t.ImportNamespaceSpecifier + | t.ImportDeclaration + | t.ImportDefaultSpecifier + )[]; } export interface IRenderContext extends IContext { contract: ContractInfo; options: TOpt; - addProviderInfo(contractName: string, type: string, classname: string, filename: string): void; + addProviderInfo( + contractName: string, + type: string, + classname: string, + filename: string + ): void; getProviderInfos(): { [key: string]: { [key: string]: ProviderInfo; @@ -30,7 +46,7 @@ export const defaultOptions: RenderOptions = { types: { enabled: true, itemsUseTuples: false, - aliasExecuteMsg: false + aliasExecuteMsg: false, }, client: { enabled: true, @@ -39,10 +55,10 @@ export const defaultOptions: RenderOptions = { useDeclareKeyword: false, }, recoil: { - enabled: false + enabled: false, }, messageComposer: { - enabled: false + enabled: false, }, messageBuilder: { enabled: false, @@ -53,25 +69,25 @@ export const defaultOptions: RenderOptions = { version: 'v4', mutations: false, camelize: true, - queryKeys: false + queryKeys: false, }, useContractsHook: { - enabled: false - } + enabled: false, + }, }; export const getDefinitionSchema = (schemas: JSONSchema[]): JSONSchema => { const aggregateSchema = { definitions: { // - } + }, }; - schemas.forEach(schema => { + schemas.forEach((schema) => { schema.definitions = schema.definitions || {}; aggregateSchema.definitions = { ...aggregateSchema.definitions, - ...schema.definitions + ...schema.definitions, }; }); @@ -85,7 +101,12 @@ export class BuilderContext { }; } = {}; - addProviderInfo(contractName: string, type: string, classname: string, filename: string): void { + addProviderInfo( + contractName: string, + type: string, + classname: string, + filename: string + ): void { if (!this.providers[contractName]) { this.providers[contractName] = {}; } @@ -93,14 +114,14 @@ export class BuilderContext { this.providers[contractName][type] = { classname, filename, - basename: basename(filename, extname(filename)) + basename: basename(filename, extname(filename)), }; } getProviderInfos(): { [key: string]: { [key: string]: ProviderInfo; }; - } { + } { return this.providers; } } @@ -110,7 +131,9 @@ export class BuilderContext { * only mergeDefaultOpt needs to implementing for combine options and default options. * @param TOpt option type */ -export abstract class RenderContextBase implements IRenderContext { +export abstract class RenderContextBase + implements IRenderContext +{ builderContext: BuilderContext; contract: ContractInfo; utils: Record = {}; @@ -138,23 +161,36 @@ export abstract class RenderContextBase implements IRender addUtil(util: string): void { this.utils[util] = true; } - addProviderInfo(contractName: string, type: string, classname: string, filename: string): void { - this.builderContext.addProviderInfo(contractName, type, classname, filename); + addProviderInfo( + contractName: string, + type: string, + classname: string, + filename: string + ): void { + this.builderContext.addProviderInfo( + contractName, + type, + classname, + filename + ); } getProviderInfos(): { [key: string]: { [key: string]: ProviderInfo; }; - } { + } { return this.builderContext.providers; } - getImports(registeredUtils?: UtilMapping, filepath?: string): (t.ImportNamespaceSpecifier | t.ImportDeclaration | t.ImportDefaultSpecifier)[] { + getImports( + registeredUtils?: UtilMapping, + filepath?: string + ): ( + | t.ImportNamespaceSpecifier + | t.ImportDeclaration + | t.ImportDefaultSpecifier + )[] { return getImportStatements( - convertUtilsToImportList( - this, - Object.keys(this.utils), - registeredUtils, - ), + convertUtilsToImportList(this, Object.keys(this.utils), registeredUtils), filepath ); } diff --git a/packages/ast/src/context/imports.ts b/packages/ast/src/context/imports.ts index 4edd6580..3459c391 100644 --- a/packages/ast/src/context/imports.ts +++ b/packages/ast/src/context/imports.ts @@ -1,10 +1,9 @@ import * as t from '@babel/types'; -import { dirname, extname,relative } from 'path'; +import { dirname, extname, relative } from 'path'; import { importAs, importStmt } from '../utils'; import { RenderContext } from './context'; - export interface ImportObj { type: 'import' | 'default' | 'namespace'; name: string; @@ -12,30 +11,29 @@ export interface ImportObj { importAs?: string; } -export type GetUtilFn = ((...args: any[]) => (context: TContext) => ImportObj); +export type GetUtilFn = ( + ...args: any[] +) => (context: TContext) => ImportObj; export type UtilMapping = { - [key: string]: - | ImportObj - | string - | GetUtilFn + [key: string]: ImportObj | string | GetUtilFn; }; const makeReactQuerySwitch = (varName: string) => { return (context: RenderContext) => { switch (context.options.reactQuery.version) { - case 'v4': - return { - type: 'import', - path: '@tanstack/react-query', - name: varName - }; - case 'v3': - default: - return { - type: 'import', - path: 'react-query', - name: varName - }; + case 'v4': + return { + type: 'import', + path: '@tanstack/react-query', + name: varName, + }; + case 'v3': + default: + return { + type: 'import', + path: 'react-query', + name: varName, + }; } }; }; @@ -55,13 +53,10 @@ export const UTILS = { useQuery: makeReactQuerySwitch('useQuery'), UseQueryOptions: makeReactQuerySwitch('UseQueryOptions'), useMutation: makeReactQuerySwitch('useMutation'), - UseMutationOptions: makeReactQuerySwitch('UseMutationOptions') - + UseMutationOptions: makeReactQuerySwitch('UseMutationOptions'), }; -export const UTIL_HELPERS = [ - '__contractContextBase__', -]; +export const UTIL_HELPERS = ['__contractContextBase__']; export const convertUtilsToImportList = ( context: RenderContext, @@ -94,12 +89,12 @@ export const convertUtil = ( util: string, registeredUtils: any ): ImportObj => { - if (!registeredUtils.hasOwnProperty(util)) return null; + if (!Object.prototype.hasOwnProperty.call(registeredUtils, util)) return null; if (typeof registeredUtils[util] === 'string') { return { type: 'import', path: registeredUtils[util], - name: util + name: util, }; } else if (typeof registeredUtils[util] === 'function') { return registeredUtils[util](context); @@ -108,84 +103,95 @@ export const convertUtil = ( } }; - // __helpers__ export const getImportStatements = ( list: ImportObj[], filepath?: string -): (t.ImportNamespaceSpecifier | t.ImportDeclaration | t.ImportDefaultSpecifier)[] => { - +): ( + | t.ImportNamespaceSpecifier + | t.ImportDeclaration + | t.ImportDefaultSpecifier +)[] => { // swap helpers with helpers file... - const modifiedImports = list.map(imp => { + const modifiedImports = list.map((imp) => { if (filepath && UTIL_HELPERS.includes(imp.path)) { const name = imp.path.replace(/__/g, ''); return { ...imp, - path: getRelativePath(filepath, `./${name}`) + path: getRelativePath(filepath, `./${name}`), }; } return imp; }); - const imports = modifiedImports.reduce((m: Record, obj) => { - m[obj.path] = m[obj.path] || []; - const exists = m[obj.path].find((el: ImportObj) => - el.type === obj.type && el.path === obj.path && el.name === obj.name); - - // MARKED AS NOT DRY [google.protobuf names] - // TODO some have google.protobuf.Any shows up... figure out the better way to handle this - if (/\./.test(obj.name)) { - obj.name = obj.name.split('.')[obj.name.split('.').length - 1]; - } - - if (!exists) { - m[obj.path].push(obj); - } - return m; - }, {}); + const imports = modifiedImports.reduce( + (m: Record, obj) => { + m[obj.path] = m[obj.path] || []; + const exists = m[obj.path].find( + (el: ImportObj) => + el.type === obj.type && el.path === obj.path && el.name === obj.name + ); + + // MARKED AS NOT DRY [google.protobuf names] + // TODO some have google.protobuf.Any shows up... figure out the better way to handle this + if (/\./.test(obj.name)) { + obj.name = obj.name.split('.')[obj.name.split('.').length - 1]; + } + if (!exists) { + m[obj.path].push(obj); + } + return m; + }, + {} + ); - return Object.entries(imports) - .reduce((m, [importPath, imports]: [string, ImportObj[]]) => { - const defaultImports = imports.filter(a => a.type === 'default'); + return Object.entries(imports).reduce( + (m, [importPath, imports]: [string, ImportObj[]]) => { + const defaultImports = imports.filter((a) => a.type === 'default'); if (defaultImports.length) { - if (defaultImports.length > 1) throw new Error('more than one default name NOT allowed.'); + if (defaultImports.length > 1) + throw new Error('more than one default name NOT allowed.'); m.push( t.importDeclaration( - [ - t.importDefaultSpecifier( - t.identifier(defaultImports[0].name) - ) - ], + [t.importDefaultSpecifier(t.identifier(defaultImports[0].name))], t.stringLiteral(defaultImports[0].path) ) ); } - const namedImports = imports.filter(a => a.type === 'import' && (!a.importAs || (a.name === a.importAs))); + const namedImports = imports.filter( + (a) => a.type === 'import' && (!a.importAs || a.name === a.importAs) + ); if (namedImports.length) { - m.push(importStmt(namedImports.map(i => i.name), namedImports[0].path)); + m.push( + importStmt( + namedImports.map((i) => i.name), + namedImports[0].path + ) + ); } - const aliasNamedImports = imports.filter(a => a.type === 'import' && (a.importAs && (a.name !== a.importAs))); - aliasNamedImports.forEach(imp => { + const aliasNamedImports = imports.filter( + (a) => a.type === 'import' && a.importAs && a.name !== a.importAs + ); + aliasNamedImports.forEach((imp) => { m.push(importAs(imp.name, imp.importAs, imp.path)); }); - const namespaced = imports.filter(a => a.type === 'namespace'); + const namespaced = imports.filter((a) => a.type === 'namespace'); if (namespaced.length) { - if (namespaced.length > 1) throw new Error('more than one namespaced name NOT allowed.'); + if (namespaced.length > 1) + throw new Error('more than one namespaced name NOT allowed.'); m.push( t.importDeclaration( - [ - t.importNamespaceSpecifier( - t.identifier(namespaced[0].name) - ) - ], + [t.importNamespaceSpecifier(t.identifier(namespaced[0].name))], t.stringLiteral(namespaced[0].path) ) ); } return m; - }, []); + }, + [] + ); }; export const getRelativePath = (f1: string, f2: string) => { @@ -193,4 +199,4 @@ export const getRelativePath = (f1: string, f2: string) => { let importPath = rel.replace(extname(rel), ''); if (!/^\./.test(importPath)) importPath = `./${importPath}`; return importPath; -}; \ No newline at end of file +}; diff --git a/packages/ast/src/context/index.ts b/packages/ast/src/context/index.ts index 49ca3de6..6a003172 100644 --- a/packages/ast/src/context/index.ts +++ b/packages/ast/src/context/index.ts @@ -1,2 +1,2 @@ export * from './context'; -export * from './imports'; \ No newline at end of file +export * from './imports'; diff --git a/packages/ast/src/message-builder/message-builder.ts b/packages/ast/src/message-builder/message-builder.ts index 152e85be..2fbd3f19 100644 --- a/packages/ast/src/message-builder/message-builder.ts +++ b/packages/ast/src/message-builder/message-builder.ts @@ -5,7 +5,11 @@ import { camel } from 'case'; import { getWasmMethodArgs } from '../client/client'; import { RenderContext } from '../context'; -import { abstractClassDeclaration, arrowFunctionExpression, getMessageProperties } from '../utils'; +import { + abstractClassDeclaration, + arrowFunctionExpression, + getMessageProperties, +} from '../utils'; import { createTypedObjectParams } from '../utils/types'; export const createMessageBuilderClass = ( @@ -33,19 +37,20 @@ function createExtractTypeAnnotation(underscoreName: string, msgTitle: string) { t.identifier('CamelCasedProperties'), t.tsTypeParameterInstantiation([ t.tsIndexedAccessType( - t.tsTypeReference(t.identifier('Extract'), + t.tsTypeReference( + t.identifier('Extract'), t.tsTypeParameterInstantiation([ t.tsTypeReference(t.identifier(msgTitle)), t.tsTypeLiteral([ t.tsPropertySignature( t.identifier(underscoreName), t.tsTypeAnnotation(t.tsUnknownKeyword()) - ) - ]) + ), + ]), ]) ), t.tsLiteralType(t.stringLiteral(underscoreName)) - ) + ), ]) ) ); @@ -72,10 +77,12 @@ const createStaticExecMethodMessageBuilder = ( if (param?.type === 'Identifier') { actionValue = t.identifier(param.name); } else { - actionValue = t.tsAsExpression(t.objectExpression(args), t.tsTypeReference(t.identifier('const'))); + actionValue = t.tsAsExpression( + t.objectExpression(args), + t.tsTypeReference(t.identifier('const')) + ); } - // TODO: this is a hack to get the type annotation to work // all type annotations in the future should be the extracted and camelized type if ( @@ -83,7 +90,10 @@ const createStaticExecMethodMessageBuilder = ( param.typeAnnotation.type === 'TSTypeAnnotation' && param.typeAnnotation.typeAnnotation.type === 'TSTypeLiteral' ) { - param.typeAnnotation = createExtractTypeAnnotation(underscoreName, msgTitle); + param.typeAnnotation = createExtractTypeAnnotation( + underscoreName, + msgTitle + ); } return t.classProperty( @@ -92,20 +102,17 @@ const createStaticExecMethodMessageBuilder = ( // params param ? [ - // props - param - ] + // props + param, + ] : [], // body t.blockStatement([ t.returnStatement( t.objectExpression([ - t.objectProperty( - t.identifier(underscoreName), - actionValue - ) + t.objectProperty(t.identifier(underscoreName), actionValue), ]) - ) + ), ]), // return type t.tsTypeAnnotation(t.tsTypeReference(t.identifier(msgTitle))), diff --git a/packages/ast/src/message-composer/index.ts b/packages/ast/src/message-composer/index.ts index d3c9f7e9..cd64f6f4 100644 --- a/packages/ast/src/message-composer/index.ts +++ b/packages/ast/src/message-composer/index.ts @@ -1 +1 @@ -export * from './message-composer'; \ No newline at end of file +export * from './message-composer'; diff --git a/packages/ast/src/message-composer/message-composer.ts b/packages/ast/src/message-composer/message-composer.ts index 21b750f6..6e63fe95 100644 --- a/packages/ast/src/message-composer/message-composer.ts +++ b/packages/ast/src/message-composer/message-composer.ts @@ -12,7 +12,7 @@ import { classProperty, getMessageProperties, OPTIONAL_FUNDS_PARAM, - typedIdentifier + typedIdentifier, } from '../utils'; import { createTypedObjectParams } from '../utils/types'; @@ -51,10 +51,10 @@ const createWasmExecMethodMessageComposer = ( arrowFunctionExpression( param ? [ - // props - param, - ...constantParams - ] + // props + param, + ...constantParams, + ] : constantParams, t.blockStatement([ t.returnStatement( @@ -99,22 +99,22 @@ const createWasmExecMethodMessageComposer = ( t.objectProperty( t.identifier(underscoreName), actionValue - ) - ]) + ), + ]), ] - ) + ), ]) ), t.objectProperty( t.identifier('funds'), t.identifier('funds_') - ) - ]) + ), + ]), ] ) - ) + ), ]) - ) + ), ]), // return type t.tsTypeAnnotation( @@ -143,23 +143,28 @@ export const createMessageComposerClass = ( const blockStmt = []; - blockStmt.push(...[ - t.expressionStatement( - t.assignmentExpression( - '=', - t.memberExpression(t.thisExpression(), t.identifier('sender')), - t.identifier('sender') - ) - ), - t.expressionStatement( - t.assignmentExpression( - '=', - t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), - t.identifier('contractAddress') - ) - ), - ...bindings - ]); + blockStmt.push( + ...[ + t.expressionStatement( + t.assignmentExpression( + '=', + t.memberExpression(t.thisExpression(), t.identifier('sender')), + t.identifier('sender') + ) + ), + t.expressionStatement( + t.assignmentExpression( + '=', + t.memberExpression( + t.thisExpression(), + t.identifier('contractAddress') + ), + t.identifier('contractAddress') + ) + ), + ...bindings, + ] + ); return t.exportNamedDeclaration( classDeclaration( @@ -183,11 +188,11 @@ export const createMessageComposerClass = ( typedIdentifier( 'contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()) - ) + ), ], t.blockStatement(blockStmt) ), - ...methods + ...methods, ], [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))], null @@ -231,7 +236,7 @@ export const createMessageComposerInterface = ( t.tsTypeAnnotation(t.tsStringKeyword()) ), - ...methods + ...methods, ]) ) ); @@ -250,7 +255,7 @@ const createPropertyFunctionWithObjectParamsForMessageComposer = ( typeAnnotation: t.tsTypeAnnotation( t.tsTypeReference(t.identifier(responseType)) ), - parameters: obj ? [obj, ...fixedParams] : fixedParams + parameters: obj ? [obj, ...fixedParams] : fixedParams, }; return t.tSPropertySignature( diff --git a/packages/ast/src/provider/index.ts b/packages/ast/src/provider/index.ts index 0a8c7e17..03be03e5 100644 --- a/packages/ast/src/provider/index.ts +++ b/packages/ast/src/provider/index.ts @@ -1 +1 @@ -export * from './provider'; \ No newline at end of file +export * from './provider'; diff --git a/packages/ast/src/provider/provider.ts b/packages/ast/src/provider/provider.ts index 13d03bac..91c51b71 100644 --- a/packages/ast/src/provider/provider.ts +++ b/packages/ast/src/provider/provider.ts @@ -64,7 +64,7 @@ export const createProvider = ( t.identifier( providerInfos[PROVIDER_TYPES.MESSAGE_COMPOSER_TYPE] ? providerInfos[PROVIDER_TYPES.MESSAGE_COMPOSER_TYPE] - .classname + .classname : 'undefined' ), ]) @@ -223,11 +223,15 @@ export const createGettingProviders = (providerInfos: { ), identifier( 'cosmWasmClient?', - t.tsTypeAnnotation(t.tsTypeReference(t.identifier('CosmWasmClient'))) + t.tsTypeAnnotation( + t.tsTypeReference(t.identifier('CosmWasmClient')) + ) ), identifier( 'signingCosmWasmClient?', - t.tsTypeAnnotation(t.tsTypeReference(t.identifier('SigningCosmWasmClient'))) + t.tsTypeAnnotation( + t.tsTypeReference(t.identifier('SigningCosmWasmClient')) + ) ), ], t.objectExpression(properties) diff --git a/packages/ast/src/react-query/index.ts b/packages/ast/src/react-query/index.ts index 0dd2cb57..82818ecb 100644 --- a/packages/ast/src/react-query/index.ts +++ b/packages/ast/src/react-query/index.ts @@ -1 +1 @@ -export * from './react-query'; \ No newline at end of file +export * from './react-query'; diff --git a/packages/ast/src/react-query/react-query.ts b/packages/ast/src/react-query/react-query.ts index f8cdc540..cd6588a5 100644 --- a/packages/ast/src/react-query/react-query.ts +++ b/packages/ast/src/react-query/react-query.ts @@ -13,19 +13,16 @@ import { identifier, OPTIONAL_FUNDS_PARAM, tsObjectPattern, - tsPropertySignature + tsPropertySignature, } from '../utils'; import { omitTypeReference, optionalConditionalExpression, propertySignature, - shorthandProperty + shorthandProperty, } from '../utils/babel'; import { OPTIONAL_FEE_PARAM, OPTIONAL_MEMO_PARAM } from '../utils/constants'; -import { - getPropertyType, - getResponseType -} from '../utils/types'; +import { getPropertyType, getResponseType } from '../utils/types'; interface ReactQueryHookQuery { context: RenderContext; @@ -60,7 +57,7 @@ export const createReactQueryHooks = ({ context, queryMsg, contractName, - QueryClient + QueryClient, }: ReactQueryHooks) => { const options = context.options.reactQuery; @@ -78,7 +75,7 @@ export const createReactQueryHooks = ({ context, queryKeysName, camelContractName: camel(contractName), - underscoreNames + underscoreNames, }) ); } @@ -108,7 +105,7 @@ export const createReactQueryHooks = ({ hookName, responseType, getterKey, - jsonschema + jsonschema, }; } ); @@ -120,7 +117,7 @@ export const createReactQueryHooks = ({ context, queryFactoryName, queryKeysName, - queryMsgs + queryMsgs, }) ); } @@ -129,7 +126,7 @@ export const createReactQueryHooks = ({ createReactQueryHookGenericInterface({ context, QueryClient, - genericQueryInterfaceName + genericQueryInterfaceName, }) ); @@ -143,7 +140,7 @@ export const createReactQueryHooks = ({ hookName, responseType, getterKey, - jsonschema + jsonschema, } ) => { return [ @@ -153,7 +150,7 @@ export const createReactQueryHooks = ({ responseType, queryInterfaceName: genericQueryInterfaceName, QueryClient, - jsonschema + jsonschema, }), createReactQueryHook({ context, @@ -163,9 +160,9 @@ export const createReactQueryHooks = ({ queryKeysName, responseType, hookKeyName: getterKey, - jsonschema + jsonschema, }), - ...m + ...m, ]; }, [] @@ -190,8 +187,8 @@ function buildQueryFn( t.identifier(camel(prop)), t.memberExpression(t.identifier('args'), t.identifier(camel(prop))) ); - }) - ]) + }), + ]), ]; } @@ -199,8 +196,8 @@ function buildQueryFn( t.memberExpression(t.identifier('Promise'), t.identifier('reject')), [ t.newExpression(t.identifier('Error'), [ - t.stringLiteral('Invalid client') - ]) + t.stringLiteral('Invalid client'), + ]), ] ); @@ -245,36 +242,36 @@ const ENABLED_QUERY_OPTION = t.objectProperty( function buildQueryOptions(options: ReactQueryOptions) { return options.optionalClient ? t.objectExpression([ - t.spreadElement(t.identifier('options')), - t.objectProperty( - t.identifier('enabled'), - t.logicalExpression( - '&&', - t.unaryExpression( - '!', - t.unaryExpression('!', t.identifier('client')) - ), - t.conditionalExpression( - // explicitly check for undefined - t.binaryExpression( - '!=', - t.optionalMemberExpression( + t.spreadElement(t.identifier('options')), + t.objectProperty( + t.identifier('enabled'), + t.logicalExpression( + '&&', + t.unaryExpression( + '!', + t.unaryExpression('!', t.identifier('client')) + ), + t.conditionalExpression( + // explicitly check for undefined + t.binaryExpression( + '!=', + t.optionalMemberExpression( + t.identifier('options'), + t.identifier('enabled'), + false, + true + ), + t.identifier('undefined') + ), + t.memberExpression( t.identifier('options'), - t.identifier('enabled'), - false, - true + t.identifier('enabled') ), - t.identifier('undefined') - ), - t.memberExpression( - t.identifier('options'), - t.identifier('enabled') - ), - t.booleanLiteral(true) + t.booleanLiteral(true) + ) ) - ) - ) - ]) + ), + ]) : t.identifier('options'); } @@ -286,7 +283,7 @@ export const createReactQueryHook = ({ hookKeyName, queryKeysName, methodName, - jsonschema + jsonschema, }: ReactQueryHookQuery) => { context.addUtil('useQuery'); context.addUtil('UseQueryOptions'); @@ -313,17 +310,17 @@ export const createReactQueryHook = ({ false, true ); - }) + }), ], t.tsTypeAnnotation( t.tsTypeReference( t.identifier(hookParamsTypeName), t.tsTypeParameterInstantiation([ - t.tsTypeReference(t.identifier(selectResponseGenericTypeName)) + t.tsTypeReference(t.identifier(selectResponseGenericTypeName)), ]) ) ) - ) + ), ], t.blockStatement([ t.returnStatement( @@ -335,18 +332,18 @@ export const createReactQueryHook = ({ queryKeysName, methodName, props, - options + options, }), buildQueryFn(methodName, jsonschema, options), - buildQueryOptions(options) + buildQueryOptions(options), ], t.tsTypeParameterInstantiation([ t.tsTypeReference(t.identifier(responseType)), t.tsTypeReference(t.identifier('Error')), - t.tsTypeReference(t.identifier(selectResponseGenericTypeName)) + t.tsTypeReference(t.identifier(selectResponseGenericTypeName)), ]) ) - ) + ), ]) ); @@ -356,7 +353,7 @@ export const createReactQueryHook = ({ undefined, t.tSTypeReference(t.identifier(responseType)), selectResponseGenericTypeName - ) + ), ]); return t.exportNamedDeclaration(queryFunctionDeclaration); @@ -392,7 +389,7 @@ export const createReactQueryMutationArgsInterface = ({ ExecuteClient, mutationHookParamsTypeName, useMutationTypeParameter, - jsonschema + jsonschema, }: ReactQueryMutationHookInterface) => { const typedUseMutationOptions = t.tsTypeReference( t.identifier('UseMutationOptions'), @@ -404,7 +401,7 @@ export const createReactQueryMutationArgsInterface = ({ t.identifier('client'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(ExecuteClient))), false - ) + ), ]; const msgType = createTypedObjectParams(context, jsonschema)?.typeAnnotation; @@ -427,9 +424,21 @@ export const createReactQueryMutationArgsInterface = ({ t.tsTypeAnnotation( // @ts-ignore:next-line t.tsTypeLiteral([ - propertySignature('fee', OPTIONAL_FEE_PARAM.typeAnnotation as t.TSTypeAnnotation, true), - propertySignature('memo', OPTIONAL_MEMO_PARAM.typeAnnotation as t.TSTypeAnnotation, true), - propertySignature('funds', OPTIONAL_FUNDS_PARAM.typeAnnotation as t.TSTypeAnnotation, true) + propertySignature( + 'fee', + OPTIONAL_FEE_PARAM.typeAnnotation as t.TSTypeAnnotation, + true + ), + propertySignature( + 'memo', + OPTIONAL_MEMO_PARAM.typeAnnotation as t.TSTypeAnnotation, + true + ), + propertySignature( + 'funds', + OPTIONAL_FUNDS_PARAM.typeAnnotation as t.TSTypeAnnotation, + true + ), ]) ) ); @@ -459,7 +468,7 @@ export const createReactQueryMutationHooks = ({ context, execMsg, contractName, - ExecuteClient + ExecuteClient, }: ReactQueryMutationHooks) => { // merge the user options with the defaults return getMessageProperties(execMsg).reduce((m, schema) => { @@ -493,7 +502,7 @@ export const createReactQueryMutationHooks = ({ mutationHookParamsTypeName, ExecuteClient, jsonschema, - useMutationTypeParameter + useMutationTypeParameter, }), createReactQueryMutationHook({ context, @@ -501,9 +510,9 @@ export const createReactQueryMutationHooks = ({ mutationHookName, mutationHookParamsTypeName, hasMsg, - useMutationTypeParameter + useMutationTypeParameter, }), - ...m + ...m, ]; }, []); }; @@ -523,7 +532,7 @@ const generateMutationTypeParameter = ( // Error t.tsTypeReference(t.identifier('Error')), // Variables - t.tsTypeReference(t.identifier(mutationHookParamsTypeName)) + t.tsTypeReference(t.identifier(mutationHookParamsTypeName)), ]); }; @@ -553,7 +562,7 @@ export const createReactQueryMutationHook = ({ mutationHookParamsTypeName, execMethodName, useMutationTypeParameter, - hasMsg + hasMsg, }: ReactQueryMutationHook) => { context.addUtil('useMutation'); context.addUtil('UseMutationOptions'); @@ -567,7 +576,7 @@ export const createReactQueryMutationHook = ({ t.objectPattern([ shorthandProperty('fee'), shorthandProperty('memo'), - shorthandProperty('funds') + shorthandProperty('funds'), ]), t.objectExpression([]) ) @@ -590,7 +599,7 @@ export const createReactQueryMutationHook = ({ ) ), true - ) + ), ], t.blockStatement([ t.returnStatement( @@ -607,16 +616,16 @@ export const createReactQueryMutationHook = ({ (hasMsg ? [t.identifier('msg')] : []).concat([ t.identifier('fee'), t.identifier('memo'), - t.identifier('funds') + t.identifier('funds'), ]) ), false // not async ), - t.identifier('options') + t.identifier('options'), ], useMutationTypeParameter ) - ) + ), ]) ) ); @@ -626,7 +635,7 @@ function createReactQueryKeys({ context, queryKeysName, camelContractName, - underscoreNames + underscoreNames, }: { context: RenderContext; queryKeysName: string; @@ -655,8 +664,8 @@ function createReactQueryKeys({ t.objectProperty( t.identifier('contract'), t.stringLiteral(camelContractName) - ) - ]) + ), + ]), ]), t.tSTypeReference(t.identifier('const')) ) @@ -683,8 +692,8 @@ function createReactQueryKeys({ t.objectProperty( t.identifier('address'), t.identifier('contractAddress') - ) - ]) + ), + ]), ]), t.tSTypeReference(t.identifier('const')) ) @@ -706,12 +715,12 @@ function createReactQueryKeys({ t.identifier('Record'), t.tsTypeParameterInstantiation([ t.tsStringKeyword(), - t.tsUnknownKeyword() + t.tsUnknownKeyword(), ]) ) ), true // optional - ) + ), ], t.tSAsExpression( t.arrayExpression([ @@ -736,16 +745,16 @@ function createReactQueryKeys({ t.stringLiteral(underscoreMethodName) ), // args - shorthandProperty('args') - ]) + shorthandProperty('args'), + ]), ]), t.tSTypeReference(t.identifier('const')) ) ) ) - ) + ), ]) - ) + ), ]) ); } @@ -754,7 +763,7 @@ function createReactQueryFactory({ context, queryFactoryName, queryKeysName, - queryMsgs + queryMsgs, }: { context: RenderContext; queryFactoryName: string; @@ -779,7 +788,7 @@ function createReactQueryFactory({ [ shorthandProperty('client'), ...(hasArgs ? [shorthandProperty('args')] : []), - shorthandProperty('options') + shorthandProperty('options'), ], t.tsTypeAnnotation( t.tsTypeReference( @@ -787,11 +796,11 @@ function createReactQueryFactory({ t.tsTypeParameterInstantiation([ t.tsTypeReference( t.identifier(GENERIC_SELECT_RESPONSE_NAME) - ) + ), ]) ) ) - ) + ), ], t.objectExpression([ // 1: queryKey @@ -809,7 +818,7 @@ function createReactQueryFactory({ false, true ), - ...(hasArgs ? [t.identifier('args')] : []) + ...(hasArgs ? [t.identifier('args')] : []), ] ) ), @@ -821,7 +830,7 @@ function createReactQueryFactory({ // 3: spread options t.spreadElement(t.identifier('options')), // 4. enabled - ENABLED_QUERY_OPTION + ENABLED_QUERY_OPTION, ]) ); @@ -831,7 +840,7 @@ function createReactQueryFactory({ undefined, t.tsTypeReference(t.identifier(responseType)), GENERIC_SELECT_RESPONSE_NAME - ) + ), ]); methodQueryOptionsFn.returnType = t.tsTypeAnnotation( @@ -842,7 +851,7 @@ function createReactQueryFactory({ t.tsTypeReference(t.identifier('Error')), t.tsTypeReference( t.identifier(GENERIC_SELECT_RESPONSE_NAME) - ) + ), ]) ) ); @@ -853,9 +862,9 @@ function createReactQueryFactory({ methodQueryOptionsFn ); } - ) + ), ]) - ) + ), ]) ); } @@ -871,7 +880,7 @@ const GENERIC_SELECT_RESPONSE_NAME = 'TData'; function createReactQueryHookGenericInterface({ context, QueryClient, - genericQueryInterfaceName + genericQueryInterfaceName, }: ReactQueryHookGenericInterface) { const options = context.options.reactQuery; const genericResponseTypeName = 'TResponse'; @@ -884,7 +893,7 @@ function createReactQueryHookGenericInterface({ t.tsTypeParameterInstantiation([ t.tsTypeReference(t.identifier(genericResponseTypeName)), t.tsTypeReference(t.identifier('Error')), - t.tsTypeReference(t.identifier(GENERIC_SELECT_RESPONSE_NAME)) + t.tsTypeReference(t.identifier(GENERIC_SELECT_RESPONSE_NAME)), ]) ); @@ -894,9 +903,9 @@ function createReactQueryHookGenericInterface({ t.tsTypeAnnotation( options.optionalClient ? t.tsUnionType([ - t.tsTypeReference(t.identifier(QueryClient)), - t.tsUndefinedKeyword() - ]) + t.tsTypeReference(t.identifier(QueryClient)), + t.tsUndefinedKeyword(), + ]) : t.tsTypeReference(t.identifier(QueryClient)) ), false @@ -906,21 +915,21 @@ function createReactQueryHookGenericInterface({ t.tsTypeAnnotation( options.version === 'v4' ? t.tSIntersectionType([ - omitTypeReference( - typedUseQueryOptions, - "'queryKey' | 'queryFn' | 'initialData'" - ), - t.tSTypeLiteral([ - t.tsPropertySignature( - t.identifier('initialData?'), - t.tsTypeAnnotation(t.tsUndefinedKeyword()) - ) + omitTypeReference( + typedUseQueryOptions, + "'queryKey' | 'queryFn' | 'initialData'" + ), + t.tSTypeLiteral([ + t.tsPropertySignature( + t.identifier('initialData?'), + t.tsTypeAnnotation(t.tsUndefinedKeyword()) + ), + ]), ]) - ]) : typedUseQueryOptions ), true - ) + ), ]; return t.exportNamedDeclaration( @@ -934,7 +943,7 @@ function createReactQueryHookGenericInterface({ undefined, t.tSTypeReference(t.identifier(genericResponseTypeName)), GENERIC_SELECT_RESPONSE_NAME - ) + ), ]), [], t.tSInterfaceBody(body) @@ -957,7 +966,7 @@ export const createReactQueryHookInterface = ({ hookParamsTypeName, queryInterfaceName, responseType, - jsonschema + jsonschema, }: ReactQueryHookQueryInterface) => { // merge the user options with the defaults const options = context.options.reactQuery; @@ -981,7 +990,7 @@ export const createReactQueryHookInterface = ({ t.tsInterfaceDeclaration( t.identifier(hookParamsTypeName), t.tsTypeParameterDeclaration([ - t.tSTypeParameter(undefined, undefined, GENERIC_SELECT_RESPONSE_NAME) + t.tSTypeParameter(undefined, undefined, GENERIC_SELECT_RESPONSE_NAME), ]), [ t.tSExpressionWithTypeArguments( @@ -990,9 +999,9 @@ export const createReactQueryHookInterface = ({ // 1: response t.tsTypeReference(t.identifier(responseType)), // 2: select generic - t.tSTypeReference(t.identifier(GENERIC_SELECT_RESPONSE_NAME)) + t.tSTypeReference(t.identifier(GENERIC_SELECT_RESPONSE_NAME)), ]) - ) + ), ], t.tsInterfaceBody(body) ) @@ -1026,7 +1035,7 @@ const generateUseQueryQueryKey = ({ queryKeysName, methodName, props, - options + options, }: GenerateUseQueryQueryKeyParams): t.ArrayExpression | t.CallExpression => { const { optionalClient, queryKeys } = options; @@ -1055,7 +1064,7 @@ const generateUseQueryQueryKey = ({ const queryKey: Array = [ t.stringLiteral(hookKeyName), - contractAddressExpression + contractAddressExpression, ]; if (hasArgs) { diff --git a/packages/ast/src/recoil/index.ts b/packages/ast/src/recoil/index.ts index d3d8f4df..6a1d327f 100644 --- a/packages/ast/src/recoil/index.ts +++ b/packages/ast/src/recoil/index.ts @@ -1 +1 @@ -export * from './recoil'; \ No newline at end of file +export * from './recoil'; diff --git a/packages/ast/src/recoil/recoil.ts b/packages/ast/src/recoil/recoil.ts index 49c9c012..bcd5d5da 100644 --- a/packages/ast/src/recoil/recoil.ts +++ b/packages/ast/src/recoil/recoil.ts @@ -6,7 +6,7 @@ import { RenderContext } from '../context'; import { callExpression, getMessageProperties, - getResponseType + getResponseType, } from '../utils'; export const createRecoilSelector = ( @@ -16,143 +16,100 @@ export const createRecoilSelector = ( methodName: string, responseType: string ) => { - context.addUtil('selectorFamily'); const selectorName = camel(`${methodName}Selector`); const getterKey = camel(`${keyPrefix}${pascal(methodName)}`); return t.exportNamedDeclaration( - t.variableDeclaration( - 'const', - [t.variableDeclarator( + t.variableDeclaration('const', [ + t.variableDeclarator( t.identifier(selectorName), callExpression( t.identifier('selectorFamily'), [ - t.objectExpression( - [ - t.objectProperty( - t.identifier('key'), - t.stringLiteral(getterKey) - ), - t.objectProperty( - t.identifier('get'), + t.objectExpression([ + t.objectProperty(t.identifier('key'), t.stringLiteral(getterKey)), + t.objectProperty( + t.identifier('get'), + t.arrowFunctionExpression( + [ + t.objectPattern([ + t.objectProperty( + t.identifier('params'), + t.identifier('params'), + false, + true + ), + t.restElement(t.identifier('queryClientParams')), + ]), + ], t.arrowFunctionExpression( [ - t.objectPattern( - [ - t.objectProperty( - t.identifier('params'), - t.identifier('params'), - false, - true - ), - t.restElement( - t.identifier('queryClientParams') - ) - ] - ) + t.objectPattern([ + t.objectProperty( + t.identifier('get'), + t.identifier('get'), + false, + true + ), + ]), ], - t.arrowFunctionExpression( - [ - t.objectPattern( - [ - t.objectProperty( - t.identifier('get'), - t.identifier('get'), - false, - true - ) - ] - ) - ], - t.blockStatement( - [ - t.variableDeclaration('const', - [ - t.variableDeclarator( - t.identifier('client'), - t.callExpression( - t.identifier('get'), - [ - t.callExpression( - t.identifier('queryClient'), - [ - t.identifier('queryClientParams') - ] - ) - ] - ) - ) + t.blockStatement([ + t.variableDeclaration('const', [ + t.variableDeclarator( + t.identifier('client'), + t.callExpression(t.identifier('get'), [ + t.callExpression(t.identifier('queryClient'), [ + t.identifier('queryClientParams'), ]), - t.returnStatement( - t.awaitExpression( - t.callExpression( - t.memberExpression( - t.identifier('client'), - t.identifier(methodName) - ), - [ - t.spreadElement( - t.identifier('params') - ) - ] - ) - ) + ]) + ), + ]), + t.returnStatement( + t.awaitExpression( + t.callExpression( + t.memberExpression( + t.identifier('client'), + t.identifier(methodName) + ), + [t.spreadElement(t.identifier('params'))] ) - ] + ) ), - true - ) + ]), + true ) ) - ] - ) - ], - t.tsTypeParameterInstantiation( - [ - t.tsTypeReference( - t.identifier(responseType) ), - t.tsIntersectionType( - [ - t.tsTypeReference( - t.identifier('QueryClientParams') - ), - t.tsTypeLiteral( - [ - t.tsPropertySignature( - t.identifier('params'), - t.tsTypeAnnotation( - t.tsTypeReference( - t.identifier('Parameters'), - t.tsTypeParameterInstantiation( - [ - t.tsIndexedAccessType( - t.tsTypeReference( - t.identifier(QueryClient) - ), - t.tsLiteralType( - t.stringLiteral(methodName) - ) - ) - ] - ) - ) - ) - ) - ] + ]), + ], + t.tsTypeParameterInstantiation([ + t.tsTypeReference(t.identifier(responseType)), + t.tsIntersectionType([ + t.tsTypeReference(t.identifier('QueryClientParams')), + t.tsTypeLiteral([ + t.tsPropertySignature( + t.identifier('params'), + t.tsTypeAnnotation( + t.tsTypeReference( + t.identifier('Parameters'), + t.tsTypeParameterInstantiation([ + t.tsIndexedAccessType( + t.tsTypeReference(t.identifier(QueryClient)), + t.tsLiteralType(t.stringLiteral(methodName)) + ), + ]) + ) ) - ] - ) - ] - ) + ), + ]), + ]), + ]) ) - )] - ) + ), + ]) ); - }; export const createRecoilSelectors = ( @@ -161,29 +118,26 @@ export const createRecoilSelectors = ( QueryClient: string, queryMsg: QueryMsg ): t.ExportNamedDeclaration[] => { - return getMessageProperties(queryMsg) - .map((schema: JSONSchema) => { - - const underscoreName = Object.keys(schema.properties)[0]; - const methodName = camel(underscoreName); - const responseType = getResponseType(context, underscoreName); - - return createRecoilSelector( - context, - keyPrefix, - QueryClient, - methodName, - responseType - ); - - }); + return getMessageProperties(queryMsg).map((schema: JSONSchema) => { + const underscoreName = Object.keys(schema.properties)[0]; + const methodName = camel(underscoreName); + const responseType = getResponseType(context, underscoreName); + + return createRecoilSelector( + context, + keyPrefix, + QueryClient, + methodName, + responseType + ); + }); }; export const createRecoilQueryClientType = () => ({ type: 'TSTypeAliasDeclaration', id: { type: 'Identifier', - name: 'QueryClientParams' + name: 'QueryClientParams', }, typeAnnotation: { type: 'TSTypeLiteral', @@ -192,18 +146,18 @@ export const createRecoilQueryClientType = () => ({ type: 'TSPropertySignature', key: { type: 'Identifier', - name: 'contractAddress' + name: 'contractAddress', }, computed: false, typeAnnotation: { type: 'TSTypeAnnotation', typeAnnotation: { - type: 'TSStringKeyword' - } - } - } - ] - } + type: 'TSStringKeyword', + }, + }, + }, + ], + }, }); export const createRecoilQueryClient = ( @@ -211,98 +165,71 @@ export const createRecoilQueryClient = ( keyPrefix: string, QueryClient: string ) => { - context.addUtil('selectorFamily'); const getterKey = camel(`${keyPrefix}${'QueryClient'}`); return t.exportNamedDeclaration( - t.variableDeclaration( - 'const', - [t.variableDeclarator( + t.variableDeclaration('const', [ + t.variableDeclarator( t.identifier('queryClient'), callExpression( t.identifier('selectorFamily'), [ - t.objectExpression( - [ - t.objectProperty( - t.identifier('key'), - t.stringLiteral(getterKey) - ), - t.objectProperty( - t.identifier('get'), + t.objectExpression([ + t.objectProperty(t.identifier('key'), t.stringLiteral(getterKey)), + t.objectProperty( + t.identifier('get'), + t.arrowFunctionExpression( + [ + t.objectPattern([ + t.objectProperty( + t.identifier('contractAddress'), + t.identifier('contractAddress'), + false, + true + ), + ]), + ], t.arrowFunctionExpression( [ - t.objectPattern( - [ - t.objectProperty( - t.identifier('contractAddress'), - t.identifier('contractAddress'), - false, - true - ) - ] - ) + t.objectPattern([ + t.objectProperty( + t.identifier('get'), + t.identifier('get'), + false, + true + ), + ]), ], - t.arrowFunctionExpression( - [ - t.objectPattern( - [ - t.objectProperty( - t.identifier('get'), - t.identifier('get'), - false, - true - ) - ] - ) - ], - t.blockStatement( - [ - t.variableDeclaration('const', - [ - t.variableDeclarator( - t.identifier('client'), - t.callExpression( - t.identifier('get'), - [ - t.identifier('cosmWasmClient') - ] - ) - ) - ]), - t.returnStatement( - t.newExpression( - t.identifier(QueryClient), - [ - t.identifier('client'), - t.identifier('contractAddress') - ] - ) - ) - ] + t.blockStatement([ + t.variableDeclaration('const', [ + t.variableDeclarator( + t.identifier('client'), + t.callExpression(t.identifier('get'), [ + t.identifier('cosmWasmClient'), + ]) + ), + ]), + t.returnStatement( + t.newExpression(t.identifier(QueryClient), [ + t.identifier('client'), + t.identifier('contractAddress'), + ]) ), - false - ) + ]), + false ) ) - ] - ) - ], - t.tsTypeParameterInstantiation( - [ - t.tsTypeReference( - t.identifier(QueryClient) ), - t.tsTypeReference( - t.identifier('QueryClientParams') - ) - ] - ) + ]), + ], + t.tsTypeParameterInstantiation([ + t.tsTypeReference(t.identifier(QueryClient)), + t.tsTypeReference(t.identifier('QueryClientParams')), + ]) ) - )] - ) + ), + ]) ); - }; diff --git a/packages/ast/src/types/context.ts b/packages/ast/src/types/context.ts index d0e28e1c..9f397ebb 100644 --- a/packages/ast/src/types/context.ts +++ b/packages/ast/src/types/context.ts @@ -1,12 +1,20 @@ import { IDLObject, JSONSchema } from '@cosmwasm/ts-codegen-types'; -import { MessageBuilderOptions, MessageComposerOptions, ReactQueryOptions, RecoilOptions, TSClientOptions, TSTypesOptions, UseContractsOptions } from './plugins'; +import { + MessageBuilderOptions, + MessageComposerOptions, + ReactQueryOptions, + RecoilOptions, + TSClientOptions, + TSTypesOptions, + UseContractsOptions, +} from './plugins'; export interface ContractInfo { schemas: JSONSchema[]; responses?: Record; idlObject?: Partial; -}; +} export interface RenderOptions { enabled?: boolean; types?: TSTypesOptions; @@ -19,7 +27,7 @@ export interface RenderOptions { } export interface ProviderInfo { - classname: string, - filename: string, - basename: string, + classname: string; + filename: string; + basename: string; } diff --git a/packages/ast/src/types/index.ts b/packages/ast/src/types/index.ts index 7fce5bef..9be80aed 100644 --- a/packages/ast/src/types/index.ts +++ b/packages/ast/src/types/index.ts @@ -1,2 +1,2 @@ export * from './context'; -export * from './plugins'; \ No newline at end of file +export * from './plugins'; diff --git a/packages/ast/src/types/plugins.ts b/packages/ast/src/types/plugins.ts index ae75606c..c3bafed7 100644 --- a/packages/ast/src/types/plugins.ts +++ b/packages/ast/src/types/plugins.ts @@ -4,8 +4,8 @@ export interface ReactQueryOptions { version?: 'v3' | 'v4'; mutations?: boolean; camelize?: boolean; - queryKeys?: boolean - queryFactory?: boolean + queryKeys?: boolean; + queryFactory?: boolean; } export interface TSClientOptions { @@ -33,4 +33,4 @@ export interface TSTypesOptions { export interface UseContractsOptions { enabled?: boolean; -}; +} diff --git a/packages/ast/src/utils/babel.ts b/packages/ast/src/utils/babel.ts index 852aba63..097eadbe 100644 --- a/packages/ast/src/utils/babel.ts +++ b/packages/ast/src/utils/babel.ts @@ -17,11 +17,15 @@ export const propertySignature = ( key: t.identifier(name), kind: 'get', typeAnnotation, - optional + optional, }; }; -export const identifier = (name: string, typeAnnotation: t.TSTypeAnnotation, optional: boolean = false): t.Identifier => { +export const identifier = ( + name: string, + typeAnnotation: t.TSTypeAnnotation, + optional: boolean = false +): t.Identifier => { const type = t.identifier(name); type.typeAnnotation = typeAnnotation; type.optional = optional; @@ -37,9 +41,13 @@ export const tsTypeOperator = (typeAnnotation: t.TSType, operator: string) => { export const getMessageProperties = (msg: JSONSchema): JSONSchema[] => { let results: JSONSchema[] = []; let objs: JSONSchema[] = []; - if (msg.anyOf) { objs = msg.anyOf; } - else if (msg.oneOf) { objs = msg.oneOf; } - else if (msg.allOf) { objs = msg.allOf; } + if (msg.anyOf) { + objs = msg.anyOf; + } else if (msg.oneOf) { + objs = msg.oneOf; + } else if (msg.allOf) { + objs = msg.allOf; + } for (const obj of objs) { if (obj.properties) { @@ -68,15 +76,11 @@ export const tsPropertySignature = ( return obj; }; - - export const tsObjectPattern = ( properties: (t.RestElement | t.ObjectProperty)[], typeAnnotation: t.TSTypeAnnotation ) => { - const obj = t.objectPattern( - properties - ); + const obj = t.objectPattern(properties); obj.typeAnnotation = typeAnnotation; return obj; }; @@ -93,27 +97,25 @@ export const callExpression = ( export const bindMethod = (name: string) => { return t.expressionStatement( - t.assignmentExpression('=', t.memberExpression( - t.thisExpression(), - t.identifier(name) - ), - t.callExpression( - t.memberExpression( + t.assignmentExpression( + '=', + t.memberExpression(t.thisExpression(), t.identifier(name)), + t.callExpression( t.memberExpression( - t.thisExpression(), - t.identifier(name) + t.memberExpression(t.thisExpression(), t.identifier(name)), + t.identifier('bind') ), - t.identifier('bind') - ), - [ - t.thisExpression() - ] - ) + [t.thisExpression()] + ) ) ); }; -export const typedIdentifier = (name: string, typeAnnotation: TSTypeAnnotation, optional: boolean = false) => { +export const typedIdentifier = ( + name: string, + typeAnnotation: TSTypeAnnotation, + optional: boolean = false +) => { const type = t.identifier(name); type.typeAnnotation = typeAnnotation; type.optional = optional; @@ -124,16 +126,17 @@ export const promiseTypeAnnotation = (name: string): t.TSTypeAnnotation => { return t.tsTypeAnnotation( t.tsTypeReference( t.identifier('Promise'), - t.tsTypeParameterInstantiation( - [ - t.tsTypeReference(t.identifier(name)) - ] - ) + t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(name))]) ) ); }; -export const abstractClassDeclaration = (name: string, body: any[], implementsExressions: TSExpressionWithTypeArguments[] = [], superClass: t.Identifier = null) => { +export const abstractClassDeclaration = ( + name: string, + body: any[], + implementsExressions: TSExpressionWithTypeArguments[] = [], + superClass: t.Identifier = null +) => { const declaration = classDeclaration( name, body, @@ -144,7 +147,12 @@ export const abstractClassDeclaration = (name: string, body: any[], implementsEx return declaration; }; -export const classDeclaration = (name: string, body: any[], implementsExressions: TSExpressionWithTypeArguments[] = [], superClass: t.Identifier = null) => { +export const classDeclaration = ( + name: string, + body: any[], + implementsExressions: TSExpressionWithTypeArguments[] = [], + superClass: t.Identifier = null +) => { const declaration = t.classDeclaration( t.identifier(name), superClass, @@ -156,14 +164,13 @@ export const classDeclaration = (name: string, body: any[], implementsExressions return declaration; }; - export const classProperty = ( name: string, typeAnnotation: TSTypeAnnotation = null, isReadonly: boolean = false, isStatic: boolean = false, noImplicitOverride: boolean = false, - useDeclareKeyword: boolean = false, + useDeclareKeyword: boolean = false ) => { const prop = t.classProperty(t.identifier(name)); if (isReadonly) prop.readonly = true; @@ -185,8 +192,10 @@ export const arrowFunctionExpression = ( return func; }; - -export const recursiveNamespace = (names: string[], moduleBlockBody: any): t.ExportNamedDeclaration[] => { +export const recursiveNamespace = ( + names: string[], + moduleBlockBody: any +): t.ExportNamedDeclaration[] => { if (!names || !names.length) return moduleBlockBody; const name = names.pop(); const body = [ @@ -195,23 +204,23 @@ export const recursiveNamespace = (names: string[], moduleBlockBody: any): t.Exp t.identifier(name), t.tsModuleBlock(recursiveNamespace(names, moduleBlockBody)) ) - ) + ), ]; return body; }; export const arrayTypeNDimensions = (body: any, n: number): t.TSArrayType => { if (!n) return t.tsArrayType(body); - return t.tsArrayType( - arrayTypeNDimensions(body, n - 1) - ); + return t.tsArrayType(arrayTypeNDimensions(body, n - 1)); }; export const FieldTypeAsts = { string: () => { return t.tsStringKeyword(); }, - array: (type: 'string' | 'Duration' | 'Height' | 'Coin' | 'Long'): t.TSArrayType => { + array: ( + type: 'string' | 'Duration' | 'Height' | 'Coin' | 'Long' + ): t.TSArrayType => { const result = FieldTypeAsts[type](); return t.tsArrayType(result); }, @@ -226,27 +235,32 @@ export const FieldTypeAsts = { }, Long: () => { return t.tsTypeReference(t.identifier('Long')); - } + }, }; export const shorthandProperty = (prop: string): t.ObjectProperty => { return t.objectProperty(t.identifier(prop), t.identifier(prop), false, true); }; -export const importStmt = (names: string[], path: string): t.ImportDeclaration => { +export const importStmt = ( + names: string[], + path: string +): t.ImportDeclaration => { return t.importDeclaration( - names.map(name => t.importSpecifier(t.identifier(name), t.identifier(name))), - t.stringLiteral(path)); + names.map((name) => + t.importSpecifier(t.identifier(name), t.identifier(name)) + ), + t.stringLiteral(path) + ); }; -export const importAs = (name: string, importAs: string, importPath: string): t.ImportDeclaration => { +export const importAs = ( + name: string, + importAs: string, + importPath: string +): t.ImportDeclaration => { return t.importDeclaration( - [ - t.importSpecifier( - t.identifier(importAs), - t.identifier(name) - ) - ], + [t.importSpecifier(t.identifier(importAs), t.identifier(name))], t.stringLiteral(importPath) ); }; @@ -266,20 +280,19 @@ export const getFieldDimensionality = (field: Field) => { return { typeName, dimensions, - isArray + isArray, }; }; -export const memberExpressionOrIdentifier = (names: string[]): t.MemberExpression | t.Identifier => { +export const memberExpressionOrIdentifier = ( + names: string[] +): t.MemberExpression | t.Identifier => { if (names.length === 1) { return t.identifier(names[0]); } if (names.length === 2) { const [b, a] = names; - return t.memberExpression( - t.identifier(a), - t.identifier(b) - ); + return t.memberExpression(t.identifier(a), t.identifier(b)); } const [name, ...rest] = names; @@ -289,16 +302,15 @@ export const memberExpressionOrIdentifier = (names: string[]): t.MemberExpressio ); }; -export const memberExpressionOrIdentifierSnake = (names: string[]): t.MemberExpression | t.Identifier => { +export const memberExpressionOrIdentifierSnake = ( + names: string[] +): t.MemberExpression | t.Identifier => { if (names.length === 1) { return t.identifier(snake(names[0])); } if (names.length === 2) { const [b, a] = names; - return t.memberExpression( - t.identifier(snake(a)), - t.identifier(snake(b)) - ); + return t.memberExpression(t.identifier(snake(a)), t.identifier(snake(b))); } const [name, ...rest] = names; @@ -311,34 +323,39 @@ export const memberExpressionOrIdentifierSnake = (names: string[]): t.MemberExpr /** * If optional, return a conditional, otherwise just the expression */ -export const optionalConditionalExpression = (test: t.Expression, expression: t.Expression, alternate: t.Expression, optional: boolean = false): t.Expression => { +export const optionalConditionalExpression = ( + test: t.Expression, + expression: t.Expression, + alternate: t.Expression, + optional: boolean = false +): t.Expression => { return optional - ? t.conditionalExpression( - test, - expression, - alternate - ) + ? t.conditionalExpression(test, expression, alternate) : expression; }; -export const typeRefOrUnionWithUndefined = (identifier: t.Identifier, optional: boolean = false): t.TSType => { +export const typeRefOrUnionWithUndefined = ( + identifier: t.Identifier, + optional: boolean = false +): t.TSType => { const typeReference = t.tsTypeReference(identifier); return optional - ? t.tsUnionType([ - typeReference, - t.tsUndefinedKeyword() - ]) + ? t.tsUnionType([typeReference, t.tsUndefinedKeyword()]) : typeReference; }; -export const parameterizedTypeReference = (identifier: string, from: t.TSType, omit: string | Array) => { +export const parameterizedTypeReference = ( + identifier: string, + from: t.TSType, + omit: string | Array +) => { return t.tsTypeReference( t.identifier(identifier), t.tsTypeParameterInstantiation([ from, typeof omit === 'string' ? t.tsLiteralType(t.stringLiteral(omit)) - : t.tsUnionType(omit.map(o => t.tsLiteralType(t.stringLiteral(o)))) + : t.tsUnionType(omit.map((o) => t.tsLiteralType(t.stringLiteral(o)))), ]) ); }; @@ -347,11 +364,16 @@ export const parameterizedTypeReference = (identifier: string, from: t.TSType, o * omitTypeReference(t.tsTypeReference(t.identifier('Cw4UpdateMembersMutation'),),'args')..... * Omit */ -export const omitTypeReference = (from: t.TSType, omit: string | Array) => { +export const omitTypeReference = ( + from: t.TSType, + omit: string | Array +) => { return parameterizedTypeReference('Omit', from, omit); }; - -export const pickTypeReference = (from: t.TSType, pick: string | Array) => { +export const pickTypeReference = ( + from: t.TSType, + pick: string | Array +) => { return parameterizedTypeReference('Pick', from, pick); }; diff --git a/packages/ast/src/utils/constants.ts b/packages/ast/src/utils/constants.ts index eda1a120..ae428d21 100644 --- a/packages/ast/src/utils/constants.ts +++ b/packages/ast/src/utils/constants.ts @@ -13,7 +13,7 @@ export const OPTIONAL_FEE_PARAM = identifier( t.tsUnionType([ t.tsNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), - t.tsLiteralType(t.stringLiteral('auto')) + t.tsLiteralType(t.stringLiteral('auto')), ]) ), true @@ -27,12 +27,12 @@ export const OPTIONAL_MEMO_PARAM = identifier( export const FIXED_EXECUTE_PARAMS = [ OPTIONAL_FEE_PARAM, OPTIONAL_MEMO_PARAM, - OPTIONAL_FUNDS_PARAM + OPTIONAL_FUNDS_PARAM, ]; export const PROVIDER_TYPES = { SIGNING_CLIENT_TYPE: 'client', QUERY_CLIENT_TYPE: 'queryClient', - MESSAGE_COMPOSER_TYPE : 'message-composer', - PROVIDER_TYPE : 'provider' + MESSAGE_COMPOSER_TYPE: 'message-composer', + PROVIDER_TYPE: 'provider', }; diff --git a/packages/ast/src/utils/ref.ts b/packages/ast/src/utils/ref.ts index 0c5306e0..42579151 100644 --- a/packages/ast/src/utils/ref.ts +++ b/packages/ast/src/utils/ref.ts @@ -3,4 +3,4 @@ import { JSONSchema } from '@cosmwasm/ts-codegen-types'; export const refLookup = ($ref: string, schema: JSONSchema): JSONSchema => { const refName = $ref.replace('#/definitions/', ''); return schema.definitions?.[refName]; -}; \ No newline at end of file +}; diff --git a/packages/ast/src/utils/types.ts b/packages/ast/src/utils/types.ts index 58419739..f6203a0b 100644 --- a/packages/ast/src/utils/types.ts +++ b/packages/ast/src/utils/types.ts @@ -11,12 +11,11 @@ export function getResponseType( ) { const methodName = camel(underscoreName); return pascal( - context.contract?.responses?.[underscoreName]?.title - ?? - // after v1.1 is adopted, we can deprecate this and require the above response - `${methodName}Response` + context.contract?.responses?.[underscoreName]?.title ?? + // after v1.1 is adopted, we can deprecate this and require the above response + `${methodName}Response` ); -}; +} const getTypeStrFromRef = ($ref: string): string => { if ($ref?.startsWith('#/definitions/')) { @@ -30,12 +29,9 @@ export const getTypeFromRef = ($ref: string) => { }; const getArrayTypeFromRef = ($ref: string) => { - return t.tsArrayType( - getTypeFromRef($ref) - ); + return t.tsArrayType(getTypeFromRef($ref)); }; - export const getTypeOrRef = (obj: JSONSchema): t.TSType => { if (obj.$ref) { return getTypeFromRef(obj.$ref); @@ -43,10 +39,12 @@ export const getTypeOrRef = (obj: JSONSchema): t.TSType => { return getType(obj.type); } else if (Array.isArray(obj.type)) { // Handle array of types by creating a union type - const types = obj.type.map(t => getType(t)); + const types = obj.type.map((t) => getType(t)); return t.tsUnionType(types); } else { - throw new Error('Type definition not supported or missing: ' + JSON.stringify(obj)); + throw new Error( + 'Type definition not supported or missing: ' + JSON.stringify(obj) + ); } }; @@ -65,31 +63,25 @@ const getArrayTypeFromItems = ( if (items.length > 0 && items[0].type === 'array') { return getArrayTypeFromItems(context, items[0]); } - return items.length > 0 ? t.tsArrayType(t.tsArrayType(getTypeOrRef(items[0]))) : t.tsArrayType(t.tsArrayType(t.tsAnyKeyword())); + return items.length > 0 + ? t.tsArrayType(t.tsArrayType(getTypeOrRef(items[0]))) + : t.tsArrayType(t.tsArrayType(t.tsAnyKeyword())); // } } else { const detect = detectType(items.type); if (detect.type === 'array') { if (Array.isArray(items.items)) { - return t.tsArrayType( - t.tsArrayType( - getTypeOrRef(items.items[0]) - ) - ); + return t.tsArrayType(t.tsArrayType(getTypeOrRef(items.items[0]))); } else if (items.items) { - return t.tsArrayType( - getArrayTypeFromItems(context, items.items) - ); + return t.tsArrayType(getArrayTypeFromItems(context, items.items)); } else { // Handle the case where items.items is undefined for array types return t.tsArrayType(t.tsAnyKeyword()); } } - return t.tsArrayType( - getType(detect.type) - ); + return t.tsArrayType(getType(detect.type)); } }; @@ -98,11 +90,15 @@ export const detectType = (type: string | string[]) => { let theType = ''; if (Array.isArray(type)) { if (type.length !== 2) { - throw new Error('[getType(array length)] case not handled by transpiler. contact maintainers.'); + throw new Error( + '[getType(array length)] case not handled by transpiler. contact maintainers.' + ); } const [nullableType, nullType] = type; if (nullType !== 'null') { - throw new Error('[getType(null)] case not handled by transpiler. contact maintainers.'); + throw new Error( + '[getType(null)] case not handled by transpiler. contact maintainers.' + ); } theType = nullableType; optional = true; @@ -112,14 +108,11 @@ export const detectType = (type: string | string[]) => { return { type: theType, - optional + optional, }; }; -export const getTypeInfo = ( - context: RenderContext, - info: JSONSchema -) => { +export const getTypeInfo = (context: RenderContext, info: JSONSchema) => { let type = undefined; let optional = undefined; @@ -130,13 +123,17 @@ export const getTypeInfo = ( } const [nullableType, nullType] = info.anyOf; if (nullType?.type !== 'null') { - throw new Error('[nullableType.type]: case not handled by transpiler. contact maintainers.'); + throw new Error( + '[nullableType.type]: case not handled by transpiler. contact maintainers.' + ); } if (!nullableType?.$ref) { if (nullableType.title) { type = t.tsTypeReference(t.identifier(nullableType.title)); } else { - throw new Error('[nullableType.title] case not handled by transpiler. contact maintainers.'); + throw new Error( + '[nullableType.title] case not handled by transpiler. contact maintainers.' + ); } } else { type = getTypeFromRef(nullableType.$ref); @@ -149,18 +146,24 @@ export const getTypeInfo = ( if (info.items.$ref) { type = getArrayTypeFromRef(info.items.$ref); } else if (info.items.title) { - type = t.tsArrayType(t.tsTypeReference(t.identifier(info.items.title))); + type = t.tsArrayType( + t.tsTypeReference(t.identifier(info.items.title)) + ); } else if (info.items.type) { type = getArrayTypeFromItems(context, info.items); } else { - throw new Error('[info.items] case not handled by transpiler. contact maintainers.'); + throw new Error( + '[info.items] case not handled by transpiler. contact maintainers.' + ); } // type = getArrayTypeFromItems(context, info.items); } else { if (Array.isArray(info.items)) { type = getArrayTypeFromItems(context, info.items); } else { - throw new Error('[info.items] case not handled by transpiler. contact maintainers.'); + throw new Error( + '[info.items] case not handled by transpiler. contact maintainers.' + ); } } } else { @@ -171,14 +174,24 @@ export const getTypeInfo = ( } else if (Array.isArray(info.type)) { // Handle multiple types, typically nullable types if (info.type.length !== 2) { - throw new Error('please report this to maintainers (field type): ' + JSON.stringify(info, null, 2)); + throw new Error( + 'please report this to maintainers (field type): ' + + JSON.stringify(info, null, 2) + ); } const [nullableType, nullType] = info.type; if (nullType !== 'null') { - throw new Error('please report this to maintainers (field type): ' + JSON.stringify(info, null, 2)); + throw new Error( + 'please report this to maintainers (field type): ' + + JSON.stringify(info, null, 2) + ); } - if (nullableType === 'array' && typeof info.items === 'object' && !Array.isArray(info.items)) { + if ( + nullableType === 'array' && + typeof info.items === 'object' && + !Array.isArray(info.items) + ) { if (info.items.type) { const detect = detectType(info.items.type); if (detect.type === 'array') { @@ -189,10 +202,10 @@ export const getTypeInfo = ( optional = detect.optional; } else if (info.items.$ref) { type = getArrayTypeFromRef(info.items.$ref); - } else if (info.items.type) { - type = getArrayTypeFromItems(context, info.items); } else { - throw new Error('[info.items] case not handled by transpiler. contact maintainers.'); + throw new Error( + '[info.items] case not handled by transpiler. contact maintainers.' + ); } } else { const detect = detectType(nullableType); @@ -204,28 +217,28 @@ export const getTypeInfo = ( } } - optional = true; // Ensure optional is set for nullable types + optional = true; // Ensure optional is set for nullable types } return { type, - optional + optional, }; }; export const getType = (type: string) => { switch (type) { - case 'string': - return t.tsStringKeyword(); - case 'boolean': - return t.tSBooleanKeyword(); - case 'integer': - return t.tsNumberKeyword(); - case 'null': - return t.tsNullKeyword(); - case 'number': - return t.tsNumberKeyword(); - default: - throw new Error('contact maintainers [unknown type]: ' + type); + case 'string': + return t.tsStringKeyword(); + case 'boolean': + return t.tSBooleanKeyword(); + case 'integer': + return t.tsNumberKeyword(); + case 'null': + return t.tsNullKeyword(); + case 'number': + return t.tsNumberKeyword(); + default: + throw new Error('contact maintainers [unknown type]: ' + type); } }; @@ -267,7 +280,6 @@ export const getPropertyType = ( return { type, optional }; }; - export function getPropertySignatureFromProp( context: RenderContext, jsonschema: JSONSchema, @@ -289,11 +301,13 @@ export function getPropertySignatureFromProp( if (Array.isArray(jsonschema.properties[prop].allOf)) { const isOptional = !jsonschema.required?.includes(prop); - const unionTypes = jsonschema.properties[prop].allOf.map(el => { - if (el.title) return el.title; - if (el.$ref) return getTypeStrFromRef(el.$ref); - return el.type; - }).filter(a => typeof a === 'string'); + const unionTypes = jsonschema.properties[prop].allOf + .map((el) => { + if (el.title) return el.title; + if (el.$ref) return getTypeStrFromRef(el.$ref); + return el.type; + }) + .filter((a) => typeof a === 'string'); // ONLY SUPPORT string types for now! // e.g. NOT supporting nullable types or type: string[] yet @@ -304,9 +318,7 @@ export function getPropertySignatureFromProp( return propertySignature( camelize ? camel(prop) : prop, t.tsTypeAnnotation( - t.tsTypeReference( - t.identifier(uniqUnionTypes[0] as string) - ) + t.tsTypeReference(t.identifier(uniqUnionTypes[0] as string)) ), isOptional ); @@ -315,10 +327,8 @@ export function getPropertySignatureFromProp( camelize ? camel(prop) : prop, t.tsTypeAnnotation( t.tsUnionType( - uniqUnionTypes.map(typ => - t.tsTypeReference( - t.identifier(typ as string) - ) + uniqUnionTypes.map((typ) => + t.tsTypeReference(t.identifier(typ as string)) ) ) ), @@ -327,11 +337,13 @@ export function getPropertySignatureFromProp( } } else if (Array.isArray(jsonschema.properties[prop].oneOf)) { const isOptional = !jsonschema.required?.includes(prop); - const unionTypes = jsonschema.properties[prop].oneOf.map(el => { - if (el.title) return el.title; - if (el.$ref) return getTypeStrFromRef(el.$ref); - return el.type; - }).filter(a => typeof a === 'string'); + const unionTypes = jsonschema.properties[prop].oneOf + .map((el) => { + if (el.title) return el.title; + if (el.$ref) return getTypeStrFromRef(el.$ref); + return el.type; + }) + .filter((a) => typeof a === 'string'); // ONLY SUPPORT string types for now! // e.g. NOT supporting nullable types or type: string[] yet @@ -340,9 +352,7 @@ export function getPropertySignatureFromProp( return propertySignature( camelize ? camel(prop) : prop, t.tsTypeAnnotation( - t.tsTypeReference( - t.identifier(uniqUnionTypes[0] as string) - ) + t.tsTypeReference(t.identifier(uniqUnionTypes[0] as string)) ), isOptional ); @@ -351,17 +361,14 @@ export function getPropertySignatureFromProp( camelize ? camel(prop) : prop, t.tsTypeAnnotation( t.tsUnionType( - uniqUnionTypes.map(typ => - t.tsTypeReference( - t.identifier(typ as string) - ) + uniqUnionTypes.map((typ) => + t.tsTypeReference(t.identifier(typ as string)) ) ) ), isOptional ); } - } try { @@ -374,9 +381,7 @@ export function getPropertySignatureFromProp( const { type, optional } = getPropertyType(context, jsonschema, prop); return propertySignature( camelize ? camel(prop) : prop, - t.tsTypeAnnotation( - type - ), + t.tsTypeAnnotation(type), optional ); } @@ -394,19 +399,14 @@ export const getParamsTypeAnnotation = ( if (!keys.length) return undefined; - const typedParams = keys.map(prop => getPropertySignatureFromProp( - context, - jsonschema, - prop, - camelize - )); + const typedParams = keys.map((prop) => + getPropertySignatureFromProp(context, jsonschema, prop, camelize) + ); return t.tsTypeAnnotation( t.tsTypeLiteral( // @ts-ignore:next-line - [ - ...typedParams - ] + [...typedParams] ) ); }; @@ -415,8 +415,7 @@ export const createTypedObjectParams = ( context: RenderContext, jsonschema: JSONSchema, camelize: boolean = true -): (t.Identifier | t.Pattern | t.RestElement) => { - +): t.Identifier | t.Pattern | t.RestElement => { const keys = Object.keys(jsonschema.properties ?? {}); if (!keys.length) { // is there a ref? @@ -428,14 +427,12 @@ export const createTypedObjectParams = ( const refType = jsonschema.$ref.split('/').pop(); const refName = camel(refType); const id = t.identifier(refName); - id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(refType))); + id.typeAnnotation = t.tsTypeAnnotation( + t.tsTypeReference(t.identifier(refType)) + ); return id; } else if (obj) { - return createTypedObjectParams( - context, - obj, - camelize - ); + return createTypedObjectParams(context, obj, camelize); } } @@ -443,7 +440,7 @@ export const createTypedObjectParams = ( return; } - const params = keys.map(prop => { + const params = keys.map((prop) => { return t.objectProperty( camelize ? t.identifier(camel(prop)) : t.identifier(prop), camelize ? t.identifier(camel(prop)) : t.identifier(prop), @@ -452,17 +449,9 @@ export const createTypedObjectParams = ( ); }); - const obj = t.objectPattern( - [ - ...params - ] - ); + const obj = t.objectPattern([...params]); - obj.typeAnnotation = getParamsTypeAnnotation( - context, - jsonschema, - camelize - ); + obj.typeAnnotation = getParamsTypeAnnotation(context, jsonschema, camelize); return obj; -}; \ No newline at end of file +}; diff --git a/packages/ast/test-utils/utils.ts b/packages/ast/test-utils/utils.ts index 71ce0709..f16ad2a3 100644 --- a/packages/ast/test-utils/utils.ts +++ b/packages/ast/test-utils/utils.ts @@ -1,6 +1,11 @@ import generate from '@babel/generator'; import { RenderOptions } from '@cosmwasm/ts-codegen-ast/types'; -import { ExecuteMsg, IDLObject, JSONSchema, QueryMsg } from '@cosmwasm/ts-codegen-types'; +import { + ExecuteMsg, + IDLObject, + JSONSchema, + QueryMsg, +} from '@cosmwasm/ts-codegen-types'; import { readFileSync } from 'fs'; import { sync as glob } from 'glob'; import { join } from 'path'; @@ -8,15 +13,11 @@ import { join } from 'path'; import { RenderContext } from '../src/context'; export const expectCode = (ast: any): void => { - expect( - generate(ast).code - ).toMatchSnapshot(); + expect(generate(ast).code).toMatchSnapshot(); }; export const printCode = (ast: any): void => { - console.log( - generate(ast).code - ); + console.log(generate(ast).code); }; export const makeContext = ( @@ -24,10 +25,13 @@ export const makeContext = ( options?: RenderOptions, responses?: Record ) => { - return new RenderContext({ - schemas: [schema], - responses - }, options); + return new RenderContext( + { + schemas: [schema], + responses, + }, + options + ); }; interface GlobContractLegacy { @@ -46,12 +50,14 @@ const globCache: Record = {}; export const globIdlBasedContracts = (p: string): GlobContract[] => { if (globCache[p]) return globCache[p] as GlobContract[]; // @ts-ignore - const contracts: GlobContract[] = glob(join(fixtureDir, p, '/*.json')).map(file => { - return { - name: file.split(join('__fixtures__', p))[1], - content: JSON.parse(readFileSync(file, 'utf-8')) - }; - }); + const contracts: GlobContract[] = glob(join(fixtureDir, p, '/*.json')).map( + (file) => { + return { + name: file.split(join('__fixtures__', p))[1], + content: JSON.parse(readFileSync(file, 'utf-8')), + }; + } + ); globCache[p] = contracts; return contracts; }; @@ -59,10 +65,12 @@ export const globIdlBasedContracts = (p: string): GlobContract[] => { export const globLegacyContracts = (p: string): GlobContractLegacy[] => { if (globCache[p]) return globCache[p] as GlobContractLegacy[]; // @ts-ignore - const contracts: GlobContractLegacy[] = glob(join(fixtureDir, p, '/*.json')).map(file => { + const contracts: GlobContractLegacy[] = glob( + join(fixtureDir, p, '/*.json') + ).map((file) => { return { name: file.split(join('__fixtures__', p))[1], - content: JSON.parse(readFileSync(file, 'utf-8')) + content: JSON.parse(readFileSync(file, 'utf-8')), }; }); globCache[p] = contracts; @@ -74,7 +82,7 @@ export const getMsgExecuteLegacyFixture = ( name: `/${string}.json` ): ExecuteMsg => { const contracts = globLegacyContracts(p); - const contract = contracts.find(a => a.name === name); + const contract = contracts.find((a) => a.name === name); return contract.content as ExecuteMsg; }; @@ -83,7 +91,7 @@ export const getMsgQueryLegacyFixture = ( name: `/${string}.json` ): QueryMsg => { const contracts = globLegacyContracts(p); - const contract = contracts.find(a => a.name === name); + const contract = contracts.find((a) => a.name === name); return contract.content as QueryMsg; }; @@ -92,6 +100,6 @@ export const getLegacyFixture = ( name: `/${string}.json` ): JSONSchema => { const contracts = globLegacyContracts(p); - const contract = contracts.find(a => a.name === name); + const contract = contracts.find((a) => a.name === name); return contract.content as JSONSchema; }; diff --git a/packages/ts-codegen/.eslintignore b/packages/ts-codegen/.eslintignore new file mode 120000 index 00000000..86039baf --- /dev/null +++ b/packages/ts-codegen/.eslintignore @@ -0,0 +1 @@ +../../.eslintignore \ No newline at end of file diff --git a/packages/ts-codegen/__tests__/builder.test.ts b/packages/ts-codegen/__tests__/builder.test.ts index a0ac37b6..bf9b3020 100644 --- a/packages/ts-codegen/__tests__/builder.test.ts +++ b/packages/ts-codegen/__tests__/builder.test.ts @@ -8,13 +8,11 @@ it('options undefined', async () => { const outPath = OUTPUT_DIR + '/vectis/factory-opt'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const builder = new TSBuilder({ - contracts: [ - schemaDir - ], + contracts: [schemaDir], outPath, - options: undefined + options: undefined, }); - // @ts-ignore + // @ts-ignore delete builder.contracts; // @ts-ignore delete builder.outPath; @@ -25,23 +23,21 @@ it('options tsClient.enabled', async () => { const outPath = OUTPUT_DIR + '/vectis/factory-opt'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const builder = new TSBuilder({ - contracts: [ - schemaDir - ], + contracts: [schemaDir], outPath, options: { types: { - enabled: true + enabled: true, }, client: { - enabled: true + enabled: true, }, reactQuery: { - enabled: true - } - } + enabled: true, + }, + }, }); - // @ts-ignore + // @ts-ignore delete builder.contracts; // @ts-ignore delete builder.outPath; @@ -59,21 +55,21 @@ it('builder invoke', async () => { s('/daodao/cw-code-id-registry'), { name: 'CwSingle', - dir: s('/daodao/cw-proposal-single') - } + dir: s('/daodao/cw-proposal-single'), + }, ], outPath, options: { types: { - enabled: true + enabled: true, }, client: { - enabled: true + enabled: true, }, reactQuery: { - enabled: true - } - } + enabled: true, + }, + }, }); await builder.build(); }); @@ -89,39 +85,39 @@ it('builder default', async () => { s('/daodao/cw-code-id-registry'), { name: 'CwSingle', - dir: s('/daodao/cw-proposal-single') - } + dir: s('/daodao/cw-proposal-single'), + }, ], outPath, options: { bundle: { bundleFile: 'index.ts', - scope: 'smart.contracts' + scope: 'smart.contracts', }, useShorthandCtor: false, types: { - enabled: true + enabled: true, }, client: { enabled: true, - execExtendsQuery: true + execExtendsQuery: true, }, reactQuery: { - enabled: true + enabled: true, }, recoil: { - enabled: true + enabled: true, }, messageComposer: { - enabled: true + enabled: true, }, messageBuilder: { - enabled: true + enabled: true, }, useContractsHook: { enabled: true, - } - } + }, + }, }); }); @@ -136,35 +132,35 @@ it('builder no extends', async () => { s('/daodao/cw-code-id-registry'), { name: 'CwSingle', - dir: s('/daodao/cw-proposal-single') - } + dir: s('/daodao/cw-proposal-single'), + }, ], outPath, options: { bundle: { bundleFile: 'index.ts', - scope: 'smart.contracts' + scope: 'smart.contracts', }, types: { - enabled: true + enabled: true, }, client: { enabled: true, - execExtendsQuery: false + execExtendsQuery: false, }, reactQuery: { - enabled: true + enabled: true, }, recoil: { - enabled: true + enabled: true, }, messageComposer: { - enabled: true + enabled: true, }, messageBuilder: { - enabled: true - } - } + enabled: true, + }, + }, }); }); @@ -180,36 +176,35 @@ it('builder set bundler path', async () => { s('/daodao/cw-code-id-registry'), { name: 'CwSingle', - dir: s('/daodao/cw-proposal-single') - } + dir: s('/daodao/cw-proposal-single'), + }, ], outPath, options: { bundle: { bundlePath: bundlerPath, bundleFile: 'index.ts', - scope: 'smart.contracts' + scope: 'smart.contracts', }, types: { - enabled: true + enabled: true, }, client: { enabled: true, - execExtendsQuery: false + execExtendsQuery: false, }, reactQuery: { - enabled: true + enabled: true, }, recoil: { - enabled: true + enabled: true, }, messageComposer: { - enabled: true + enabled: true, }, useContractsHook: { enabled: true, - } - } + }, + }, }); }); - diff --git a/packages/ts-codegen/__tests__/bundler.test.ts b/packages/ts-codegen/__tests__/bundler.test.ts index bb02e3e5..f499c5ed 100644 --- a/packages/ts-codegen/__tests__/bundler.test.ts +++ b/packages/ts-codegen/__tests__/bundler.test.ts @@ -2,10 +2,7 @@ import generate from '@babel/generator'; import * as t from '@babel/types'; import cases from 'jest-in-case'; -import { - BundleData, - recursiveModuleBundle -} from '../src/bundler'; +import { BundleData, recursiveModuleBundle } from '../src/bundler'; const preview = (ast: any) => { // @ts-ignore @@ -13,159 +10,163 @@ const preview = (ast: any) => { }; interface JestBundleData { - name: string; - data: BundleData + name: string; + data: BundleData; } -cases(`recursiveModuleBundle`, (opts: JestBundleData) => { - expect(preview(recursiveModuleBundle(opts.data))).toMatchSnapshot(); -}, [ - { - name: 'root', - data: { - osmosis: { - __export: true, - _0: true - }, - tendermint: { - __export: true, - _0: true - } - } - }, - { - name: 'single', - data: { - ics23: { - __export: true, - _0: true - } - } +cases( + `recursiveModuleBundle`, + (opts: JestBundleData) => { + expect(preview(recursiveModuleBundle(opts.data))).toMatchSnapshot(); }, - { - name: 'tendermint', - data: { - tendermint: { - abci: { + [ + { + name: 'root', + data: { + osmosis: { __export: true, - _223: true + _0: true, }, - crypto: { + tendermint: { __export: true, - _224: true, - _225: true - }, - libs: { - bits: { - __export: true, - _226: true - } + _0: true, }, - p2p: { - __export: true, - _227: true - }, - types: { + }, + }, + { + name: 'single', + data: { + ics23: { __export: true, - _228: true, - _229: true, - _230: true, - _231: true, - _232: true + _0: true, }, - version: { - __export: true, - _233: true - } - } - } - }, - { - name: 'osmo', - data: { - osmosis: { - claim: { - v1beta1: { + }, + }, + { + name: 'tendermint', + data: { + tendermint: { + abci: { __export: true, - _177: true, - _178: true, - _179: true, - _180: true - } - }, - epochs: { - v1beta1: { + _223: true, + }, + crypto: { __export: true, - _181: true, - _182: true - } - }, - gamm: { - v1beta1: { + _224: true, + _225: true, + }, + libs: { + bits: { + __export: true, + _226: true, + }, + }, + p2p: { __export: true, - _183: true, - _184: true, - _185: true, - _186: true, - _187: true - } - }, - incentives: { - __export: true, - _188: true, - _189: true, - _190: true, - _191: true, - _192: true - }, - lockup: { - __export: true, - _193: true, - _194: true, - _195: true, - _196: true - }, - mint: { - v1beta1: { + _227: true, + }, + types: { __export: true, - _197: true, - _198: true, - _199: true - } - }, - poolincentives: { - v1beta1: { + _228: true, + _229: true, + _230: true, + _231: true, + _232: true, + }, + version: { __export: true, - _200: true, - _201: true, - _202: true, - _203: true - } + _233: true, + }, }, - store: { - v1beta1: { + }, + }, + { + name: 'osmo', + data: { + osmosis: { + claim: { + v1beta1: { + __export: true, + _177: true, + _178: true, + _179: true, + _180: true, + }, + }, + epochs: { + v1beta1: { + __export: true, + _181: true, + _182: true, + }, + }, + gamm: { + v1beta1: { + __export: true, + _183: true, + _184: true, + _185: true, + _186: true, + _187: true, + }, + }, + incentives: { __export: true, - _204: true - } - }, - superfluid: { - __export: true, - _205: true, - _206: true, - _207: true, - _208: true, - _209: true - }, - txfees: { - v1beta1: { + _188: true, + _189: true, + _190: true, + _191: true, + _192: true, + }, + lockup: { __export: true, - _210: true, - _211: true, - _212: true, - _213: true - } - } - } - } - } -]); \ No newline at end of file + _193: true, + _194: true, + _195: true, + _196: true, + }, + mint: { + v1beta1: { + __export: true, + _197: true, + _198: true, + _199: true, + }, + }, + poolincentives: { + v1beta1: { + __export: true, + _200: true, + _201: true, + _202: true, + _203: true, + }, + }, + store: { + v1beta1: { + __export: true, + _204: true, + }, + }, + superfluid: { + __export: true, + _205: true, + _206: true, + _207: true, + _208: true, + _209: true, + }, + txfees: { + v1beta1: { + __export: true, + _210: true, + _211: true, + _212: true, + _213: true, + }, + }, + }, + }, + }, + ] +); diff --git a/packages/ts-codegen/__tests__/cleanse.test.ts b/packages/ts-codegen/__tests__/cleanse.test.ts index f112b774..f3980c2f 100644 --- a/packages/ts-codegen/__tests__/cleanse.test.ts +++ b/packages/ts-codegen/__tests__/cleanse.test.ts @@ -6,7 +6,6 @@ import { readSchemas } from '../src/utils'; const FIXTURE_DIR = __dirname + '/../../../__fixtures__'; const OUTPUT_DIR = __dirname + '/../../../__output__'; - it('sg721', async () => { const out = OUTPUT_DIR + '/sg721'; const schemaDir = FIXTURE_DIR + '/sg721/'; @@ -17,7 +16,6 @@ it('sg721', async () => { mkdirp(out); writeFileSync(out + '/orig.json', JSON.stringify(orig, null, 2)); writeFileSync(out + '/clean.json', JSON.stringify(clean, null, 2)); - }); it('daodao/cw-code-id-registry', async () => { @@ -43,4 +41,3 @@ it('issues/103', async () => { writeFileSync(out + '/orig.json', JSON.stringify(orig, null, 2)); writeFileSync(out + '/clean.json', JSON.stringify(clean, null, 2)); }); - diff --git a/packages/ts-codegen/__tests__/ts-codegen.issue-98.test.ts b/packages/ts-codegen/__tests__/ts-codegen.issue-98.test.ts index 5fdddbd6..b35839b1 100644 --- a/packages/ts-codegen/__tests__/ts-codegen.issue-98.test.ts +++ b/packages/ts-codegen/__tests__/ts-codegen.issue-98.test.ts @@ -7,21 +7,19 @@ it('issue-98', async () => { const schemaDir = FIXTURE_DIR + '/issues/98/'; const builder = new TSBuilder({ - contracts: [ - schemaDir - ], + contracts: [schemaDir], outPath, options: { types: { - enabled: true + enabled: true, }, client: { - enabled: true + enabled: true, }, reactQuery: { - enabled: true - } - } + enabled: true, + }, + }, }); await builder.build(); -}); \ No newline at end of file +}); diff --git a/packages/ts-codegen/__tests__/ts-codegen.issue-long-exe-msg-name.test.ts b/packages/ts-codegen/__tests__/ts-codegen.issue-long-exe-msg-name.test.ts index a4270283..7b2af568 100644 --- a/packages/ts-codegen/__tests__/ts-codegen.issue-long-exe-msg-name.test.ts +++ b/packages/ts-codegen/__tests__/ts-codegen.issue-long-exe-msg-name.test.ts @@ -12,18 +12,18 @@ it('issue-long-exe-msg-name', async () => { outPath, options: { messageComposer: { - enabled: true + enabled: true, }, types: { - enabled: true + enabled: true, }, client: { - enabled: true + enabled: true, }, reactQuery: { - enabled: true - } - } + enabled: true, + }, + }, }); await builder.build(); }); diff --git a/packages/ts-codegen/__tests__/ts-codegen.test.ts b/packages/ts-codegen/__tests__/ts-codegen.test.ts index c2f6f05c..656a6b30 100644 --- a/packages/ts-codegen/__tests__/ts-codegen.test.ts +++ b/packages/ts-codegen/__tests__/ts-codegen.test.ts @@ -1,7 +1,15 @@ import { BuilderContext } from '@cosmwasm/ts-codegen-ast'; import { readSchemas } from '../src/utils'; -import { generateClient, generateContractHooks,generateMessageBuilder, generateMessageComposer, generateReactQuery, generateRecoil, generateTypes } from '../test-utils'; +import { + generateClient, + generateContractHooks, + generateMessageBuilder, + generateMessageComposer, + generateReactQuery, + generateRecoil, + generateTypes, +} from '../test-utils'; const FIXTURE_DIR = __dirname + '/../../../__fixtures__'; const OUTPUT_DIR = __dirname + '/../../../__output__'; @@ -10,16 +18,18 @@ it('optionalClient', async () => { const outopt = OUTPUT_DIR + '/vectis/factory-optional-client'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, + }); + await generateReactQuery('Factory', contractInfo, outopt, { + optionalClient: true, }); - await generateReactQuery('Factory', contractInfo, outopt, { optionalClient: true }); }); it('v4Query', async () => { const outopt = OUTPUT_DIR + '/vectis/factory-v4-query'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateReactQuery('Factory', contractInfo, outopt, { version: 'v4' }); }); @@ -28,38 +38,47 @@ it('queryKeys', async () => { const outopt = OUTPUT_DIR + '/vectis/factory-query-keys'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, + }); + await generateReactQuery('Factory', contractInfo, outopt, { + queryKeys: true, }); - await generateReactQuery('Factory', contractInfo, outopt, { queryKeys: true }); }); it('queryFactory', async () => { const outopt = OUTPUT_DIR + '/vectis/factory-query-keys'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, + }); + await generateReactQuery('Factory', contractInfo, outopt, { + queryKeys: true, + queryFactory: true, }); - await generateReactQuery('Factory', contractInfo, outopt, { queryKeys: true, queryFactory: true }); }); - - it('queryKeysOptionalClient', async () => { const outopt = OUTPUT_DIR + '/vectis/factory-query-keys-optional-client'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, + }); + await generateReactQuery('Factory', contractInfo, outopt, { + queryKeys: true, + optionalClient: true, }); - await generateReactQuery('Factory', contractInfo, outopt, { queryKeys: true, optionalClient: true }); }); it('useMutations', async () => { const outopt = OUTPUT_DIR + '/vectis/factory-w-mutations'; const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, + }); + await generateReactQuery('Factory', contractInfo, outopt, { + version: 'v4', + mutations: true, }); - await generateReactQuery('Factory', contractInfo, outopt, { version: 'v4', mutations: true }); }); it('vectis/factory', async () => { @@ -67,7 +86,7 @@ it('vectis/factory', async () => { const schemaDir = FIXTURE_DIR + '/vectis/factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('Factory', contractInfo, out); await generateClient('Factory', contractInfo, out); @@ -81,7 +100,7 @@ it('vectis/govec', async () => { const schemaDir = FIXTURE_DIR + '/vectis/govec/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('Govec', contractInfo, out); await generateClient('Govec', contractInfo, out); @@ -95,7 +114,7 @@ it('vectis/proxy', async () => { const schemaDir = FIXTURE_DIR + '/vectis/proxy/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('Proxy', contractInfo, out); await generateClient('Proxy', contractInfo, out); @@ -108,7 +127,7 @@ it('minter', async () => { const out = OUTPUT_DIR + '/minter'; const schemaDir = FIXTURE_DIR + '/minter/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('Minter', contractInfo, out); await generateClient('Minter', contractInfo, out); @@ -122,7 +141,7 @@ it('sg721', async () => { const schemaDir = FIXTURE_DIR + '/sg721/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); const builderContext = new BuilderContext(); @@ -141,7 +160,7 @@ it('cw-named-groups', async () => { const schemaDir = FIXTURE_DIR + '/daodao/cw-named-groups/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('CwNamedGroups', contractInfo, out); await generateClient('CwNamedGroups', contractInfo, out); @@ -155,7 +174,7 @@ it('cw-proposal-single', async () => { const schemaDir = FIXTURE_DIR + '/daodao/cw-proposal-single/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('CwProposalSingle', contractInfo, out); await generateClient('CwProposalSingle', contractInfo, out); @@ -169,7 +188,7 @@ it('cw-admin-factory', async () => { const schemaDir = FIXTURE_DIR + '/daodao/cw-admin-factory/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('CwAdminFactory', contractInfo, out); await generateClient('CwAdminFactory', contractInfo, out); @@ -183,7 +202,7 @@ it('cw-code-id-registry', async () => { const schemaDir = FIXTURE_DIR + '/daodao/cw-code-id-registry/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('CwCodeIdRegistry', contractInfo, out); await generateClient('CwCodeIdRegistry', contractInfo, out); @@ -197,7 +216,7 @@ it('idl-version/hackatom', async () => { const schemaDir = FIXTURE_DIR + '/idl-version/hackatom/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('HackAtom', contractInfo, out); await generateClient('HackAtom', contractInfo, out); @@ -211,7 +230,7 @@ it('idl-version/cyberpunk', async () => { const schemaDir = FIXTURE_DIR + '/idl-version/cyberpunk/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('CyberPunk', contractInfo, out); @@ -226,7 +245,7 @@ it('idl-version/cw4-group', async () => { const schemaDir = FIXTURE_DIR + '/idl-version/cw4-group/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('Cw4Group', contractInfo, out); @@ -241,7 +260,7 @@ it('idl-version/cw3-fixed-multisig', async () => { const schemaDir = FIXTURE_DIR + '/idl-version/cw3-fixed-multisig/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('Cw3FixedMultiSig', contractInfo, out); @@ -256,7 +275,7 @@ it('idl-version/accounts-nft', async () => { const schemaDir = FIXTURE_DIR + '/idl-version/accounts-nft/'; const contractInfo = await readSchemas({ - schemaDir + schemaDir, }); await generateTypes('AccountsNft', contractInfo, out); diff --git a/packages/ts-codegen/package.json b/packages/ts-codegen/package.json index e80ec591..45827a61 100644 --- a/packages/ts-codegen/package.json +++ b/packages/ts-codegen/package.json @@ -23,6 +23,7 @@ "cmds": "ts-node ./scripts/cmds.ts", "build": "npm run clean; tsc; tsc -p tsconfig.esm.json; npm run copy", "lint": "eslint . --fix", + "format": "prettier --write --log-level warn \"./**/*.ts\"", "test": "jest", "test:watch": "jest --watch", "dev": "ts-node src/ts-codegen", diff --git a/packages/ts-codegen/scripts/cmds.ts b/packages/ts-codegen/scripts/cmds.ts index baf611fa..28dc2316 100644 --- a/packages/ts-codegen/scripts/cmds.ts +++ b/packages/ts-codegen/scripts/cmds.ts @@ -8,7 +8,7 @@ interface PathObj { name: string; param: string; safe: string; - path: string + path: string; } const paths: PathObj[] = glob(`${srcDir}/**.[j|t]s`).map((file: string) => { const [, name] = file.match(/\/(.*)\.[j|t]s$/); @@ -19,7 +19,7 @@ const paths: PathObj[] = glob(`${srcDir}/**.[j|t]s`).map((file: string) => { path: file .replace(srcDir, './commands') .replace(/\.js$/, '') - .replace(/\.ts$/, '') + .replace(/\.ts$/, ''), }; }); @@ -33,10 +33,10 @@ const out = ` ${imports} const Commands: any = {}; ${paths - .map((a) => { - return `Commands['${a.param}'] = _${a.safe};`; - }) - .join('\n')} + .map((a) => { + return `Commands['${a.param}'] = _${a.safe};`; + }) + .join('\n')} export { Commands }; diff --git a/packages/ts-codegen/src/builder/builder.ts b/packages/ts-codegen/src/builder/builder.ts index 32aacbc6..d8c7597d 100644 --- a/packages/ts-codegen/src/builder/builder.ts +++ b/packages/ts-codegen/src/builder/builder.ts @@ -1,6 +1,11 @@ import generate from '@babel/generator'; import * as t from '@babel/types'; -import { BuilderContext,ContractInfo, defaultOptions, RenderOptions } from '@cosmwasm/ts-codegen-ast'; +import { + BuilderContext, + ContractInfo, + defaultOptions, + RenderOptions, +} from '@cosmwasm/ts-codegen-ast'; import { pascal } from 'case'; import deepmerge from 'deepmerge'; import { writeFileSync } from 'fs'; @@ -27,49 +32,56 @@ const defaultOpts: TSBuilderOptions = { bundle: { enabled: true, scope: 'contracts', - bundleFile: 'bundle.ts' + bundleFile: 'bundle.ts', }, - useShorthandCtor: true + useShorthandCtor: true, }; export interface TSBuilderInput { - contracts: Array; - outPath: string; - options?: TSBuilderOptions; - plugins?: IBuilderPlugin[]; -}; + contracts: Array; + outPath: string; + options?: TSBuilderOptions; + plugins?: IBuilderPlugin[]; +} export interface BundleOptions { - enabled?: boolean; - scope?: string; - bundleFile?: string; - bundlePath?: string; -}; + enabled?: boolean; + scope?: string; + bundleFile?: string; + bundlePath?: string; +} export type TSBuilderOptions = { - bundle?: BundleOptions; - /** - * Enable using shorthand constructor. - * Default: true - */ - useShorthandCtor?: boolean; + bundle?: BundleOptions; + /** + * Enable using shorthand constructor. + * Default: true + */ + useShorthandCtor?: boolean; } & RenderOptions; -export type BuilderFileType = 'type' | 'client' | 'recoil' | 'react-query' | 'message-composer' | 'message-builder' | 'plugin'; +export type BuilderFileType = + | 'type' + | 'client' + | 'recoil' + | 'react-query' + | 'message-composer' + | 'message-builder' + | 'plugin'; export interface BuilderFile { - type: BuilderFileType; - pluginType?: string; - contract: string; - //filename only: Factory.client.ts - localname: string; - //full path: contracts/Factory.client.ts - filename: string; -}; + type: BuilderFileType; + pluginType?: string; + contract: string; + //filename only: Factory.client.ts + localname: string; + //full path: contracts/Factory.client.ts + filename: string; +} export interface ContractFile { - name: string; - dir: string; + name: string; + dir: string; } function getContract(contractOpt: ContractFile | string): ContractFile { @@ -78,12 +90,12 @@ function getContract(contractOpt: ContractFile | string): ContractFile { const contractName = pascal(name); return { name: contractName, - dir: contractOpt + dir: contractOpt, }; } return { name: pascal(contractOpt.name), - dir: contractOpt.dir + dir: contractOpt.dir, }; } @@ -113,10 +125,7 @@ export class TSBuilder { this.contracts = contracts; this.outPath = outPath; this.options = deepmerge( - deepmerge( - defaultOptions, - defaultOpts - ), + deepmerge(defaultOptions, defaultOpts), options ?? {} ); @@ -126,7 +135,7 @@ export class TSBuilder { this.plugins.push(...plugins); } - this.plugins.forEach(plugin => plugin.setBuilder(this)); + this.plugins.forEach((plugin) => plugin.setBuilder(this)); } async build() { @@ -140,7 +149,7 @@ export class TSBuilder { const contract = getContract(contractOpt); //resolve contract schema. const contractInfo = await readSchemas({ - schemaDir: contract.dir + schemaDir: contract.dir, }); //lifecycle and plugins. @@ -154,9 +163,7 @@ export class TSBuilder { contractInfo?: ContractInfo ) { const plugins = lifecycle - ? this.plugins.filter((p) => - p.lifecycle === lifecycle - ) + ? this.plugins.filter((p) => p.lifecycle === lifecycle) : this.plugins; for (const plugin of plugins) { @@ -174,12 +181,15 @@ export class TSBuilder { private async after() { await this.render('after'); - const helpers = createHelpers({ - outPath: this.outPath, - contracts: this.contracts, - options: this.options, - plugins: this.plugins, - }, this.builderContext); + const helpers = createHelpers( + { + outPath: this.outPath, + contracts: this.contracts, + options: this.options, + plugins: this.plugins, + }, + this.builderContext + ); if (helpers && helpers.length) { this.files.push(...helpers); @@ -199,9 +209,13 @@ export class TSBuilder { bundleFile ); const bundleVariables = {}; - const importPaths: (t.ImportDeclaration | t.ImportDefaultSpecifier | t.ImportNamespaceSpecifier)[] = []; + const importPaths: ( + | t.ImportDeclaration + | t.ImportDefaultSpecifier + | t.ImportNamespaceSpecifier + )[] = []; - allFiles.forEach(file => { + allFiles.forEach((file) => { createFileBundle( `${this.options.bundle.scope}.${file.contract}`, file.filename, @@ -209,19 +223,17 @@ export class TSBuilder { importPaths, bundleVariables ); - }); const ast = recursiveModuleBundle(bundleVariables); - const nodes = [ - ...importPaths, - ...ast - ]; + const nodes = [...importPaths, ...ast]; // @ts-ignore - let code = generate(t.program( - // @ts-ignore - nodes - )).code; + let code = generate( + t.program( + // @ts-ignore + nodes + ) + ).code; if (this.options?.bundle?.bundlePath) { mkdirp(this.options?.bundle?.bundlePath); @@ -232,6 +244,5 @@ export class TSBuilder { if (code.trim() === '') code = 'export {};'; writeFileSync(bundlePath, header + code); - } } diff --git a/packages/ts-codegen/src/builder/index.ts b/packages/ts-codegen/src/builder/index.ts index 813cccec..ecea700b 100644 --- a/packages/ts-codegen/src/builder/index.ts +++ b/packages/ts-codegen/src/builder/index.ts @@ -1 +1 @@ -export * from './builder'; \ No newline at end of file +export * from './builder'; diff --git a/packages/ts-codegen/src/bundler/bundler.ts b/packages/ts-codegen/src/bundler/bundler.ts index 20efb89c..91358be6 100644 --- a/packages/ts-codegen/src/bundler/bundler.ts +++ b/packages/ts-codegen/src/bundler/bundler.ts @@ -1,16 +1,16 @@ import * as t from '@babel/types'; import nested from 'nested-obj'; -import { - dirname, extname, - relative} from 'path'; +import { dirname, extname, relative } from 'path'; export interface BundleData { - __export?: boolean; - [key: string]: boolean | BundleData; + __export?: boolean; + [key: string]: boolean | BundleData; } -export const recursiveModuleBundle = (obj: BundleData): t.ExportNamedDeclaration[] => { - return Object.keys(obj).map(key => { +export const recursiveModuleBundle = ( + obj: BundleData +): t.ExportNamedDeclaration[] => { + return Object.keys(obj).map((key) => { const value = obj[key]; if (typeof value === 'object' && value && value.__export) { // e.g. abci @@ -18,21 +18,21 @@ export const recursiveModuleBundle = (obj: BundleData): t.ExportNamedDeclaration // 2. splat ALL _0, parms into abci // 3. export that variable - const nmspc = t.variableDeclaration('const', - [t.variableDeclarator( + const nmspc = t.variableDeclaration('const', [ + t.variableDeclarator( t.identifier(key), t.objectExpression( Object.keys(obj[key]) - .filter(a => a !== '__export') - .filter(a => a.startsWith('_')) - .map(a => t.spreadElement(t.identifier(a))) + .filter((a) => a !== '__export') + .filter((a) => a.startsWith('_')) + .map((a) => t.spreadElement(t.identifier(a))) ) - )] - ); + ), + ]); const others = Object.keys(obj[key]) - .filter(a => a !== '__export') - .filter(a => !a.startsWith('_')); + .filter((a) => a !== '__export') + .filter((a) => !a.startsWith('_')); if (others.length) { throw new Error('namespace and package not supported, yet.'); } @@ -54,19 +54,22 @@ export const recursiveModuleBundle = (obj: BundleData): t.ExportNamedDeclaration }); }; -export const importNamespace = (ident: string, path: string) => t.importDeclaration( - [ - t.importNamespaceSpecifier(t.identifier(ident)) - ], - t.stringLiteral(path.replace(extname(path), '')) -); +export const importNamespace = (ident: string, path: string) => + t.importDeclaration( + [t.importNamespaceSpecifier(t.identifier(ident))], + t.stringLiteral(path.replace(extname(path), '')) + ); let counter = 0; export const createFileBundle = ( pkg: string, filename: string, bundleFile: string, - importPaths: (t.ImportDeclaration | t.ImportDefaultSpecifier | t.ImportNamespaceSpecifier)[], + importPaths: ( + | t.ImportDeclaration + | t.ImportDefaultSpecifier + | t.ImportNamespaceSpecifier + )[], bundleVariables: BundleData ) => { let rel = relative(dirname(bundleFile), filename); @@ -75,4 +78,4 @@ export const createFileBundle = ( importPaths.push(importNamespace(variable, rel)); nested.set(bundleVariables, pkg + '.__export', true); nested.set(bundleVariables, pkg + '.' + variable, true); -}; \ No newline at end of file +}; diff --git a/packages/ts-codegen/src/bundler/index.ts b/packages/ts-codegen/src/bundler/index.ts index 6061e08b..86bd4845 100644 --- a/packages/ts-codegen/src/bundler/index.ts +++ b/packages/ts-codegen/src/bundler/index.ts @@ -1 +1 @@ -export * from './bundler'; \ No newline at end of file +export * from './bundler'; diff --git a/packages/ts-codegen/src/cli.ts b/packages/ts-codegen/src/cli.ts index 71be8ec0..61e2d0a1 100644 --- a/packages/ts-codegen/src/cli.ts +++ b/packages/ts-codegen/src/cli.ts @@ -9,8 +9,8 @@ const question = [ type: 'fuzzy', name: 'cmd', message: 'what do you want to do?', - choices: Object.keys(commands) - } + choices: Object.keys(commands), + }, ]; export const cli = async (argv: MinimistArgs) => { diff --git a/packages/ts-codegen/src/cmds.ts b/packages/ts-codegen/src/cmds.ts index 9630ad7f..3e3c332a 100644 --- a/packages/ts-codegen/src/cmds.ts +++ b/packages/ts-codegen/src/cmds.ts @@ -1,4 +1,3 @@ - import _create_boilerplate from './commands/create-boilerplate'; import _generate from './commands/generate'; import _install from './commands/install'; @@ -7,6 +6,4 @@ Commands['create-boilerplate'] = _create_boilerplate; Commands['generate'] = _generate; Commands['install'] = _install; -export { Commands }; - - \ No newline at end of file +export { Commands }; diff --git a/packages/ts-codegen/src/commands/create-boilerplate.ts b/packages/ts-codegen/src/commands/create-boilerplate.ts index c9a23b21..5cf68e94 100644 --- a/packages/ts-codegen/src/commands/create-boilerplate.ts +++ b/packages/ts-codegen/src/commands/create-boilerplate.ts @@ -15,13 +15,16 @@ export default async (argv: MinimistArgs) => { return shell.exit(1); } - const { name } = await prompt([ - { - type: 'string', - name: 'name', - message: 'Enter your new module name', - } - ], argv); + const { name } = await prompt( + [ + { + type: 'string', + name: 'name', + message: 'Enter your new module name', + }, + ], + argv + ); shell.exec(`git clone ${repo} ${name}`); shell.cd(name); @@ -89,14 +92,14 @@ export default async (argv: MinimistArgs) => { let content = fs.readFileSync(templateFile).toString(); if ( path.basename(templateFile) === 'LICENSE' && - license.__LICENSE__ === 'closed' + license.__LICENSE__ === 'closed' ) { content = `Copyright (c) 2023 __USERFULLNAME__ <__USEREMAIL__> - All Rights Reserved Unauthorized copying via any medium is strictly prohibited Proprietary and confidential`; } - Object.keys(results).forEach(key => { + Object.keys(results).forEach((key) => { if (/^__/.test(key)) { content = content.replace(new RegExp(key, 'g'), results[key]); } @@ -139,4 +142,4 @@ Proprietary and confidential`; ✨ Great work! `); -}; \ No newline at end of file +}; diff --git a/packages/ts-codegen/src/commands/generate.ts b/packages/ts-codegen/src/commands/generate.ts index 519824d2..fe1b1695 100644 --- a/packages/ts-codegen/src/commands/generate.ts +++ b/packages/ts-codegen/src/commands/generate.ts @@ -12,38 +12,33 @@ export default async (argv: MinimistArgs) => { type: 'path', name: 'schema', message: 'which directory contains the the Rust contracts?', - default: './schema' + default: './schema', }, { _: true, type: 'path', name: 'out', message: 'where is the output directory?', - default: './ts' + default: './ts', }, { _: true, type: 'string', name: 'name', - message: 'contract name?' + message: 'contract name?', }, { type: 'checkbox', name: 'plugin', message: 'which plugins?', - choices: [ - 'client', - 'recoil', - 'react-query', - 'message-composer' - ] + choices: ['client', 'recoil', 'react-query', 'message-composer'], }, { type: 'confirm', name: 'bundle', message: 'enable bundle?', - default: true - } + default: true, + }, ]; if (argv.typesOnly) { @@ -62,23 +57,23 @@ export default async (argv: MinimistArgs) => { type: 'confirm', name: 'optionalClient', message: 'optionalClient?', - default: false + default: false, }, { type: 'list', name: 'version', message: 'which react-query version?', default: 'v4', - choices: ['v3', 'v4'] + choices: ['v3', 'v4'], }, { type: 'confirm', name: 'queryKeys', message: 'queryKeys?', - default: false + default: false, }, ]); - }; + } const { optionalClient, version, queryKeys } = await prompt(questions2, argv); const questions3 = []; if (version === 'v4') { @@ -88,11 +83,10 @@ export default async (argv: MinimistArgs) => { type: 'confirm', name: 'mutations', message: 'Generate useMutation hooks?', - default: false - } - + default: false, + }, ]); - }; + } const { mutations } = await prompt(questions3, argv); const queryFactoryQuestions = []; @@ -103,10 +97,10 @@ export default async (argv: MinimistArgs) => { type: 'confirm', name: 'queryFactory', message: 'queryFactory? ', - default: false - } + default: false, + }, ]); - }; + } const { queryFactory } = await prompt(queryFactoryQuestions, argv); ///////// END REACT QUERY @@ -118,28 +112,28 @@ export default async (argv: MinimistArgs) => { type: 'string', name: 'bundleFile', message: 'bundleFile?', - default: 'index.ts' + default: 'index.ts', }, { type: 'string', name: 'bundleScope', message: 'bundleScope?', - default: 'contracts' - } + default: 'contracts', + }, ]); - }; + } const { bundleFile, bundleScope } = await prompt(questions4, argv); ///////// END BUNDLE const options: TSBuilderOptions = { types: { - enabled: true + enabled: true, }, client: { enabled: - plugin.includes('client') || - plugin.includes('recoil') || - plugin.includes('react-query') + plugin.includes('client') || + plugin.includes('recoil') || + plugin.includes('react-query'), }, reactQuery: { enabled: plugin.includes('react-query'), @@ -147,33 +141,32 @@ export default async (argv: MinimistArgs) => { queryKeys, version, mutations, - queryFactory + queryFactory, }, recoil: { enabled: plugin.includes('recoil'), }, messageComposer: { - enabled: plugin.includes('message-composer') + enabled: plugin.includes('message-composer'), }, messageBuilder: { - - enabled: plugin.includes('message-builder') + enabled: plugin.includes('message-builder'), }, bundle: { enabled: bundle, scope: bundleScope, - bundleFile - } + bundleFile, + }, }; await codegen({ contracts: [ { name, - dir: schema - } + dir: schema, + }, ], outPath: out, - options + options, }); }; diff --git a/packages/ts-codegen/src/commands/install.ts b/packages/ts-codegen/src/commands/install.ts index f14db991..5f32a181 100644 --- a/packages/ts-codegen/src/commands/install.ts +++ b/packages/ts-codegen/src/commands/install.ts @@ -4,7 +4,7 @@ import { sync as glob } from 'glob'; import { sync as mkdirp } from 'mkdirp'; import { tmpdir } from 'os'; import { parse } from 'parse-package-name'; -import { basename, dirname, extname,join, resolve } from 'path'; +import { basename, dirname, extname, join, resolve } from 'path'; import { sync as rimraf } from 'rimraf'; import { exec } from 'shelljs'; @@ -13,17 +13,18 @@ import { prompt } from '../utils/prompt'; const TMPDIR = tmpdir(); const rnd = () => Math.random().toString(36).substring(2, 15) + - Math.random().toString(36).substring(2, 15); + Math.random().toString(36).substring(2, 15); const getPackages = (names: string[]) => { - return names.map(pkg => { - const { name, version } = parse(pkg); - return `${name}@${version}`; - }).join(' '); + return names + .map((pkg) => { + const { name, version } = parse(pkg); + return `${name}@${version}`; + }) + .join(' '); }; export default async (argv: MinimistArgs) => { - // don't prompt if we got this... if (argv._.length) { argv.pkg = argv._; @@ -39,43 +40,49 @@ export default async (argv: MinimistArgs) => { } // what are we installing? - let { pkg } = await prompt([ - { - type: 'checkbox', - name: 'pkg', - message: - 'which chain contracts do you want to support?', - choices: [ - 'stargaze-base-factory', - 'stargaze-base-minter', - 'stargaze-sg721-base', - 'stargaze-sg721-metdata-onchain', - 'stargaze-sg721-nt', - 'stargaze-splits', - 'stargaze-vending-factory', - 'stargaze-vending-minter', - 'stargaze-whitelist', - 'wasmswap' - ].map(name => { - return { - name, - value: `@cosmjson/${name}` - }; - }) - } - ], argv); + let { pkg } = await prompt( + [ + { + type: 'checkbox', + name: 'pkg', + message: 'which chain contracts do you want to support?', + choices: [ + 'stargaze-base-factory', + 'stargaze-base-minter', + 'stargaze-sg721-base', + 'stargaze-sg721-metdata-onchain', + 'stargaze-sg721-nt', + 'stargaze-splits', + 'stargaze-vending-factory', + 'stargaze-vending-minter', + 'stargaze-whitelist', + 'wasmswap', + ].map((name) => { + return { + name, + value: `@cosmjson/${name}`, + }; + }), + }, + ], + argv + ); // install if (!Array.isArray(pkg)) pkg = [pkg]; const tmp = join(TMPDIR, rnd()); mkdirp(tmp); process.chdir(tmp); - exec(`npm install ${getPackages(pkg)} --production --prefix ./smart-contracts`); + exec( + `npm install ${getPackages(pkg)} --production --prefix ./smart-contracts` + ); // protos const pkgs = glob('./smart-contracts/**/package.json'); const cmds = pkgs - .filter((f) => { return f !== './smart-contracts/package.json'; }) + .filter((f) => { + return f !== './smart-contracts/package.json'; + }) .map((f) => resolve(join(tmp, f))) .map((conf) => { const extDir = dirname(conf); @@ -83,17 +90,20 @@ export default async (argv: MinimistArgs) => { const dst = basename(dir); const files = glob(`${extDir}/**/*`, { nodir: true }); - files.forEach(f => { - if (extname(f) === '.json' - || f === 'package.json' - || /license/i.test(f) - || /readme/i.test(f)) return; + files.forEach((f) => { + if ( + extname(f) === '.json' || + f === 'package.json' || + /license/i.test(f) || + /readme/i.test(f) + ) + return; rimraf(f); }); return [extDir, resolve(join(cur, 'contracts', dst)), dir]; }); - // move protos + // move protos for (const [src, dst, pkg] of cmds) { rimraf(dst); console.log(`installing ${pkg}...`); @@ -102,17 +112,24 @@ export default async (argv: MinimistArgs) => { } // package - const packageInfo = JSON.parse(readFileSync('./smart-contracts/package.json', 'utf-8')); + const packageInfo = JSON.parse( + readFileSync('./smart-contracts/package.json', 'utf-8') + ); const deps = packageInfo.dependencies ?? {}; thisPackage.devDependencies = thisPackage.devDependencies ?? {}; thisPackage.devDependencies = { ...thisPackage.devDependencies, - ...deps + ...deps, }; - thisPackage.devDependencies = Object.fromEntries(Object.entries(thisPackage.devDependencies).sort()); + thisPackage.devDependencies = Object.fromEntries( + Object.entries(thisPackage.devDependencies).sort() + ); - writeFileSync(join(cur, 'package.json'), JSON.stringify(thisPackage, null, 2)); + writeFileSync( + join(cur, 'package.json'), + JSON.stringify(thisPackage, null, 2) + ); // cleanup rimraf(tmp); diff --git a/packages/ts-codegen/src/file.ts b/packages/ts-codegen/src/file.ts index 8a39f093..559d1860 100644 --- a/packages/ts-codegen/src/file.ts +++ b/packages/ts-codegen/src/file.ts @@ -11,8 +11,8 @@ const question = [ _: true, type: 'string', name: 'file', - message: 'file' - } + message: 'file', + }, ]; (async () => { diff --git a/packages/ts-codegen/src/helpers/create-helpers.ts b/packages/ts-codegen/src/helpers/create-helpers.ts index ccb92224..1e7e9fe8 100644 --- a/packages/ts-codegen/src/helpers/create-helpers.ts +++ b/packages/ts-codegen/src/helpers/create-helpers.ts @@ -1,6 +1,6 @@ import { BuilderContext } from '@cosmwasm/ts-codegen-ast'; import { sync as mkdirp } from 'mkdirp'; -import { basename, dirname, extname,join } from 'path'; +import { basename, dirname, extname, join } from 'path'; import { BuilderFile, TSBuilderInput } from '../builder'; import { diff --git a/packages/ts-codegen/src/helpers/index.ts b/packages/ts-codegen/src/helpers/index.ts index ab8e74c9..de7142d8 100644 --- a/packages/ts-codegen/src/helpers/index.ts +++ b/packages/ts-codegen/src/helpers/index.ts @@ -1,3 +1,3 @@ export * from './contractContextBase'; export * from './contractContextBaseShortHandCtor'; -export * from './contractsContextTSX'; \ No newline at end of file +export * from './contractsContextTSX'; diff --git a/packages/ts-codegen/src/index.ts b/packages/ts-codegen/src/index.ts index 79330fcf..e6c6db59 100644 --- a/packages/ts-codegen/src/index.ts +++ b/packages/ts-codegen/src/index.ts @@ -8,4 +8,4 @@ export * from './utils'; export default async (input: TSBuilderInput) => { const builder = new TSBuilder(input); await builder.build(); -}; \ No newline at end of file +}; diff --git a/packages/ts-codegen/src/plugins/client.ts b/packages/ts-codegen/src/plugins/client.ts index 9394b30e..3c1d178b 100644 --- a/packages/ts-codegen/src/plugins/client.ts +++ b/packages/ts-codegen/src/plugins/client.ts @@ -107,7 +107,7 @@ export class ClientPlugin extends BuilderPluginBase { } } - if (typeHash.hasOwnProperty('Coin')) { + if (Object.prototype.hasOwnProperty.call(typeHash, 'Coin')) { // @ts-ignore delete context.utils.Coin; } diff --git a/packages/ts-codegen/src/plugins/index.ts b/packages/ts-codegen/src/plugins/index.ts index 815f6f4d..99efdc4c 100644 --- a/packages/ts-codegen/src/plugins/index.ts +++ b/packages/ts-codegen/src/plugins/index.ts @@ -4,4 +4,4 @@ export * from './message-composer'; export * from './plugin-base'; export * from './react-query'; export * from './recoil'; -export * from './types'; \ No newline at end of file +export * from './types'; diff --git a/packages/ts-codegen/src/plugins/message-builder.ts b/packages/ts-codegen/src/plugins/message-builder.ts index 1a7df80f..74e0a4a0 100644 --- a/packages/ts-codegen/src/plugins/message-builder.ts +++ b/packages/ts-codegen/src/plugins/message-builder.ts @@ -4,12 +4,12 @@ import { getMessageProperties, RenderContext, RenderContextBase, - RenderOptions + RenderOptions, } from '@cosmwasm/ts-codegen-ast'; import { pascal } from 'case'; import { BuilderFileType } from '../builder'; -import { findAndParseTypes, findExecuteMsg,findQueryMsg } from '../utils'; +import { findAndParseTypes, findExecuteMsg, findQueryMsg } from '../utils'; import { BuilderPluginBase } from './plugin-base'; export class MessageBuilderPlugin extends BuilderPluginBase { @@ -70,7 +70,7 @@ export class MessageBuilderPlugin extends BuilderPluginBase { } } - if (typeHash.hasOwnProperty('Coin')) { + if (Object.prototype.hasOwnProperty.call(typeHash, 'Coin')) { // @ts-ignore delete context.utils.Coin; } @@ -79,8 +79,8 @@ export class MessageBuilderPlugin extends BuilderPluginBase { { type: 'message-builder', localname, - body - } + body, + }, ]; } } diff --git a/packages/ts-codegen/src/plugins/message-composer.ts b/packages/ts-codegen/src/plugins/message-composer.ts index e5dfe09b..880448da 100644 --- a/packages/ts-codegen/src/plugins/message-composer.ts +++ b/packages/ts-codegen/src/plugins/message-composer.ts @@ -71,7 +71,7 @@ export class MessageComposerPlugin extends BuilderPluginBase { } } - if (typeHash.hasOwnProperty('Coin')) { + if (Object.prototype.hasOwnProperty.call(typeHash, 'Coin')) { // @ts-ignore delete context.utils.Coin; } diff --git a/packages/ts-codegen/src/plugins/plugin-base.ts b/packages/ts-codegen/src/plugins/plugin-base.ts index 9c800f7c..34582bcb 100644 --- a/packages/ts-codegen/src/plugins/plugin-base.ts +++ b/packages/ts-codegen/src/plugins/plugin-base.ts @@ -1,16 +1,17 @@ import generate from '@babel/generator'; import * as t from '@babel/types'; -import { ContractInfo, defaultOptions,IContext, UtilMapping } from '@cosmwasm/ts-codegen-ast'; +import { + ContractInfo, + defaultOptions, + IContext, + UtilMapping, +} from '@cosmwasm/ts-codegen-ast'; import deepmerge from 'deepmerge'; import { writeFileSync } from 'fs'; import { sync as mkdirp } from 'mkdirp'; import { join } from 'path'; -import { - BuilderFile, - BuilderFileType, - TSBuilder, -} from '../builder'; +import { BuilderFile, BuilderFileType, TSBuilder } from '../builder'; import { header } from '../utils/header'; /** @@ -43,7 +44,7 @@ export interface IBuilderPlugin { render( outPath: string, name?: string, - contractInfo?: ContractInfo, + contractInfo?: ContractInfo ): Promise; } @@ -51,7 +52,8 @@ export interface IBuilderPlugin { * BuilderPluginBase enable ts-codegen users implement their own plugins by only implement a few functions. */ export abstract class BuilderPluginBase -implements IBuilderPlugin { + implements IBuilderPlugin +{ builder?: TSBuilder; options: TOpt; utils: UtilMapping; @@ -75,7 +77,7 @@ implements IBuilderPlugin { async render( outPath: string, name?: string, - contractInfo?: ContractInfo, + contractInfo?: ContractInfo ): Promise { if (!this.options) { this.options = this.getDefaultOptions(this.options); @@ -98,7 +100,8 @@ implements IBuilderPlugin { return results.map((result) => { const imports = context.getImports(this.utils, result.localname); // @ts-ignore - const code = header + generate(t.program([...imports, ...result.body])).code; + const code = + header + generate(t.program([...imports, ...result.body])).code; mkdirp(outPath); const filename = join(outPath, result.localname); diff --git a/packages/ts-codegen/src/plugins/provider-bundle.ts b/packages/ts-codegen/src/plugins/provider-bundle.ts index 51348114..00f5c127 100644 --- a/packages/ts-codegen/src/plugins/provider-bundle.ts +++ b/packages/ts-codegen/src/plugins/provider-bundle.ts @@ -1,5 +1,9 @@ import * as w from '@cosmwasm/ts-codegen-ast'; -import { ContractInfo, RenderContext,RenderContextBase } from '@cosmwasm/ts-codegen-ast'; +import { + ContractInfo, + RenderContext, + RenderContextBase, +} from '@cosmwasm/ts-codegen-ast'; import { pascal } from 'case'; import { BuilderFileType, TSBuilderOptions } from '../builder'; @@ -70,12 +74,7 @@ export class ContractsProviderBundlePlugin extends BuilderPluginBase { context, queryMsg: QueryMsg, contractName: name, - QueryClient + QueryClient, }) ); } @@ -94,12 +95,12 @@ export class ReactQueryPlugin extends BuilderPluginBase { context, execMsg: ExecuteMsg, contractName: name, - ExecuteClient + ExecuteClient, }) ); } - if (typeHash.hasOwnProperty('Coin')) { + if (Object.prototype.hasOwnProperty.call(typeHash, 'Coin')) { // @ts-ignore delete context.utils.Coin; } @@ -108,8 +109,8 @@ export class ReactQueryPlugin extends BuilderPluginBase { { type: 'react-query', localname, - body - } + body, + }, ]; } } diff --git a/packages/ts-codegen/src/plugins/recoil.ts b/packages/ts-codegen/src/plugins/recoil.ts index 11c68ca2..be26b25b 100644 --- a/packages/ts-codegen/src/plugins/recoil.ts +++ b/packages/ts-codegen/src/plugins/recoil.ts @@ -4,7 +4,7 @@ import { RenderContext, RenderContextBase, RenderOptions, - UtilMapping + UtilMapping, } from '@cosmwasm/ts-codegen-ast'; import { pascal } from 'case'; @@ -68,12 +68,17 @@ export class RecoilPlugin extends BuilderPluginBase { body.push(w.createRecoilQueryClientType()); body.push(w.createRecoilQueryClient(context, name, QueryClient)); - const selectors = w.createRecoilSelectors(context, name, QueryClient, QueryMsg); + const selectors = w.createRecoilSelectors( + context, + name, + QueryClient, + QueryMsg + ); body.push(...selectors); } - if (typeHash.hasOwnProperty('Coin')) { + if (Object.prototype.hasOwnProperty.call(typeHash, 'Coin')) { // @ts-ignore delete context.utils.Coin; } @@ -82,8 +87,8 @@ export class RecoilPlugin extends BuilderPluginBase { { type: 'recoil', localname, - body - } + body, + }, ]; } } diff --git a/packages/ts-codegen/src/plugins/types.ts b/packages/ts-codegen/src/plugins/types.ts index ce7458a7..da8c9a17 100644 --- a/packages/ts-codegen/src/plugins/types.ts +++ b/packages/ts-codegen/src/plugins/types.ts @@ -3,7 +3,7 @@ import { ContractInfo, RenderContext, RenderContextBase, - RenderOptions + RenderOptions, } from '@cosmwasm/ts-codegen-ast'; import { pascal } from 'case'; @@ -68,8 +68,8 @@ export class TypesPlugin extends BuilderPluginBase { { type: 'type', localname, - body - } + body, + }, ]; } } diff --git a/packages/ts-codegen/src/utils/clean.ts b/packages/ts-codegen/src/utils/clean.ts index 81217f74..6eabd9d2 100644 --- a/packages/ts-codegen/src/utils/clean.ts +++ b/packages/ts-codegen/src/utils/clean.ts @@ -23,17 +23,17 @@ export const clean = (obj: any): any => { if (obj instanceof Object || typeof obj === 'object') { copy = {}; for (let attr in obj) { - if (obj.hasOwnProperty(attr)) { + if (Object.prototype.hasOwnProperty.call(obj, attr)) { switch (attr) { - case 'leadingComments': - case 'trailingComments': - case 'loc': - case 'start': - case 'end': - break; - default: - // @ts-ignore - copy[attr] = clean(obj[attr]); + case 'leadingComments': + case 'trailingComments': + case 'loc': + case 'start': + case 'end': + break; + default: + // @ts-ignore + copy[attr] = clean(obj[attr]); } } else { // @ts-ignore @@ -44,4 +44,4 @@ export const clean = (obj: any): any => { } throw new Error("Unable to copy obj! Its type isn't supported."); -}; \ No newline at end of file +}; diff --git a/packages/ts-codegen/src/utils/cleanse.ts b/packages/ts-codegen/src/utils/cleanse.ts index 34fff970..9ae2bd75 100644 --- a/packages/ts-codegen/src/utils/cleanse.ts +++ b/packages/ts-codegen/src/utils/cleanse.ts @@ -55,8 +55,7 @@ export const cleanse = (obj: any): any => { } for (let attr in obj) { - if (obj.hasOwnProperty(attr)) { - + if (Object.prototype.hasOwnProperty.call(obj, attr)) { if (/_for_/.test(attr)) { // @ts-ignore copy[cleanFor(attr)] = cleanse(obj[attr]); @@ -65,24 +64,21 @@ export const cleanse = (obj: any): any => { copy[cleanNullable(attr)] = cleanse(obj[attr]); } else { switch (attr) { - case 'title': - case '$ref': - if (typeof obj[attr] === 'string') { - // @ts-ignore - copy[attr] = cleanse( - cleanNullable(cleanFor(obj[attr])) - ); - } else { + case 'title': + case '$ref': + if (typeof obj[attr] === 'string') { + // @ts-ignore + copy[attr] = cleanse(cleanNullable(cleanFor(obj[attr]))); + } else { + // @ts-ignore + copy[attr] = cleanse(obj[attr]); + } + break; + default: // @ts-ignore copy[attr] = cleanse(obj[attr]); - } - break; - default: - // @ts-ignore - copy[attr] = cleanse(obj[attr]); } } - } else { // @ts-ignore copy[attr] = cleanse(obj[attr]); @@ -92,4 +88,4 @@ export const cleanse = (obj: any): any => { } throw new Error("Unable to copy obj! Its type isn't supported."); -}; \ No newline at end of file +}; diff --git a/packages/ts-codegen/src/utils/index.ts b/packages/ts-codegen/src/utils/index.ts index 27156028..e84d06c3 100644 --- a/packages/ts-codegen/src/utils/index.ts +++ b/packages/ts-codegen/src/utils/index.ts @@ -1 +1 @@ -export * from './schemas'; \ No newline at end of file +export * from './schemas'; diff --git a/packages/ts-codegen/src/utils/package.ts b/packages/ts-codegen/src/utils/package.ts index 23150c02..7ea2ef99 100644 --- a/packages/ts-codegen/src/utils/package.ts +++ b/packages/ts-codegen/src/utils/package.ts @@ -1,7 +1,7 @@ -import { existsSync,readFileSync } from 'fs'; -import { dirname,join } from 'path'; +import { existsSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; -// need to search due to the dist/ folder and src/, etc. +// need to search due to the dist/ folder and src/, etc. function findPackageJson(currentDir: string) { const filePath = join(currentDir, 'package.json'); @@ -30,4 +30,4 @@ export function readAndParsePackageJson() { const str = readFileSync(pkgPath, 'utf8'); const pkg = JSON.parse(str); return pkg; -} \ No newline at end of file +} diff --git a/packages/ts-codegen/src/utils/parse.ts b/packages/ts-codegen/src/utils/parse.ts index bf42cf27..03ab4bea 100644 --- a/packages/ts-codegen/src/utils/parse.ts +++ b/packages/ts-codegen/src/utils/parse.ts @@ -2,29 +2,24 @@ import { parse, ParserPlugin } from '@babel/parser'; import babelTraverse from '@babel/traverse'; export const parser = (codes: string[]) => { - const hash: Record = {}; - codes.forEach(code => { - - const plugins: ParserPlugin[] = [ - 'typescript', - ]; + codes.forEach((code) => { + const plugins: ParserPlugin[] = ['typescript']; const ast = parse(code, { sourceType: 'module', - plugins + plugins, }); const visitor = visitorFn({ addType(key: string, node: any) { hash[key] = node; - } + }, }); babelTraverse(ast as any, visitor); }); return hash; - }; const visitorFn = (parser: any) => ({ @@ -40,6 +35,5 @@ const visitorFn = (parser: any) => ({ }, TSInterfaceDeclaration(path: any) { parser.addType(path.node.id.name, path.parentPath.node); - } + }, }); - diff --git a/packages/ts-codegen/src/utils/prompt.ts b/packages/ts-codegen/src/utils/prompt.ts index 8e002be9..8bb262fe 100644 --- a/packages/ts-codegen/src/utils/prompt.ts +++ b/packages/ts-codegen/src/utils/prompt.ts @@ -44,7 +44,7 @@ const transform = (questions) => { return { ...q, type: 'autocomplete', - source: getFuzzySearch(choices) + source: getFuzzySearch(choices), }; } else if (q.type === 'fuzzy:objects') { const choices = q.choices; @@ -52,7 +52,7 @@ const transform = (questions) => { return { ...q, type: 'autocomplete', - source: getFuzzySearchNames(choices) + source: getFuzzySearchNames(choices), }; } else { return q; diff --git a/packages/ts-codegen/src/utils/schemas.ts b/packages/ts-codegen/src/utils/schemas.ts index 0ca000fb..25e55e03 100644 --- a/packages/ts-codegen/src/utils/schemas.ts +++ b/packages/ts-codegen/src/utils/schemas.ts @@ -1,5 +1,10 @@ import { ContractInfo } from '@cosmwasm/ts-codegen-ast'; -import { ExecuteMsg, IDLObject, JSONSchema, QueryMsg } from '@cosmwasm/ts-codegen-types'; +import { + ExecuteMsg, + IDLObject, + JSONSchema, + QueryMsg, +} from '@cosmwasm/ts-codegen-types'; import { compile } from '@pyramation/json-schema-to-typescript'; import { readFileSync } from 'fs'; import { sync as glob } from 'glob'; @@ -9,32 +14,41 @@ import { parser } from './parse'; interface ReadSchemaOpts { schemaDir: string; clean?: boolean; -}; +} export const readSchemas = async ({ - schemaDir, clean = true + schemaDir, + clean = true, }: ReadSchemaOpts): Promise => { - const fn = clean ? cleanse : (schema: JSONSchema[] | Partial) => schema; - const files = glob(schemaDir + '/**/*.json') - .filter(file => !file.match(/\/raw\//)); + const fn = clean + ? cleanse + : (schema: JSONSchema[] | Partial) => schema; + const files = glob(schemaDir + '/**/*.json').filter( + (file) => !file.match(/\/raw\//) + ); - const schemas: JSONSchema[] = files - .map(file => JSON.parse(readFileSync(file, 'utf-8'))); + const schemas: JSONSchema[] = files.map((file) => + JSON.parse(readFileSync(file, 'utf-8')) + ); if (schemas.length > 1) { // legacy // TODO add console.warn here return { - schemas: fn(schemas) + schemas: fn(schemas), }; } if (schemas.length === 0) { - throw new Error('Error [too few files]: requires one schema file per contract'); + throw new Error( + 'Error [too few files]: requires one schema file per contract' + ); } if (schemas.length !== 1) { - throw new Error('Error [too many files]: CosmWasm v1.1 schemas supports one file'); + throw new Error( + 'Error [too many files]: CosmWasm v1.1 schemas supports one file' + ); } const idlObject: Partial = schemas[0] as Partial; @@ -47,13 +61,13 @@ export const readSchemas = async ({ execute, query, migrate, - sudo + sudo, } = idlObject; if (typeof idl_version !== 'string') { // legacy return { - schemas: fn(schemas) + schemas: fn(schemas), }; } @@ -63,25 +77,25 @@ export const readSchemas = async ({ execute, query, migrate, - sudo + sudo, }; return { schemas: [ ...Object.values(fn(idl)).filter(Boolean), - ...Object.values(fn({ ...responses })).filter(Boolean) + ...Object.values(fn({ ...responses })).filter(Boolean), ], responses, - idlObject + idlObject, }; }; export const findQueryMsg = (schemas: JSONSchema[]): QueryMsg => { - const queryMsg = schemas.find(schema => schema.title === 'QueryMsg'); + const queryMsg = schemas.find((schema) => schema.title === 'QueryMsg'); return queryMsg as QueryMsg; }; export const findExecuteMsg = (schemas: JSONSchema[]): ExecuteMsg => { - const executeMsg = schemas.find(schema => + const executeMsg = schemas.find((schema) => schema.title.startsWith('ExecuteMsg') ); return executeMsg as ExecuteMsg; diff --git a/packages/ts-codegen/src/utils/unused.ts b/packages/ts-codegen/src/utils/unused.ts index a6bd99ec..9072c127 100644 --- a/packages/ts-codegen/src/utils/unused.ts +++ b/packages/ts-codegen/src/utils/unused.ts @@ -14,13 +14,11 @@ export const unused = { const source = binding.path.parentPath.get('source'); const importName = source.node.value; - if ( - !t.isStringLiteral(source) - ) - continue; + if (!t.isStringLiteral(source)) continue; - const key = `${importName}(${source.node.loc && - source.node.loc.start.line})`; + const key = `${importName}(${ + source.node.loc && source.node.loc.start.line + })`; if (!UnRefBindings.has(key)) { UnRefBindings.set(key, binding); @@ -47,6 +45,6 @@ export const unused = { binding.path.parentPath.remove(); } }); - } - } -}; \ No newline at end of file + }, + }, +}; diff --git a/packages/types/.eslintignore b/packages/types/.eslintignore new file mode 120000 index 00000000..86039baf --- /dev/null +++ b/packages/types/.eslintignore @@ -0,0 +1 @@ +../../.eslintignore \ No newline at end of file diff --git a/packages/types/package.json b/packages/types/package.json index b7d2b108..c410102c 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -18,6 +18,7 @@ "prepare": "npm run build", "build": "npm run clean; tsc; tsc -p tsconfig.esm.json; npm run copy", "lint": "eslint . --fix", + "format": "prettier --write --log-level warn \"./**/*.ts\"", "test": "jest --passWithNoTests", "test:watch": "jest --watch --passWithNoTests" }, diff --git a/packages/types/src/idl.ts b/packages/types/src/idl.ts index deaa9c87..6f503ed2 100644 --- a/packages/types/src/idl.ts +++ b/packages/types/src/idl.ts @@ -13,4 +13,4 @@ export interface IDLObject { migrate: JSONSchema; sudo: JSONSchema; responses: KeyedSchema; -} \ No newline at end of file +} diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index f367b7f6..2ba12f5a 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -1,13 +1,18 @@ -export declare type fieldType = 'Long' | 'Coin' | 'Duration' | 'Height' | string; +export declare type fieldType = + | 'Long' + | 'Coin' + | 'Duration' + | 'Height' + | string; export interface Field { name: string; type: fieldType; node: any; -}; +} export interface Interface { name: string; - fields: Field[] -}; + fields: Field[]; +} export interface QueryMsg { $schema: string; @@ -40,16 +45,27 @@ export interface JSONSchema { additionalItems?: JSONSchema; required?: string[]; title?: string; - type?: string | string[] + type?: string | string[]; } - // this is actually what items ends up being most of the time: export type JSONSchemaType = | { type: 'integer'; format?: 'int32' | 'int64' } | { type: 'number'; format?: 'float' | 'double' } - | { type: 'string'; format?: 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri' } + | { + type: 'string'; + format?: 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri'; + } | { type: 'boolean' } - | { type: 'object'; properties?: { [key: string]: JSONSchemaType }; required?: string[] } - | { type: 'array'; items?: JSONSchemaType | JSONSchemaType[]; maxItems?: number; minItems?: number } + | { + type: 'object'; + properties?: { [key: string]: JSONSchemaType }; + required?: string[]; + } + | { + type: 'array'; + items?: JSONSchemaType | JSONSchemaType[]; + maxItems?: number; + minItems?: number; + } | JSONSchemaType[]; // For tuple definitions diff --git a/yarn.lock b/yarn.lock index 755dfb0e..d0d93d97 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3030,10 +3030,10 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== -eslint-config-prettier@^9.1.0: - version "9.1.0" - resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz#31af3d94578645966c082fcb71a5846d3c94867f" - integrity sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw== +eslint-config-prettier@^10.1.5: + version "10.1.5" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-10.1.5.tgz#00c18d7225043b6fbce6a665697377998d453782" + integrity sha512-zc1UmCpNltmVY34vuLRV61r1K27sWuX39E+uyUnY8xS2Bex88VV9cugG+UZbRSRGtGyFboj+D8JODyme1plMpw== eslint-plugin-simple-import-sort@^12.1.0: version "12.1.0" @@ -6200,10 +6200,10 @@ prettier@^2.6.2: resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.8.tgz#e8c5d7e98a4305ffe3de2e1fc4aca1a71c28b1da" integrity sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q== -prettier@^3.0.2: - version "3.2.5" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.2.5.tgz#e52bc3090586e824964a8813b09aba6233b28368" - integrity sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A== +prettier@^3.6.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.6.0.tgz#18ec98d62cb0757a5d4eab40253ff3e6d0fc8dea" + integrity sha512-ujSB9uXHJKzM/2GBuE0hBOUgC77CN3Bnpqa+g80bkv3T3A93wL/xlzDATHhnhkzifz/UE2SNOvmbTz5hSkDlHw== pretty-format@29.4.3: version "29.4.3" @@ -6853,7 +6853,16 @@ string-length@^4.0.1: char-regex "^1.0.2" strip-ansi "^6.0.0" -"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -6898,7 +6907,7 @@ string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6, strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -6926,6 +6935,13 @@ strip-ansi@^5.1.0: dependencies: ansi-regex "^4.1.0" +strip-ansi@^6, strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + strip-ansi@^7.0.1: version "7.1.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" @@ -7513,7 +7529,7 @@ wordwrap@^1.0.0: resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" integrity sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q== -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== @@ -7531,6 +7547,15 @@ wrap-ansi@^6.0.1: string-width "^4.1.0" strip-ansi "^6.0.0" +wrap-ansi@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrap-ansi@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214"