diff --git a/.eslintrc.js b/.eslintrc.cjs similarity index 100% rename from .eslintrc.js rename to .eslintrc.cjs diff --git a/.github/workflows/npm.yml b/.github/workflows/npm.yml index 3290cdc9..3c5605cc 100644 --- a/.github/workflows/npm.yml +++ b/.github/workflows/npm.yml @@ -53,8 +53,8 @@ jobs: - name: Install Dependencies run: npm install - - name: Generate Version - run: ./scripts/generate-version.sh + - name: Generate Package JSON + run: ./scripts/generate-package-json.sh - name: Pack Testing run: ./scripts/npm-pack-testing.sh @@ -80,8 +80,8 @@ jobs: - name: Install Dependencies run: npm install - - name: Generate Version - run: ./scripts/generate-version.sh + - name: Generate Package JSON + run: ./scripts/generate-package-json.sh - name: Set Publish Config run: ./scripts/package-publish-config-tag.sh diff --git a/README.md b/README.md index 95443889..96da5f00 100644 --- a/README.md +++ b/README.md @@ -57,9 +57,9 @@ WECHATY_PUPPET_SERVICE_TOKEN=${WECHATY_PUPPET_SERVCIE_TOKEN} node bot.js ## History -### master +### master v0.31 -Refactoring +1. ES Modules supported. ### v0.30 (Aug 25, 2021) diff --git a/examples/ding-dong-bot.ts b/examples/ding-dong-bot.ts index 701279f6..80d7d34e 100644 --- a/examples/ding-dong-bot.ts +++ b/examples/ding-dong-bot.ts @@ -9,7 +9,7 @@ import { FileBox, } from 'wechaty-puppet' -import { PuppetService } from '../src/mod' +import { PuppetService } from '../src/mod.js' /** * diff --git a/package.json b/package.json index 2920a682..5d3da0dc 100644 --- a/package.json +++ b/package.json @@ -1,26 +1,34 @@ { "name": "wechaty-puppet-service", - "version": "0.31.3", + "version": "0.31.5", "description": "Puppet Service for Wechaty", - "main": "dist/src/mod.js", - "typings": "dist/src/mod.d.ts", - "directories": { - "test": "tests" + "type": "module", + "exports": { + ".": { + "import": "./dist/esm/src/mod.js", + "require": "./dist/cjs/src/mod.js" + } }, + "typings": "./dist/esm/src/mod.d.ts", "engines": { - "wechaty": ">=0.60", - "wechaty-puppet": ">=0.41" + "wechaty": ">=0.69", + "wechaty-puppet": ">=0.43" + }, + "directories": { + "test": "tests" }, "scripts": { "clean": "shx rm -fr dist/*", - "dist": "npm run clean && tsc", + "dist": "npm-run-all clean build fixup", + "build": "tsc && tsc -p tsconfig.cjs.json", + "fixup": "shx echo '{\"type\": \"commonjs\"}' > dist/cjs/package.json", "lint": "npm run lint:es && npm run lint:ts && npm run lint:md", "lint:md": "markdownlint README.md", - "lint:ts": "tsc --noEmit", + "lint:ts": "tsc --isolatedModules --noEmit", "start": "ts-node examples/ding-dong-bot.ts", "test": "npm run lint && npm run test:unit", "test:pack": "bash -x scripts/npm-pack-testing.sh", - "test:unit": "tap --node-arg=--require=ts-node/register \"src/**/*.spec.ts\" \"src/*.spec.ts\" \"tests/*.spec.ts\" \"tests/**/*.spec.ts\"", + "test:unit": "tap --node-arg=--loader=ts-node/esm --node-arg=--no-warnings \"src/**/*.spec.ts\" \"src/*.spec.ts\" \"tests/*.spec.ts\" \"tests/**/*.spec.ts\"", "lint:es": "eslint --ignore-pattern fixtures/ \"src/**/*.ts\" \"tests/**/*.ts\"" }, "repository": { @@ -43,7 +51,7 @@ }, "homepage": "https://github.com/wechaty/wechaty-puppet-service#readme", "devDependencies": { - "@chatie/eslint-config": "^0.12.4", + "@chatie/eslint-config": "^0.13.5", "@chatie/git-scripts": "^0.6.2", "@chatie/semver": "^0.4.7", "@chatie/tsconfig": "^0.17.2", @@ -51,26 +59,32 @@ "@types/lru-cache": "^5.1.1", "@types/semver": "^6.2.2", "@types/ws": "^7.4.4", + "npm-run-all": "^4.1.5", "pkg-jq": "^0.2.11", "shx": "^0.3.3", "tstest": "^0.5.16", - "typescript": "4.3", - "wechaty": "^0.61", - "wechaty-puppet": "^0.41.7", - "wechaty-puppet-mock": "^0.29.6" + "typescript": "^4.4", + "wechaty": "^0.69.12", + "wechaty-puppet": "^0.43.9", + "wechaty-puppet-mock": "^0.31.3" }, "dependencies": { "flash-store": "^1.1.1", "rxjs": "^7.1.0", "semver": "^6.3.0", "stronger-typed-streams": "^0.2.0", - "wechaty-grpc": "^0.25.1", + "wechaty-grpc": "^0.27.6", "wechaty-token": "^0.5.8" }, "publishConfig": { "access": "public", "tag": "next" }, + "files": [ + "bin/", + "dist/", + "src/" + ], "tap": { "check-coverage": false }, diff --git a/scripts/generate-package-json.sh b/scripts/generate-package-json.sh new file mode 100755 index 00000000..cc0c45b9 --- /dev/null +++ b/scripts/generate-package-json.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -e + +SRC_PACKAGE_JSON_TS_FILE='src/package-json.ts' + +[ -f ${SRC_PACKAGE_JSON_TS_FILE} ] || { + echo ${SRC_PACKAGE_JSON_TS_FILE}" not found" + exit 1 +} + +cat <<_SRC_ > ${SRC_PACKAGE_JSON_TS_FILE} +/** + * This file was auto generated from scripts/generate-version.sh + */ +import { PackageJson } from 'type-fest' +export const packageJson: PackageJson = $(cat package.json) as any +_SRC_ diff --git a/scripts/generate-version.sh b/scripts/generate-version.sh deleted file mode 100755 index e8ef7f99..00000000 --- a/scripts/generate-version.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash -set -e - -SRC_VERSION_TS_FILE='src/version.ts' - -[ -f ${SRC_VERSION_TS_FILE} ] || { - echo ${SRC_VERSION_TS_FILE}" not found" - exit 1 -} - -VERSION=$(npx pkg-jq -r .version) - -cat <<_SRC_ > ${SRC_VERSION_TS_FILE} -/** - * This file was auto generated from scripts/generate-version.sh - */ -export const VERSION: string = '${VERSION}' -_SRC_ diff --git a/scripts/npm-pack-testing.sh b/scripts/npm-pack-testing.sh index d9bdd3fe..2eb956df 100755 --- a/scripts/npm-pack-testing.sh +++ b/scripts/npm-pack-testing.sh @@ -3,7 +3,7 @@ set -e VERSION=$(npx pkg-jq -r .version) -if npx --package @chatie/semver semver-is-prod $VERSION; then +if npx --package @chatie/semver semver-is-prod "$VERSION"; then NPM_TAG=latest else NPM_TAG=next @@ -18,18 +18,52 @@ mv ./*-*.*.*.tgz "$TMPDIR" cp tests/fixtures/smoke-testing.ts "$TMPDIR" cd $TMPDIR + npm init -y -npm install *-*.*.*.tgz \ - @chatie/tsconfig \ - brolog \ +npm install --production *-*.*.*.tgz \ + @types/node \ + @chatie/tsconfig@$NPM_TAG \ "wechaty-puppet@$NPM_TAG" \ + "wechaty@$NPM_TAG" \ +# +# CommonJS +# ./node_modules/.bin/tsc \ + --target es6 \ + --module CommonJS \ + \ + --moduleResolution node \ --esModuleInterop \ --lib esnext \ + --noEmitOnError \ + --noImplicitAny \ --skipLibCheck \ + smoke-testing.ts + +echo +echo "CommonJS: pack testing..." +node smoke-testing.js + +# +# ES Modules +# + +# https://stackoverflow.com/a/59203952/1123955 +echo "`jq '.type="module"' package.json`" > package.json + +./node_modules/.bin/tsc \ + --target es2020 \ + --module es2020 \ + \ + --moduleResolution node \ + --esModuleInterop \ + --lib esnext \ --noEmitOnError \ --noImplicitAny \ + --skipLibCheck \ smoke-testing.ts +echo +echo "ES Module: pack testing..." node smoke-testing.js diff --git a/src/auth/auth-impl-token.spec.ts b/src/auth/auth-impl-token.spec.ts index ec94306f..3da18b42 100755 --- a/src/auth/auth-impl-token.spec.ts +++ b/src/auth/auth-impl-token.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test, @@ -9,9 +9,9 @@ import { GrpcStatus, Metadata, UntypedServiceImplementation, -} from './grpc-js' +} from './grpc-js.js' -import { authImplToken } from './auth-impl-token' +import { authImplToken } from './auth-impl-token.js' test('authImplToken()', async t => { const sandbox = sinon.createSandbox() diff --git a/src/auth/auth-impl-token.ts b/src/auth/auth-impl-token.ts index e1f64cc9..48dc5540 100644 --- a/src/auth/auth-impl-token.ts +++ b/src/auth/auth-impl-token.ts @@ -1,4 +1,4 @@ -import { log } from '../config' +import { log } from 'wechaty-puppet' import { StatusBuilder, @@ -8,9 +8,9 @@ import { ServerUnaryCall, GrpcStatus, UntypedServiceImplementation, -} from './grpc-js' +} from './grpc-js.js' -import { monkeyPatchMetadataFromHttp2Headers } from './mokey-patch-header-authorization' +import { monkeyPatchMetadataFromHttp2Headers } from './mokey-patch-header-authorization.js' /** * Huan(202108): Monkey patch to support diff --git a/src/auth/ca.spec.ts b/src/auth/ca.spec.ts index 136aa888..ea562509 100755 --- a/src/auth/ca.spec.ts +++ b/src/auth/ca.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test, @@ -6,7 +6,7 @@ import { import https from 'https' -import * as envVar from './env-vars' +import * as envVar from './env-vars.js' import { AddressInfo } from 'ws' import { @@ -14,7 +14,7 @@ import { TLS_INSECURE_SERVER_CERT_COMMON_NAME, TLS_INSECURE_SERVER_CERT, TLS_INSECURE_SERVER_KEY, -} from './ca' +} from './ca.js' test('CA smoke testing', async t => { diff --git a/src/auth/call-cred.spec.ts b/src/auth/call-cred.spec.ts index 3ddb346c..98f3dae9 100755 --- a/src/auth/call-cred.spec.ts +++ b/src/auth/call-cred.spec.ts @@ -1,11 +1,11 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test, sinon, } from 'tstest' -import { metaGeneratorToken } from './call-cred' +import { metaGeneratorToken } from './call-cred.js' test('metaGeneratorToken()', async t => { const TOKEN = 'UUIDv4' diff --git a/src/auth/call-cred.ts b/src/auth/call-cred.ts index 40c9df91..91b39213 100644 --- a/src/auth/call-cred.ts +++ b/src/auth/call-cred.ts @@ -2,7 +2,7 @@ import { credentials, CallMetadataGenerator, Metadata, -} from './grpc-js' +} from './grpc-js.js' /** * With server authentication SSL/TLS and a custom header with token diff --git a/src/auth/grpc-js.ts b/src/auth/grpc-js.ts index a8ede85c..51c4fe3a 100644 --- a/src/auth/grpc-js.ts +++ b/src/auth/grpc-js.ts @@ -12,16 +12,18 @@ import { import { CallMetadataGenerator, } from '@grpc/grpc-js/build/src/call-credentials' -import { Status as GrpcStatus } from '@grpc/grpc-js/build/src/constants' +import { Status as GrpcStatus } from '@grpc/grpc-js/build/src/constants.js' +export type { + UntypedServiceImplementation, + UntypedHandleCall, + sendUnaryData, + ServerUnaryCall, + CallMetadataGenerator, +} export { credentials, - CallMetadataGenerator, GrpcStatus, Metadata, - sendUnaryData, - ServerUnaryCall, StatusBuilder, - UntypedHandleCall, - UntypedServiceImplementation, } diff --git a/src/auth/mod.ts b/src/auth/mod.ts index c5aa72bc..62105ead 100644 --- a/src/auth/mod.ts +++ b/src/auth/mod.ts @@ -1,6 +1,6 @@ -import { authImplToken } from './auth-impl-token' -import { monkeyPatchMetadataFromHttp2Headers } from './mokey-patch-header-authorization' -import { callCredToken } from './call-cred' +import { authImplToken } from './auth-impl-token.js' +import { monkeyPatchMetadataFromHttp2Headers } from './mokey-patch-header-authorization.js' +import { callCredToken } from './call-cred.js' export { authImplToken, diff --git a/src/auth/mokey-patch-header-authorization.ts b/src/auth/mokey-patch-header-authorization.ts index eb00ac1f..3aea1051 100644 --- a/src/auth/mokey-patch-header-authorization.ts +++ b/src/auth/mokey-patch-header-authorization.ts @@ -1,10 +1,10 @@ import http2 from 'http2' -import { log } from '../config' +import { log } from 'wechaty-puppet' import { Metadata, -} from './grpc-js' +} from './grpc-js.js' /** * Huan(202108): This is for compatible with old clients (version v0.26 or before) diff --git a/src/auth/monkey-patch-header-authorization.spec.ts b/src/auth/monkey-patch-header-authorization.spec.ts index 0bee1a23..992118df 100755 --- a/src/auth/monkey-patch-header-authorization.spec.ts +++ b/src/auth/monkey-patch-header-authorization.spec.ts @@ -1,13 +1,13 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' import http2 from 'http2' import { Metadata, -} from './grpc-js' +} from './grpc-js.js' -import { monkeyPatchMetadataFromHttp2Headers } from './mokey-patch-header-authorization' +import { monkeyPatchMetadataFromHttp2Headers } from './mokey-patch-header-authorization.js' test('monkeyPatchMetadataFromHttp2Headers', async t => { const AUTHORITY = '__authority__' diff --git a/src/client/grpc-client.spec.ts b/src/client/grpc-client.spec.ts index 1a86e31e..87295e16 100755 --- a/src/client/grpc-client.spec.ts +++ b/src/client/grpc-client.spec.ts @@ -1,8 +1,8 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' -import { GrpcClient } from './grpc-client' +import { GrpcClient } from './grpc-client.js' /** * Huan(202108): diff --git a/src/client/grpc-client.ts b/src/client/grpc-client.ts index fa9f421c..7f6eef07 100644 --- a/src/client/grpc-client.ts +++ b/src/client/grpc-client.ts @@ -2,13 +2,10 @@ import util from 'util' import EventEmitter from 'events' import crypto from 'crypto' +import { log } from 'wechaty-puppet' import { grpc, - PuppetClient, - EventRequest, - StartRequest, - StopRequest, - EventResponse, + puppet, } from 'wechaty-grpc' import { WechatyToken, @@ -17,18 +14,17 @@ import { import { GRPC_OPTIONS, - log, envVars, -} from '../config' +} from '../config.js' -import { callCredToken } from '../auth/mod' -import { GrpcStatus } from '../auth/grpc-js' +import { callCredToken } from '../auth/mod.js' +import { GrpcStatus } from '../auth/grpc-js.js' import { TLS_CA_CERT, TLS_INSECURE_SERVER_CERT_COMMON_NAME, -} from '../auth/ca' +} from '../auth/ca.js' -import { PuppetServiceOptions } from './puppet-service' +import { PuppetServiceOptions } from './puppet-service.js' /** * Huan(202108): register `wechaty` schema for gRPC service discovery @@ -40,8 +36,8 @@ WechatyResolver.setup() class GrpcClient extends EventEmitter { - client? : PuppetClient - eventStream? : grpc.ClientReadableStream + client? : puppet.PuppetClient + eventStream? : grpc.ClientReadableStream /** * gRPC settings @@ -135,7 +131,7 @@ class GrpcClient extends EventEmitter { await util.promisify( this.client!.start .bind(this.client) - )(new StartRequest()) + )(new puppet.StartRequest()) } async stop (): Promise { @@ -151,7 +147,7 @@ class GrpcClient extends EventEmitter { */ await util.promisify( this.client!.stop.bind(this.client) - )(new StopRequest()) + )(new puppet.StopRequest()) /** * 3. Destroy grpc client */ @@ -202,7 +198,7 @@ class GrpcClient extends EventEmitter { this.client = undefined } - this.client = new PuppetClient( + this.client = new puppet.PuppetClient( this.endpoint, credential, clientOptions, @@ -226,7 +222,7 @@ class GrpcClient extends EventEmitter { try { client.close() } catch (e) { - log.error('GrpcClient', 'destroy() grpcClient.close() rejection: %s\n%s', e && e.message, e.stack) + log.error('GrpcClient', 'destroy() grpcClient.close() rejection: %s\n%s', e && (e as Error).message, (e as Error).stack) } } @@ -242,13 +238,13 @@ class GrpcClient extends EventEmitter { this.eventStream = undefined } - const eventStream = this.client.event(new EventRequest()) + const eventStream = this.client.event(new puppet.EventRequest()) /** * Store the event data from the stream when we test connection, * and re-emit the event data when we have finished testing the connection */ - let peekedData: undefined | EventResponse + let peekedData: undefined | puppet.EventResponse /** * Huan(202108): future must be placed before other listenser registration @@ -267,7 +263,7 @@ class GrpcClient extends EventEmitter { * So we also need a timeout for compatible with those providers * in case of they are not following this special protocol. */ - .once('data', (resp: EventResponse) => { + .once('data', (resp: puppet.EventResponse) => { peekedData = resp resolve() }) diff --git a/src/client/payload-store.spec.ts b/src/client/payload-store.spec.ts index 30ccc66e..8e300c77 100755 --- a/src/client/payload-store.spec.ts +++ b/src/client/payload-store.spec.ts @@ -1,8 +1,8 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' -import { PayloadStore } from './payload-store' +import { PayloadStore } from './payload-store.js' test('PayloadStore perfect restart', async t => { const token = Math.random().toString(36) diff --git a/src/client/payload-store.ts b/src/client/payload-store.ts index 1a8d7aaa..bf7ae3af 100644 --- a/src/client/payload-store.ts +++ b/src/client/payload-store.ts @@ -15,7 +15,7 @@ import { import { FlashStore } from 'flash-store' // import LRU from 'lru-cache' -import { VERSION } from '../version' +import { VERSION } from '../config.js' interface PayloadStoreOptions { token: string diff --git a/src/client/puppet-service.spec.ts b/src/client/puppet-service.spec.ts index e5280e13..03d553a3 100755 --- a/src/client/puppet-service.spec.ts +++ b/src/client/puppet-service.spec.ts @@ -1,8 +1,8 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' -import { PuppetService } from './puppet-service' +import { PuppetService } from './puppet-service.js' test('version()', async t => { const puppet = new PuppetService({ @@ -25,6 +25,6 @@ test.skip('PuppetService restart without problem', async t => { } t.pass('PuppetService() start/restart successed.') } catch (e) { - t.fail(e) + t.fail(e as any) } }) diff --git a/src/client/puppet-service.ts b/src/client/puppet-service.ts index 72641e8d..3caca47a 100644 --- a/src/client/puppet-service.ts +++ b/src/client/puppet-service.ts @@ -3,10 +3,11 @@ import util from 'util' import { FileBoxType } from 'file-box' import { - ContactPayload, - + log, FileBox, + ContactPayload, + FriendshipAddOptions, FriendshipPayload, @@ -40,85 +41,30 @@ import { } from 'wechaty-puppet' import { - EventResponse, - ContactAliasRequest, - LogoutRequest, - ContactListRequest, - ContactSelfQRCodeRequest, - ContactAvatarRequest, - ContactPayloadRequest, - ContactSelfNameRequest, - ContactSelfSignatureRequest, - MessageMiniProgramRequest, - MessageContactRequest, - MessageForwardRequest, - MessageSendMiniProgramRequest, - MessageRecallRequest, - MessagePayloadRequest, - MessageSendTextRequest, - MessageSendContactRequest, - MessageSendUrlRequest, - MessageUrlRequest, - RoomPayloadRequest, - RoomListRequest, - RoomDelRequest, - RoomAvatarRequest, - RoomAddRequest, - RoomTopicRequest, - RoomCreateRequest, - RoomQuitRequest, - RoomQRCodeRequest, - RoomAnnounceRequest, - RoomInvitationAcceptRequest, - RoomInvitationPayloadRequest, - FriendshipSearchPhoneRequest, - FriendshipSearchWeixinRequest, - FriendshipPayloadRequest, - FriendshipAddRequest, - FriendshipAcceptRequest, - RoomMemberListRequest, - RoomMemberPayloadRequest, - TagContactAddRequest, - TagContactRemoveRequest, - TagContactDeleteRequest, - TagContactListRequest, - StringValue, - DingRequest, - - EventType, - DirtyPayloadRequest, - ContactCorporationRemarkRequest, - ContactDescriptionRequest, - ContactPhoneRequest, - MessageFileStreamRequest, - MessageImageStreamRequest, - MessageSendFileStreamResponse, - MessageSendFileStreamRequest, - MessageSendFileRequest, + puppet as pbPuppet, } from 'wechaty-grpc' import { Subscription } from 'rxjs' import { envVars, - log, VERSION, -} from '../config' +} from '../config.js' import { EventTypeRev, -} from '../event-type-rev' +} from '../event-type-rev.js' import { packConversationIdFileBoxToPb, unpackFileBoxFromPb, -} from '../file-box-stream/mod' -import { serializeFileBox } from '../server/serialize-file-box' +} from '../file-box-stream/mod.js' +import { serializeFileBox } from '../server/serialize-file-box.js' -import { recover$ } from './recover$' -import { GrpcClient } from './grpc-client' -import { PayloadStore } from './payload-store' +import { recover$ } from './recover$.js' +import { GrpcClient } from './grpc-client.js' +import { PayloadStore } from './payload-store.js' export type PuppetServiceOptions = PuppetOptions & { authority? : string @@ -188,11 +134,11 @@ export class PuppetService extends Puppet { this.state.on(true) } catch (e) { - log.error('PuppetService', 'start() rejection: %s\n%s', e.message, e.stack) + log.error('PuppetService', 'start() rejection: %s\n%s', (e as Error).message, (e as Error).stack) try { await this.grpc?.stop() } catch (e) { - log.error('PuppetService', 'start() this.grpc.stop() rejection: %s\n%s', e.message, e.stack) + log.error('PuppetService', 'start() this.grpc.stop() rejection: %s\n%s', (e as Error).message, (e as Error).stack) } finally { this.state.off(true) } @@ -231,7 +177,7 @@ export class PuppetService extends Puppet { this.grpc = undefined } catch (e) { - log.error('PuppetService', 'stop() client.stop() rejection: %s', e.message) + log.error('PuppetService', 'stop() client.stop() rejection: %s', (e as Error).message) } finally { this.state.off(true) } @@ -245,7 +191,7 @@ export class PuppetService extends Puppet { log.verbose('PuppetService', 'hookPayloadStore() this.on(login) contactId: "%s"', contactId) await this.payloadStore.start(contactId) } catch (e) { - log.verbose('PuppetService', 'hookPayloadStore() this.on(login) rejection "%s"', e.message) + log.verbose('PuppetService', 'hookPayloadStore() this.on(login) rejection "%s"', (e as Error).message) } }) @@ -254,7 +200,7 @@ export class PuppetService extends Puppet { try { await this.payloadStore.stop() } catch (e) { - log.verbose('PuppetService', 'hookPayloadStore() this.on(logout) rejection "%s"', e.message) + log.verbose('PuppetService', 'hookPayloadStore() this.on(logout) rejection "%s"', (e as Error).message) } }) } @@ -284,7 +230,7 @@ export class PuppetService extends Puppet { }) } - private onGrpcStreamEvent (event: EventResponse): void { + private onGrpcStreamEvent (event: pbPuppet.EventResponse): void { const type = event.getType() const payload = event.getPayload() @@ -301,66 +247,66 @@ export class PuppetService extends Puppet { payload, ) - if (type !== EventType.EVENT_TYPE_HEARTBEAT) { + if (type !== pbPuppet.EventType.EVENT_TYPE_HEARTBEAT) { this.emit('heartbeat', { data: `onGrpcStreamEvent(${EventTypeRev[type]})`, }) } switch (type) { - case EventType.EVENT_TYPE_DONG: + case pbPuppet.EventType.EVENT_TYPE_DONG: this.emit('dong', JSON.parse(payload) as EventDongPayload) break - case EventType.EVENT_TYPE_ERROR: + case pbPuppet.EventType.EVENT_TYPE_ERROR: this.emit('error', JSON.parse(payload) as EventErrorPayload) break - case EventType.EVENT_TYPE_HEARTBEAT: + case pbPuppet.EventType.EVENT_TYPE_HEARTBEAT: this.emit('heartbeat', JSON.parse(payload) as EventHeartbeatPayload) break - case EventType.EVENT_TYPE_FRIENDSHIP: + case pbPuppet.EventType.EVENT_TYPE_FRIENDSHIP: this.emit('friendship', JSON.parse(payload) as EventFriendshipPayload) break - case EventType.EVENT_TYPE_LOGIN: + case pbPuppet.EventType.EVENT_TYPE_LOGIN: { const loginPayload = JSON.parse(payload) as EventLoginPayload this.id = loginPayload.contactId this.emit('login', loginPayload) } break - case EventType.EVENT_TYPE_LOGOUT: + case pbPuppet.EventType.EVENT_TYPE_LOGOUT: this.id = undefined this.emit('logout', JSON.parse(payload) as EventLogoutPayload) break - case EventType.EVENT_TYPE_DIRTY: + case pbPuppet.EventType.EVENT_TYPE_DIRTY: this.emit('dirty', JSON.parse(payload) as EventDirtyPayload) break - case EventType.EVENT_TYPE_MESSAGE: + case pbPuppet.EventType.EVENT_TYPE_MESSAGE: this.emit('message', JSON.parse(payload) as EventMessagePayload) break - case EventType.EVENT_TYPE_READY: + case pbPuppet.EventType.EVENT_TYPE_READY: this.emit('ready', JSON.parse(payload) as EventReadyPayload) break - case EventType.EVENT_TYPE_ROOM_INVITE: + case pbPuppet.EventType.EVENT_TYPE_ROOM_INVITE: this.emit('room-invite', JSON.parse(payload) as EventRoomInvitePayload) break - case EventType.EVENT_TYPE_ROOM_JOIN: + case pbPuppet.EventType.EVENT_TYPE_ROOM_JOIN: this.emit('room-join', JSON.parse(payload) as EventRoomJoinPayload) break - case EventType.EVENT_TYPE_ROOM_LEAVE: + case pbPuppet.EventType.EVENT_TYPE_ROOM_LEAVE: this.emit('room-leave', JSON.parse(payload) as EventRoomLeavePayload) break - case EventType.EVENT_TYPE_ROOM_TOPIC: + case pbPuppet.EventType.EVENT_TYPE_ROOM_TOPIC: this.emit('room-topic', JSON.parse(payload) as EventRoomTopicPayload) break - case EventType.EVENT_TYPE_SCAN: + case pbPuppet.EventType.EVENT_TYPE_SCAN: this.emit('scan', JSON.parse(payload) as EventScanPayload) break - case EventType.EVENT_TYPE_RESET: + case pbPuppet.EventType.EVENT_TYPE_RESET: log.warn('PuppetService', 'onGrpcStreamEvent() got an EventType.EVENT_TYPE_RESET ?') // the `reset` event should be dealed not send out break - case EventType.EVENT_TYPE_UNSPECIFIED: + case pbPuppet.EventType.EVENT_TYPE_UNSPECIFIED: log.error('PuppetService', 'onGrpcStreamEvent() got an EventType.EVENT_TYPE_UNSPECIFIED ?') break @@ -380,10 +326,10 @@ export class PuppetService extends Puppet { try { await util.promisify( this.grpc!.client!.logout.bind(this.grpc!.client!) - )(new LogoutRequest()) + )(new pbPuppet.LogoutRequest()) } catch (e) { - log.error('PuppetService', 'logout() rejection: %s', e && e.message) + log.error('PuppetService', 'logout() rejection: %s', e && (e as Error).message) throw e } } @@ -391,7 +337,7 @@ export class PuppetService extends Puppet { override ding (data: string): void { log.silly('PuppetService', 'ding(%s)', data) - const request = new DingRequest() + const request = new pbPuppet.DingRequest() request.setData(data || '') if (!this.grpc?.client) { @@ -443,7 +389,7 @@ export class PuppetService extends Puppet { if (!this.grpc?.client) { throw new Error('PuppetService dirtyPayload() can not execute due to no grpcClient.') } - const request = new DirtyPayloadRequest() + const request = new pbPuppet.DirtyPayloadRequest() request.setId(id) request.setType(type) try { @@ -452,7 +398,7 @@ export class PuppetService extends Puppet { )(request) } catch (e) { - log.error('PuppetService', 'dirtyPayload() rejection: %s', e && e.message) + log.error('PuppetService', 'dirtyPayload() rejection: %s', e && (e as Error).message) throw e } } @@ -477,7 +423,7 @@ export class PuppetService extends Puppet { * Get alias */ if (typeof alias === 'undefined') { - const request = new ContactAliasRequest() + const request = new pbPuppet.ContactAliasRequest() request.setId(contactId) const response = await util.promisify( @@ -499,7 +445,7 @@ export class PuppetService extends Puppet { const aliasWrapper = new StringValue() aliasWrapper.setValue(alias || '') // null -> '', in server, we treat '' as null - const request = new ContactAliasRequest() + const request = new pbPuppet.ContactAliasRequest() request.setId(contactId) request.setAlias(aliasWrapper) @@ -511,7 +457,7 @@ export class PuppetService extends Puppet { override async contactPhone (contactId: string, phoneList: string[]): Promise { log.verbose('PuppetService', 'contactPhone(%s, %s)', contactId, phoneList) - const request = new ContactPhoneRequest() + const request = new pbPuppet.ContactPhoneRequest() request.setContactId(contactId) request.setPhoneListList(phoneList) @@ -528,7 +474,7 @@ export class PuppetService extends Puppet { corporationRemarkWrapper.setValue(corporationRemark) } - const request = new ContactCorporationRemarkRequest() + const request = new pbPuppet.ContactCorporationRemarkRequest() request.setContactId(contactId) request.setCorporationRemark(corporationRemarkWrapper) @@ -545,7 +491,7 @@ export class PuppetService extends Puppet { descriptionWrapper.setValue(description) } - const request = new ContactDescriptionRequest() + const request = new pbPuppet.ContactDescriptionRequest() request.setContactId(contactId) request.setDescription(descriptionWrapper) @@ -559,7 +505,7 @@ export class PuppetService extends Puppet { const response = await util.promisify( this.grpc!.client!.contactList.bind(this.grpc!.client!) - )(new ContactListRequest()) + )(new pbPuppet.ContactListRequest()) return response.getIdsList() } @@ -589,7 +535,7 @@ export class PuppetService extends Puppet { const fileboxWrapper = new StringValue() fileboxWrapper.setValue(await serializeFileBox(fileBox)) - const request = new ContactAvatarRequest() + const request = new pbPuppet.ContactAvatarRequest() request.setId(contactId) request.setFilebox(fileboxWrapper) @@ -603,7 +549,7 @@ export class PuppetService extends Puppet { /** * 2. get */ - const request = new ContactAvatarRequest() + const request = new pbPuppet.ContactAvatarRequest() request.setId(contactId) const response = await util.promisify( @@ -629,7 +575,7 @@ export class PuppetService extends Puppet { return cachedPayload } - const request = new ContactPayloadRequest() + const request = new pbPuppet.ContactPayloadRequest() request.setId(id) const response = await util.promisify( @@ -672,7 +618,7 @@ export class PuppetService extends Puppet { override async contactSelfName (name: string): Promise { log.verbose('PuppetService', 'contactSelfName(%s)', name) - const request = new ContactSelfNameRequest() + const request = new pbPuppet.ContactSelfNameRequest() request.setName(name) await util.promisify( @@ -685,7 +631,7 @@ export class PuppetService extends Puppet { const response = await util.promisify( this.grpc!.client!.contactSelfQRCode.bind(this.grpc!.client!) - )(new ContactSelfQRCodeRequest()) + )(new pbPuppet.ContactSelfQRCodeRequest()) return response.getQrcode() } @@ -693,7 +639,7 @@ export class PuppetService extends Puppet { override async contactSelfSignature (signature: string): Promise { log.verbose('PuppetService', 'contactSelfSignature(%s)', signature) - const request = new ContactSelfSignatureRequest() + const request = new pbPuppet.ContactSelfSignatureRequest() request.setSignature(signature) await util.promisify( @@ -724,7 +670,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageMiniProgram(%s)', messageId) - const request = new MessageMiniProgramRequest() + const request = new pbPuppet.MessageMiniProgramRequest() request.setId(messageId) const response = await util.promisify( @@ -747,7 +693,7 @@ export class PuppetService extends Puppet { ImageType[imageType], ) - const request = new MessageImageStreamRequest() + const request = new pbPuppet.MessageImageStreamRequest() request.setId(messageId) request.setType(imageType) @@ -766,7 +712,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageContact(%s)', messageId) - const request = new MessageContactRequest() + const request = new pbPuppet.MessageContactRequest() request.setId(messageId) const response = await util.promisify( @@ -783,7 +729,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageSendMiniProgram(%s)', conversationId, JSON.stringify(miniProgramPayload)) - const request = new MessageSendMiniProgramRequest() + const request = new pbPuppet.MessageSendMiniProgramRequest() request.setConversationId(conversationId) request.setMiniProgram(JSON.stringify(miniProgramPayload)) @@ -803,7 +749,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageRecall(%s)', messageId) - const request = new MessageRecallRequest() + const request = new pbPuppet.MessageRecallRequest() request.setId(messageId) const response = await util.promisify( @@ -816,7 +762,7 @@ export class PuppetService extends Puppet { override async messageFile (id: string): Promise { log.verbose('PuppetService', 'messageFile(%s)', id) - const request = new MessageFileStreamRequest() + const request = new pbPuppet.MessageFileStreamRequest() request.setId(id) if (!this.grpc?.client) { @@ -835,7 +781,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageForward(%s, %s)', conversationId, messageId) - const request = new MessageForwardRequest() + const request = new pbPuppet.MessageForwardRequest() request.setConversationId(conversationId) request.setMessageId(messageId) @@ -859,7 +805,7 @@ export class PuppetService extends Puppet { // return cachedPayload // } - const request = new MessagePayloadRequest() + const request = new pbPuppet.MessagePayloadRequest() request.setId(id) const response = await util.promisify( @@ -897,7 +843,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageSend(%s, %s)', conversationId, text) - const request = new MessageSendTextRequest() + const request = new pbPuppet.MessageSendTextRequest() request.setConversationId(conversationId) request.setText(text) if (typeof mentionIdList !== 'undefined') { @@ -941,7 +887,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageSend("%s", %s)', conversationId, contactId) - const request = new MessageSendContactRequest() + const request = new pbPuppet.MessageSendContactRequest() request.setConversationId(conversationId) request.setContactId(contactId) @@ -962,7 +908,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'messageSendUrl("%s", %s)', conversationId, JSON.stringify(urlLinkPayload)) - const request = new MessageSendUrlRequest() + const request = new pbPuppet.MessageSendUrlRequest() request.setConversationId(conversationId) request.setUrlLink(JSON.stringify(urlLinkPayload)) @@ -980,7 +926,7 @@ export class PuppetService extends Puppet { override async messageUrl (messageId: string): Promise { log.verbose('PuppetService', 'messageUrl(%s)', messageId) - const request = new MessageUrlRequest() + const request = new pbPuppet.MessageUrlRequest() request.setId(messageId) const response = await util.promisify( @@ -1009,7 +955,7 @@ export class PuppetService extends Puppet { return cachedPayload } - const request = new RoomPayloadRequest() + const request = new pbPuppet.RoomPayloadRequest() request.setId(id) const response = await util.promisify( @@ -1042,7 +988,7 @@ export class PuppetService extends Puppet { const response = await util.promisify( this.grpc!.client!.roomList.bind(this.grpc!.client!) - )(new RoomListRequest()) + )(new pbPuppet.RoomListRequest()) return response.getIdsList() } @@ -1053,7 +999,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'roomDel(%s, %s)', roomId, contactId) - const request = new RoomDelRequest() + const request = new pbPuppet.RoomDelRequest() request.setId(roomId) request.setContactId(contactId) @@ -1065,7 +1011,7 @@ export class PuppetService extends Puppet { override async roomAvatar (roomId: string): Promise { log.verbose('PuppetService', 'roomAvatar(%s)', roomId) - const request = new RoomAvatarRequest() + const request = new pbPuppet.RoomAvatarRequest() request.setId(roomId) const response = await util.promisify( @@ -1083,7 +1029,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'roomAdd(%s, %s)', roomId, contactId) - const request = new RoomAddRequest() + const request = new pbPuppet.RoomAddRequest() request.setId(roomId) request.setContactId(contactId) request.setInviteOnly(inviteOnly) @@ -1106,7 +1052,7 @@ export class PuppetService extends Puppet { * Get */ if (typeof topic === 'undefined') { - const request = new RoomTopicRequest() + const request = new pbPuppet.RoomTopicRequest() request.setId(roomId) const response = await util.promisify( @@ -1126,7 +1072,7 @@ export class PuppetService extends Puppet { const topicWrapper = new StringValue() topicWrapper.setValue(topic) - const request = new RoomTopicRequest() + const request = new pbPuppet.RoomTopicRequest() request.setId(roomId) request.setTopic(topicWrapper) @@ -1141,7 +1087,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'roomCreate(%s, %s)', contactIdList, topic) - const request = new RoomCreateRequest() + const request = new pbPuppet.RoomCreateRequest() request.setContactIdsList(contactIdList) request.setTopic(topic) @@ -1155,7 +1101,7 @@ export class PuppetService extends Puppet { override async roomQuit (roomId: string): Promise { log.verbose('PuppetService', 'roomQuit(%s)', roomId) - const request = new RoomQuitRequest() + const request = new pbPuppet.RoomQuitRequest() request.setId(roomId) await util.promisify( @@ -1166,7 +1112,7 @@ export class PuppetService extends Puppet { override async roomQRCode (roomId: string): Promise { log.verbose('PuppetService', 'roomQRCode(%s)', roomId) - const request = new RoomQRCodeRequest() + const request = new pbPuppet.RoomQRCodeRequest() request.setId(roomId) const response = await util.promisify( @@ -1179,7 +1125,7 @@ export class PuppetService extends Puppet { override async roomMemberList (roomId: string) : Promise { log.verbose('PuppetService', 'roomMemberList(%s)', roomId) - const request = new RoomMemberListRequest() + const request = new pbPuppet.RoomMemberListRequest() request.setId(roomId) const response = await util.promisify( @@ -1199,7 +1145,7 @@ export class PuppetService extends Puppet { return cachedPayload } - const request = new RoomMemberPayloadRequest() + const request = new pbPuppet.RoomMemberPayloadRequest() request.setId(roomId) request.setMemberId(contactId) @@ -1245,7 +1191,7 @@ export class PuppetService extends Puppet { const textWrapper = new StringValue() textWrapper.setValue(text) - const request = new RoomAnnounceRequest() + const request = new pbPuppet.RoomAnnounceRequest() request.setId(roomId) request.setText(textWrapper) @@ -1259,7 +1205,7 @@ export class PuppetService extends Puppet { /** * Get */ - const request = new RoomAnnounceRequest() + const request = new pbPuppet.RoomAnnounceRequest() request.setId(roomId) const response = await util.promisify( @@ -1278,7 +1224,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'roomInvitationAccept(%s)', roomInvitationId) - const request = new RoomInvitationAcceptRequest() + const request = new pbPuppet.RoomInvitationAcceptRequest() request.setId(roomInvitationId) await util.promisify( @@ -1291,7 +1237,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'roomInvitationRawPayload(%s)', id) - const request = new RoomInvitationPayloadRequest() + const request = new pbPuppet.RoomInvitationPayloadRequest() request.setId(id) const response = await util.promisify( @@ -1329,7 +1275,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'friendshipSearchPhone(%s)', phone) - const request = new FriendshipSearchPhoneRequest() + const request = new pbPuppet.FriendshipSearchPhoneRequest() request.setPhone(phone) const response = await util.promisify( @@ -1348,7 +1294,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'friendshipSearchWeixin(%s)', weixin) - const request = new FriendshipSearchWeixinRequest() + const request = new pbPuppet.FriendshipSearchWeixinRequest() request.setWeixin(weixin) const response = await util.promisify( @@ -1365,7 +1311,7 @@ export class PuppetService extends Puppet { override async friendshipRawPayload (id: string): Promise { log.verbose('PuppetService', 'friendshipRawPayload(%s)', id) - const request = new FriendshipPayloadRequest() + const request = new pbPuppet.FriendshipPayloadRequest() request.setId(id) const response = await util.promisify( @@ -1397,7 +1343,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'friendshipAdd(%s, %s)', contactId, JSON.stringify(options)) - const request = new FriendshipAddRequest() + const request = new pbPuppet.FriendshipAddRequest() request.setContactId(contactId) // FIXME: for backward compatibility, need to be removed after all puppet has updated. @@ -1423,7 +1369,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'friendshipAccept(%s)', friendshipId) - const request = new FriendshipAcceptRequest() + const request = new pbPuppet.FriendshipAcceptRequest() request.setId(friendshipId) await util.promisify( @@ -1443,7 +1389,7 @@ export class PuppetService extends Puppet { ): Promise { log.verbose('PuppetService', 'tagContactAdd(%s, %s)', id, contactId) - const request = new TagContactAddRequest() + const request = new pbPuppet.TagContactAddRequest() request.setId(id) request.setContactId(contactId) @@ -1459,7 +1405,7 @@ export class PuppetService extends Puppet { ) : Promise { log.verbose('PuppetService', 'tagContactRemove(%s, %s)', id, contactId) - const request = new TagContactRemoveRequest() + const request = new pbPuppet.TagContactRemoveRequest() request.setId(id) request.setContactId(contactId) @@ -1474,7 +1420,7 @@ export class PuppetService extends Puppet { ) : Promise { log.verbose('PuppetService', 'tagContactDelete(%s)', id) - const request = new TagContactDeleteRequest() + const request = new pbPuppet.TagContactDeleteRequest() request.setId(id) await util.promisify( @@ -1488,7 +1434,7 @@ export class PuppetService extends Puppet { ) : Promise { log.verbose('PuppetService', 'tagContactList(%s)', contactId) - const request = new TagContactListRequest() + const request = new pbPuppet.TagContactListRequest() if (typeof contactId !== 'undefined') { const contactIdWrapper = new StringValue() @@ -1507,9 +1453,9 @@ export class PuppetService extends Puppet { conversationId : string, file : FileBox, ): Promise { - const request = await packConversationIdFileBoxToPb(MessageSendFileStreamRequest)(conversationId, file) + const request = await packConversationIdFileBoxToPb(pbPuppet.MessageSendFileStreamRequest)(conversationId, file) - const response = await new Promise((resolve, reject) => { + const response = await new Promise((resolve, reject) => { if (!this.grpc?.client) { reject(new Error('Can not send message file since no grpc client.')) return @@ -1535,7 +1481,7 @@ export class PuppetService extends Puppet { conversationId : string, file : FileBox, ): Promise { - const request = new MessageSendFileRequest() + const request = new pbPuppet.MessageSendFileRequest() request.setConversationId(conversationId) request.setFilebox(JSON.stringify(file)) diff --git a/src/client/recover$.spec.ts b/src/client/recover$.spec.ts index 8cf94338..63f1e2c9 100755 --- a/src/client/recover$.spec.ts +++ b/src/client/recover$.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' @@ -10,7 +10,7 @@ import { test } from 'tstest' import { switchSuccess, -} from './recover$' +} from './recover$.js' test('switchSuccess()', async t => { t.equal(switchSuccess(true), true, 'should get expected result for boolean `true`') diff --git a/src/client/recover$.ts b/src/client/recover$.ts index 9c716dff..9d3cc673 100644 --- a/src/client/recover$.ts +++ b/src/client/recover$.ts @@ -1,5 +1,6 @@ import { Puppet, + log, } from 'wechaty-puppet' import { @@ -21,10 +22,6 @@ import { tap, } from 'rxjs/operators' -import { - log, -} from '../config' - /** * Filters */ diff --git a/src/config.ts b/src/config.ts index bc494a20..2e460f05 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,11 +1,11 @@ /// -import { log } from 'wechaty-puppet' +import { packageJson } from './package-json.js' -import { VERSION } from './version' +import * as rootEnvVars from './env-vars.js' +import * as authEnvVars from './auth/env-vars.js' -import * as rootEnvVars from './env-vars' -import * as authEnvVars from './auth/env-vars' +const VERSION = packageJson.version || '0.0.0' const envVars = { ...rootEnvVars, @@ -23,7 +23,6 @@ const GRPC_OPTIONS = { export { envVars, - log, GRPC_OPTIONS, VERSION, } diff --git a/src/env-vars.spec.ts b/src/env-vars.spec.ts index 5fdc6ced..b725ac3a 100755 --- a/src/env-vars.spec.ts +++ b/src/env-vars.spec.ts @@ -1,9 +1,9 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm // tslint:disable:no-shadowed-variable import { test } from 'tstest' -import { WECHATY_PUPPET_SERVICE_AUTHORITY } from './env-vars' +import { WECHATY_PUPPET_SERVICE_AUTHORITY } from './env-vars.js' /** * Huan(202108): compatible with old env var diff --git a/src/env-vars.ts b/src/env-vars.ts index 1ae707b1..5db0d4fa 100644 --- a/src/env-vars.ts +++ b/src/env-vars.ts @@ -1,4 +1,4 @@ -import { log } from './config' +import { log } from 'wechaty-puppet' // Huan(202011): use a function to return the value in time. const WECHATY_PUPPET_SERVICE_TOKEN: (token?: string) => string = token => { diff --git a/src/event-type-rev.ts b/src/event-type-rev.ts index 3cf9a593..dbe59edd 100644 --- a/src/event-type-rev.ts +++ b/src/event-type-rev.ts @@ -1,6 +1,5 @@ import { - EventType, - EventTypeMap, + puppet, } from 'wechaty-grpc' /** @@ -14,7 +13,7 @@ export const EventTypeRev = {} as { [key: number]: string, } -for (const key in EventType) { - const val = EventType[key as keyof EventTypeMap] +for (const key in puppet.EventType) { + const val = puppet.EventType[key as keyof puppet.EventTypeMap] EventTypeRev[val] = key } diff --git a/src/file-box-stream/chunk-pb.spec.ts b/src/file-box-stream/chunk-pb.spec.ts index e95ab022..964c27d3 100755 --- a/src/file-box-stream/chunk-pb.spec.ts +++ b/src/file-box-stream/chunk-pb.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' @@ -7,19 +7,17 @@ import { PassThrough } from 'stream' import { FileBox } from 'wechaty-puppet' import { - FileBoxChunk, - MessageFileStreamResponse, - MessageSendFileStreamRequest, + puppet, } from 'wechaty-grpc' import { unpackFileBoxFromChunk, packFileBoxToChunk, -} from './file-box-chunk' +} from './file-box-chunk.js' import { unpackFileBoxChunkFromPb, packFileBoxChunkToPb, -} from './chunk-pb' +} from './chunk-pb.js' test('packFileBoxChunk()', async t => { const FILE_BOX_DATA = 'test' @@ -31,11 +29,11 @@ test('packFileBoxChunk()', async t => { ) const chunkStream = await packFileBoxToChunk(fileBox) - const pbStream = await packFileBoxChunkToPb(MessageFileStreamResponse)(chunkStream) + const pbStream = await packFileBoxChunkToPb(puppet.MessageFileStreamResponse)(chunkStream) let name = '' let buffer = '' - pbStream.on('data', (data: MessageFileStreamResponse) => { + pbStream.on('data', (data: puppet.MessageFileStreamResponse) => { if (data.hasFileBoxChunk()) { const fileBoxChunk = data.getFileBoxChunk() if (fileBoxChunk!.hasData()) { @@ -62,11 +60,11 @@ test('unpackFileBoxChunkFromPb()', async t => { ) const chunkStream = await packFileBoxToChunk(fileBox) - const request = new MessageSendFileStreamRequest() + const request = new puppet.MessageSendFileStreamRequest() const packedStream = new PassThrough({ objectMode: true }) - chunkStream.on('data', (data: FileBoxChunk) => { + chunkStream.on('data', (data: puppet.FileBoxChunk) => { request.setFileBoxChunk(data) packedStream.write(request) }).on('end', () => { @@ -89,7 +87,7 @@ test('packFileBoxChunk() <-> unpackFileBoxChunkFromPb()', async t => { ) const chunkStream = await packFileBoxToChunk(fileBox) - const packedStream = packFileBoxChunkToPb(MessageFileStreamResponse)(chunkStream) + const packedStream = packFileBoxChunkToPb(puppet.MessageFileStreamResponse)(chunkStream) const unpackedStream = unpackFileBoxChunkFromPb(packedStream) const restoredBox = await unpackFileBoxFromChunk(unpackedStream) @@ -107,9 +105,9 @@ test('packFileBoxChunk(): should not throw if no read on the stream', async t => const stream = await getTestChunkStream({}) let outStream try { - outStream = packFileBoxChunkToPb(MessageFileStreamResponse)(stream) + outStream = packFileBoxChunkToPb(puppet.MessageFileStreamResponse)(stream) } catch (e) { - t.ok(e.message) + t.ok((e as Error).message) return } outStream.on('error', _ => { /* Do nothing */ }) @@ -120,7 +118,7 @@ test('packFileBoxChunk(): should emit error in the output stream', async t => { const EXPECTED_MESSAGE = 'test emit error' const stream = await getTestChunkStream({ errorMessage: EXPECTED_MESSAGE }) - const outStream = packFileBoxChunkToPb(MessageFileStreamResponse)(stream) + const outStream = packFileBoxChunkToPb(puppet.MessageFileStreamResponse)(stream) const error = await new Promise(resolve => outStream.on('error', resolve)) // await new Promise(resolve => outStream.on('end', resolve)) @@ -136,7 +134,7 @@ test('unpackFileBoxChunkFromPb(): should not throw if no read on the stream', as outStream = unpackFileBoxChunkFromPb(stream) t.pass('should no rejection') } catch (e) { - t.fail(e.message) + t.fail((e as Error).message) return } outStream.on('error', _ => { /* Do nothing */ }) @@ -147,7 +145,7 @@ test('unpackFileBoxChunkFromPb(): should emit error in the output stream', async const errorMessage = 'test emit error' const stream = await getTestPackedStream({ errorMessage }) - const outStream = packFileBoxChunkToPb(MessageFileStreamResponse)(stream) + const outStream = packFileBoxChunkToPb(puppet.MessageFileStreamResponse)(stream) try { await new Promise((resolve, reject) => { @@ -156,7 +154,7 @@ test('unpackFileBoxChunkFromPb(): should emit error in the output stream', async }) t.fail('should reject the promise') } catch (e) { - t.equal(e.message, errorMessage, 'should get the expected rejection error message') + t.equal((e as Error).message, errorMessage, 'should get the expected rejection error message') } }) @@ -197,7 +195,7 @@ async function getTestPackedStream (options: { const chunkStream = await packFileBoxToChunk(fileBox) const packedStream = new PassThrough({ objectMode: true }) chunkStream.on('data', d => { - const packedChunk = new MessageFileStreamResponse() + const packedChunk = new puppet.MessageFileStreamResponse() packedChunk.setFileBoxChunk(d) packedStream.write(packedChunk) }).on('error', e => { diff --git a/src/file-box-stream/chunk-pb.ts b/src/file-box-stream/chunk-pb.ts index 53f64590..fcef5954 100644 --- a/src/file-box-stream/chunk-pb.ts +++ b/src/file-box-stream/chunk-pb.ts @@ -1,17 +1,17 @@ -import { FileBoxChunk } from 'wechaty-grpc' +import { puppet } from 'wechaty-grpc' import { Readable, Transform } from 'stronger-typed-streams' import { PassThrough } from 'stream' -import { FileBoxPb } from './file-box-pb.type' +import { FileBoxPb } from './file-box-pb.type.js' /** * Wrap FileBoxChunk */ const encoder = ( PbConstructor: { new(): T }, -) => new Transform({ +) => new Transform({ objectMode: true, - transform: (chunk: FileBoxChunk, _: any, callback: (error: Error | null, data: T) => void) => { + transform: (chunk: puppet.FileBoxChunk, _: any, callback: (error: Error | null, data: T) => void) => { const message = new PbConstructor() message.setFileBoxChunk(chunk) callback(null, message) @@ -21,7 +21,7 @@ const encoder = ( function packFileBoxChunkToPb ( PbConstructor: { new(): T }, ) { - return (stream: Readable): Readable => { + return (stream: Readable): Readable => { const outStream = new PassThrough({ objectMode: true }) const encodedStream = stream.pipe(encoder(PbConstructor)) @@ -36,9 +36,9 @@ function packFileBoxChunkToPb ( /** * Unwrap FileBoxChunk */ -const decoder = () => new Transform({ +const decoder = () => new Transform({ objectMode: true, - transform: (chunk: T, _: any, callback: (error: Error | null, data?: FileBoxChunk) => void) => { + transform: (chunk: T, _: any, callback: (error: Error | null, data?: puppet.FileBoxChunk) => void) => { const fileBoxChunk = chunk.getFileBoxChunk() if (!fileBoxChunk) { callback(new Error('No FileBoxChunk')) @@ -50,7 +50,7 @@ const decoder = () => new Transform({ function unpackFileBoxChunkFromPb ( stream: Readable, -): Readable { +): Readable { const outStream = new PassThrough({ objectMode: true }) const decodedStream = stream.pipe(decoder()) diff --git a/src/file-box-stream/conversation-id-file-box.spec.ts b/src/file-box-stream/conversation-id-file-box.spec.ts index ac8fe434..021bfa85 100755 --- a/src/file-box-stream/conversation-id-file-box.spec.ts +++ b/src/file-box-stream/conversation-id-file-box.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm /** * Wechaty Chatbot SDK - https://github.com/wechaty/wechaty @@ -20,19 +20,18 @@ * */ import { - FileBoxChunk, - MessageSendFileStreamRequest, + puppet, } from 'wechaty-grpc' import { test } from 'tstest' import { PassThrough } from 'stream' import { FileBox } from 'wechaty-puppet' -import { nextData } from './next-data' +import { nextData } from './next-data.js' import { packConversationIdFileBoxToPb, unpackConversationIdFileBoxArgsFromPb, -} from './conversation-id-file-box' +} from './conversation-id-file-box.js' test('unpackConversationIdFileBoxArgsFromPb()', async t => { const FILE_BOX_DATA = 'test' @@ -46,21 +45,21 @@ test('unpackConversationIdFileBoxArgsFromPb()', async t => { const stream = new PassThrough({ objectMode: true }) - const req1 = new MessageSendFileStreamRequest() + const req1 = new puppet.MessageSendFileStreamRequest() req1.setConversationId(CONVERSATION_ID) stream.write(req1) - const req2 = new MessageSendFileStreamRequest() - const chunk1 = new FileBoxChunk() + const req2 = new puppet.MessageSendFileStreamRequest() + const chunk1 = new puppet.FileBoxChunk() chunk1.setName(fileBox.name) req2.setFileBoxChunk(chunk1) stream.write(req2) const fileBoxStream = await fileBox.toStream() fileBoxStream.on('data', chunk => { - const fileBoxChunk = new FileBoxChunk() + const fileBoxChunk = new puppet.FileBoxChunk() fileBoxChunk.setData(chunk) - const req3 = new MessageSendFileStreamRequest() + const req3 = new puppet.MessageSendFileStreamRequest() req3.setFileBoxChunk(fileBoxChunk) stream.write(req3) }) @@ -84,7 +83,7 @@ test('packConversationIdFileBoxToPb()', async t => { FILE_BOX_NAME, ) - const stream = await packConversationIdFileBoxToPb(MessageSendFileStreamRequest)( + const stream = await packConversationIdFileBoxToPb(puppet.MessageSendFileStreamRequest)( CONVERSATION_ID, fileBox, ) @@ -98,7 +97,7 @@ test('packConversationIdFileBoxToPb()', async t => { t.equal(data2.getFileBoxChunk()!.getName(), FILE_BOX_NAME, 'match file box name') let data = '' - stream.on('data', (chunk: MessageSendFileStreamRequest) => { + stream.on('data', (chunk: puppet.MessageSendFileStreamRequest) => { if (!chunk.hasFileBoxChunk()) { throw new Error('no file box chunk') } @@ -123,7 +122,7 @@ test('unpackConversationIdFileBoxArgsFromPb() <-> packConversationIdFileBoxToPb( FILE_BOX_NAME, ) - const stream = await packConversationIdFileBoxToPb(MessageSendFileStreamRequest)(CONVERSATION_ID, fileBox) + const stream = await packConversationIdFileBoxToPb(puppet.MessageSendFileStreamRequest)(CONVERSATION_ID, fileBox) const args = await unpackConversationIdFileBoxArgsFromPb(stream) t.equal(args.conversationId, CONVERSATION_ID, 'should match conversation id') diff --git a/src/file-box-stream/conversation-id-file-box.ts b/src/file-box-stream/conversation-id-file-box.ts index ce9cab02..ac1f2d88 100644 --- a/src/file-box-stream/conversation-id-file-box.ts +++ b/src/file-box-stream/conversation-id-file-box.ts @@ -2,12 +2,12 @@ import { FileBox } from 'wechaty-puppet' import { PassThrough } from 'stream' import { Readable } from 'stronger-typed-streams' -import { nextData } from './next-data' +import { nextData } from './next-data.js' import { packFileBoxToPb, unpackFileBoxFromPb, -} from './file-box-pb' -import { ConversationIdFileBoxPb } from './file-box-pb.type' +} from './file-box-pb.js' +import { ConversationIdFileBoxPb } from './file-box-pb.type.js' interface ConversationIdFileBoxArgs { conversationId: string, diff --git a/src/file-box-stream/file-box-chunk.spec.ts b/src/file-box-stream/file-box-chunk.spec.ts index e48a70ff..48435143 100755 --- a/src/file-box-stream/file-box-chunk.spec.ts +++ b/src/file-box-stream/file-box-chunk.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm /** * Wechaty Chatbot SDK - https://github.com/wechaty/wechaty @@ -26,14 +26,14 @@ import { Duplex } from 'stronger-typed-streams' import { FileBox } from 'wechaty-puppet' import { - FileBoxChunk, + puppet, } from 'wechaty-grpc' import { unpackFileBoxFromChunk, packFileBoxToChunk, -} from './file-box-chunk' -import { nextData } from './next-data' +} from './file-box-chunk.js' +import { nextData } from './next-data.js' test('unpackFileBoxFromChunk()', async t => { const FILE_BOX_DATA = 'test' @@ -67,7 +67,7 @@ test('packFileBoxToChunk()', async t => { t.equal(fileName, FILE_BOX_NAME, 'should get name') let data = '' - stream.on('data', (chunk: FileBoxChunk) => { + stream.on('data', (chunk: puppet.FileBoxChunk) => { if (!chunk.hasData()) { throw new Error('no data') } @@ -105,7 +105,7 @@ test('should handle no name error in catch', async t => { try { await unpackFileBoxFromChunk(stream) } catch (e) { - t.equal(e.message, 'no name') + t.equal((e as Error).message, 'no name') } }) @@ -119,7 +119,7 @@ test('should handle first error catch', async t => { try { await unpackFileBoxFromChunk(stream) } catch (e) { - t.equal(e.message, 'first exception') + t.equal((e as Error).message, 'first exception') } }) @@ -134,7 +134,7 @@ test('should handle middle error in further ops', async t => { try { await fileBox.toBuffer() } catch (e) { - t.equal(e.message, 'middle exception') + t.equal((e as Error).message, 'middle exception') } }) @@ -150,7 +150,7 @@ async function getFileBoxStreamStub ( name, ) - const stream: Duplex = new PassThrough({ objectMode: true }) + const stream: Duplex = new PassThrough({ objectMode: true }) if (firstException) { stream.pause() @@ -159,7 +159,7 @@ async function getFileBoxStreamStub ( stream.resume() }) } else { - const chunk1 = new FileBoxChunk() + const chunk1 = new puppet.FileBoxChunk() if (!noname) { chunk1.setName(fileBox.name) } @@ -174,7 +174,7 @@ async function getFileBoxStreamStub ( const fileBoxStream = await fileBox.toStream() fileBoxStream.on('data', chunk => { - const fileBoxChunk = new FileBoxChunk() + const fileBoxChunk = new puppet.FileBoxChunk() fileBoxChunk.setData(chunk) setTimeout(() => stream.write(fileBoxChunk), 200) }) diff --git a/src/file-box-stream/file-box-chunk.ts b/src/file-box-stream/file-box-chunk.ts index 73bac7e4..a41156fc 100644 --- a/src/file-box-stream/file-box-chunk.ts +++ b/src/file-box-stream/file-box-chunk.ts @@ -1,4 +1,3 @@ -import { FileBoxChunk } from 'wechaty-grpc' import { FileBox } from 'wechaty-puppet' import { PassThrough } from 'stream' import { @@ -6,11 +5,13 @@ import { Transform, } from 'stronger-typed-streams' -import { nextData } from './next-data' +import { puppet } from 'wechaty-grpc' -const decoder = () => new Transform({ +import { nextData } from './next-data.js' + +const decoder = () => new Transform({ objectMode: true, - transform: (chunk: FileBoxChunk, _: any, callback: any) => { + transform: (chunk: puppet.FileBoxChunk, _: any, callback: any) => { if (!chunk.hasData()) { callback(new Error('no data')) return @@ -21,7 +22,7 @@ const decoder = () => new Transform({ }) async function unpackFileBoxFromChunk ( - stream: Readable, + stream: Readable, ): Promise { const chunk = await nextData(stream) if (!chunk.hasName()) { @@ -40,10 +41,10 @@ async function unpackFileBoxFromChunk ( return fileBox } -const encoder = () => new Transform({ +const encoder = () => new Transform({ objectMode: true, transform: (chunk: any, _: any, callback: any) => { - const fileBoxChunk = new FileBoxChunk() + const fileBoxChunk = new puppet.FileBoxChunk() fileBoxChunk.setData(chunk) callback(null, fileBoxChunk) }, @@ -51,10 +52,10 @@ const encoder = () => new Transform({ async function packFileBoxToChunk ( fileBox: FileBox, -): Promise> { +): Promise> { const stream = new PassThrough({ objectMode: true }) - const chunk = new FileBoxChunk() + const chunk = new puppet.FileBoxChunk() chunk.setName(fileBox.name) // FIXME: Huan(202010) write might return false diff --git a/src/file-box-stream/file-box-pb.spec.ts b/src/file-box-stream/file-box-pb.spec.ts index a481e446..7d590836 100755 --- a/src/file-box-stream/file-box-pb.spec.ts +++ b/src/file-box-stream/file-box-pb.spec.ts @@ -1,17 +1,17 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' import { FileBox } from 'wechaty-puppet' import { - MessageFileStreamResponse, + puppet, } from 'wechaty-grpc' import { packFileBoxToPb, unpackFileBoxFromPb, -} from './file-box-pb' +} from './file-box-pb.js' test('packFileBoxToPb()', async t => { const FILE_BOX_DATA = 'test' @@ -22,7 +22,7 @@ test('packFileBoxToPb()', async t => { FILE_BOX_NAME, ) - const pb = await packFileBoxToPb(MessageFileStreamResponse)(fileBox) + const pb = await packFileBoxToPb(puppet.MessageFileStreamResponse)(fileBox) const restoredFileBox = await unpackFileBoxFromPb(pb) t.ok(restoredFileBox instanceof FileBox, 'should get an instance of FileBOX') diff --git a/src/file-box-stream/file-box-pb.ts b/src/file-box-stream/file-box-pb.ts index 4e26703a..fc950c98 100644 --- a/src/file-box-stream/file-box-pb.ts +++ b/src/file-box-stream/file-box-pb.ts @@ -4,12 +4,12 @@ import { Readable } from 'stronger-typed-streams' import { packFileBoxToChunk, unpackFileBoxFromChunk, -} from './file-box-chunk' +} from './file-box-chunk.js' import { packFileBoxChunkToPb, unpackFileBoxChunkFromPb, -} from './chunk-pb' -import { FileBoxPb } from './file-box-pb.type' +} from './chunk-pb.js' +import { FileBoxPb } from './file-box-pb.type.js' function packFileBoxToPb ( PbConstructor: { new(): T }, diff --git a/src/file-box-stream/file-box-pb.type.ts b/src/file-box-stream/file-box-pb.type.ts index 841a205f..87ccf459 100644 --- a/src/file-box-stream/file-box-pb.type.ts +++ b/src/file-box-stream/file-box-pb.type.ts @@ -1,12 +1,12 @@ -import { FileBoxChunk } from 'wechaty-grpc' +import { puppet } from 'wechaty-grpc' /** * Any Protocol Buffer message that include a FileBoxChunk */ export interface FileBoxPb { hasFileBoxChunk(): boolean - getFileBoxChunk(): FileBoxChunk | undefined - setFileBoxChunk(value?: FileBoxChunk): void + getFileBoxChunk(): puppet.FileBoxChunk | undefined + setFileBoxChunk(value?: puppet.FileBoxChunk): void } export interface ConversationIdFileBoxPb extends FileBoxPb { diff --git a/src/file-box-stream/mod.ts b/src/file-box-stream/mod.ts index 2ee763d7..1593e995 100644 --- a/src/file-box-stream/mod.ts +++ b/src/file-box-stream/mod.ts @@ -1,8 +1,8 @@ export { packConversationIdFileBoxToPb, unpackConversationIdFileBoxArgsFromPb, -} from './conversation-id-file-box' +} from './conversation-id-file-box.js' export { packFileBoxToPb, unpackFileBoxFromPb, -} from './file-box-pb' +} from './file-box-pb.js' diff --git a/src/mod.spec.ts b/src/mod.spec.ts index 110f9f8e..b252f910 100644 --- a/src/mod.spec.ts +++ b/src/mod.spec.ts @@ -1,8 +1,8 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' -import * as mod from './mod' +import * as mod from './mod.js' test('default export', async t => { t.ok(mod.default, 'should export a default, which is required from PuppetManager of Wechaty') diff --git a/src/mod.ts b/src/mod.ts index e1523082..fe8334d0 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -1,14 +1,25 @@ -export { - PuppetService, - PuppetService as default, -} from './client/puppet-service' - -export { +import { log, +} from 'wechaty-puppet' +import { + PuppetService, +} from './client/puppet-service.js' +import { VERSION, -} from './config' +} from './config.js' +import { + PuppetServer, + PuppetServerOptions, +} from './server/puppet-server.js' export { + log, PuppetServer, + PuppetService, + VERSION, +} +export type { PuppetServerOptions, -} from './server/puppet-server' +} + +export default PuppetService diff --git a/src/package-json.spec.ts b/src/package-json.spec.ts new file mode 100755 index 00000000..4e65468a --- /dev/null +++ b/src/package-json.spec.ts @@ -0,0 +1,10 @@ +#!/usr/bin/env node --no-warnings --loader ts-node/esm + +import { test } from 'tstest' + +import { packageJson } from './package-json.js' + +test('Make sure the packageJson is fresh in source code', async t => { + const keyNum = Object.keys(packageJson).length + t.equal(keyNum, 0, 'packageJson should be empty in source code, only updated before publish to NPM') +}) diff --git a/src/package-json.ts b/src/package-json.ts new file mode 100644 index 00000000..be70e65e --- /dev/null +++ b/src/package-json.ts @@ -0,0 +1,11 @@ +/** + * This file will be overwrite when we publish NPM module + * by scripts/generate_version.ts + */ +import { PackageJson } from 'type-fest' + +/** + * Huan(202108): + * The below default values is only for unit testing + */ +export const packageJson: PackageJson = {} diff --git a/src/server/event-stream-manager.ts b/src/server/event-stream-manager.ts index eedfbf6b..20143887 100644 --- a/src/server/event-stream-manager.ts +++ b/src/server/event-stream-manager.ts @@ -1,8 +1,5 @@ import { - EventRequest, - EventResponse, - EventType, - EventTypeMap, + puppet as grpcPuppet, grpc, } from 'wechaty-grpc' @@ -24,19 +21,16 @@ import { PUPPET_EVENT_DICT, Puppet, PuppetEventName, -} from 'wechaty-puppet' - -import { log, -} from '../config' +} from 'wechaty-puppet' import { EventTypeRev, -} from '../event-type-rev' +} from '../event-type-rev.js' class EventStreamManager { - protected eventStream: undefined | grpc.ServerWritableStream + protected eventStream: undefined | grpc.ServerWritableStream private puppetListening = false @@ -51,7 +45,7 @@ class EventStreamManager { } public start ( - stream: grpc.ServerWritableStream, + stream: grpc.ServerWritableStream, ): void { log.verbose('EventStreamManager', 'start(stream)') @@ -79,7 +73,7 @@ class EventStreamManager { data: 'Wechaty Puppet gRPC stream connect successfully', } as EventHeartbeatPayload this.grpcEmit( - EventType.EVENT_TYPE_HEARTBEAT, + grpcPuppet.EventType.EVENT_TYPE_HEARTBEAT, connectSuccessHeartbeatPayload, ) @@ -93,7 +87,7 @@ class EventStreamManager { contactId: this.puppet.selfId(), } as EventLoginPayload - this.grpcEmit(EventType.EVENT_TYPE_LOGIN, payload) + this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_LOGIN, payload) } } @@ -109,7 +103,7 @@ class EventStreamManager { } public grpcEmit ( - type : EventTypeMap[keyof EventTypeMap], // https://stackoverflow.com/a/49286056/1123955 + type : grpcPuppet.EventTypeMap[keyof grpcPuppet.EventTypeMap], // https://stackoverflow.com/a/49286056/1123955 obj : object, ): void { log.verbose('EventStreamManager', 'grpcEmit(%s[%s], %s)', @@ -118,7 +112,7 @@ class EventStreamManager { JSON.stringify(obj), ) - const response = new EventResponse() + const response = new grpcPuppet.EventResponse() response.setType(type) response.setPayload( @@ -161,98 +155,98 @@ class EventStreamManager { switch (eventName) { case 'dong': { - const listener = (payload: EventDongPayload) => this.grpcEmit(EventType.EVENT_TYPE_DONG, payload) + const listener = (payload: EventDongPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_DONG, payload) this.puppet.on('dong', listener) const off = () => this.puppet.off('dong', listener) offCallbackList.push(off) break } case 'dirty': { - const listener = (payload: EventDirtyPayload) => this.grpcEmit(EventType.EVENT_TYPE_DIRTY, payload) + const listener = (payload: EventDirtyPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_DIRTY, payload) this.puppet.on('dirty', listener) const off = () => this.puppet.off('dirty', listener) offCallbackList.push(off) break } case 'error': { - const listener = (payload: EventErrorPayload) => this.grpcEmit(EventType.EVENT_TYPE_ERROR, payload) + const listener = (payload: EventErrorPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_ERROR, payload) this.puppet.on('error', listener) const off = () => this.puppet.off('error', listener) offCallbackList.push(off) break } case 'heartbeat': { - const listener = (payload: EventHeartbeatPayload) => this.grpcEmit(EventType.EVENT_TYPE_HEARTBEAT, payload) + const listener = (payload: EventHeartbeatPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_HEARTBEAT, payload) this.puppet.on('heartbeat', listener) const off = () => this.puppet.off('heartbeat', listener) offCallbackList.push(off) break } case 'friendship': { - const listener = (payload: EventFriendshipPayload) => this.grpcEmit(EventType.EVENT_TYPE_FRIENDSHIP, payload) + const listener = (payload: EventFriendshipPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_FRIENDSHIP, payload) this.puppet.on('friendship', listener) const off = () => this.puppet.off('friendship', listener) offCallbackList.push(off) break } case 'login': { - const listener = (payload: EventLoginPayload) => this.grpcEmit(EventType.EVENT_TYPE_LOGIN, payload) + const listener = (payload: EventLoginPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_LOGIN, payload) this.puppet.on('login', listener) const off = () => this.puppet.off('login', listener) offCallbackList.push(off) break } case 'logout': { - const listener = (payload: EventLogoutPayload) => this.grpcEmit(EventType.EVENT_TYPE_LOGOUT, payload) + const listener = (payload: EventLogoutPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_LOGOUT, payload) this.puppet.on('logout', listener) const off = () => this.puppet.off('logout', listener) offCallbackList.push(off) break } case 'message': { - const listener = (payload: EventMessagePayload) => this.grpcEmit(EventType.EVENT_TYPE_MESSAGE, payload) + const listener = (payload: EventMessagePayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_MESSAGE, payload) this.puppet.on('message', listener) const off = () => this.puppet.off('message', listener) offCallbackList.push(off) break } case 'ready': { - const listener = (payload: EventReadyPayload) => this.grpcEmit(EventType.EVENT_TYPE_READY, payload) + const listener = (payload: EventReadyPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_READY, payload) this.puppet.on('ready', listener) const off = () => this.puppet.off('ready', listener) offCallbackList.push(off) break } case 'room-invite': { - const listener = (payload: EventRoomInvitePayload) => this.grpcEmit(EventType.EVENT_TYPE_ROOM_INVITE, payload) + const listener = (payload: EventRoomInvitePayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_ROOM_INVITE, payload) this.puppet.on('room-invite', listener) const off = () => this.puppet.off('room-invite', listener) offCallbackList.push(off) break } case 'room-join': { - const listener = (payload: EventRoomJoinPayload) => this.grpcEmit(EventType.EVENT_TYPE_ROOM_JOIN, payload) + const listener = (payload: EventRoomJoinPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_ROOM_JOIN, payload) this.puppet.on('room-join', listener) const off = () => this.puppet.off('room-join', listener) offCallbackList.push(off) break } case 'room-leave': { - const listener = (payload: EventRoomLeavePayload) => this.grpcEmit(EventType.EVENT_TYPE_ROOM_LEAVE, payload) + const listener = (payload: EventRoomLeavePayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_ROOM_LEAVE, payload) this.puppet.on('room-leave', listener) const off = () => this.puppet.off('room-leave', listener) offCallbackList.push(off) break } case 'room-topic': { - const listener = (payload: EventRoomTopicPayload) => this.grpcEmit(EventType.EVENT_TYPE_ROOM_TOPIC, payload) + const listener = (payload: EventRoomTopicPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_ROOM_TOPIC, payload) this.puppet.on('room-topic', listener) const off = () => this.puppet.off('room-topic', listener) offCallbackList.push(off) break } case 'scan': { - const listener = (payload: EventScanPayload) => this.grpcEmit(EventType.EVENT_TYPE_SCAN, payload) + const listener = (payload: EventScanPayload) => this.grpcEmit(grpcPuppet.EventType.EVENT_TYPE_SCAN, payload) this.puppet.on('scan', listener) const off = () => this.puppet.off('scan', listener) offCallbackList.push(off) diff --git a/src/server/grpc-error.ts b/src/server/grpc-error.ts index 48978ae3..6efcc8af 100644 --- a/src/server/grpc-error.ts +++ b/src/server/grpc-error.ts @@ -1,8 +1,7 @@ import { grpc } from 'wechaty-grpc' - import { log, -} from '../config' +} from 'wechaty-puppet' export function grpcError ( method : string, diff --git a/src/server/puppet-implementation.ts b/src/server/puppet-implementation.ts index b2d76e60..b27b5416 100644 --- a/src/server/puppet-implementation.ts +++ b/src/server/puppet-implementation.ts @@ -1,70 +1,15 @@ import { grpc, - IPuppetServer, - ContactAliasResponse, - ContactAvatarResponse, - ContactListResponse, - ContactPayloadResponse, - ContactSelfNameResponse, - ContactSelfQRCodeResponse, - ContactSelfSignatureResponse, - DingResponse, - DirtyPayloadResponse, - FriendshipAcceptResponse, - FriendshipAddResponse, - FriendshipPayloadResponse, - FriendshipSearchPhoneResponse, - FriendshipSearchWeixinResponse, - LogoutResponse, - MessageContactResponse, - MessageFileResponse, - MessageForwardResponse, - MessageMiniProgramResponse, - MessagePayloadResponse, - MessageRecallResponse, - MessageSendContactResponse, - MessageSendFileResponse, - MessageSendTextResponse, - MessageUrlResponse, - RoomAddResponse, - RoomAnnounceResponse, - RoomAvatarResponse, - RoomCreateResponse, - RoomDelResponse, - RoomInvitationAcceptResponse, - RoomInvitationPayloadResponse, - RoomListResponse, - RoomMemberListResponse, - RoomMemberPayloadResponse, - RoomPayloadResponse, - RoomQRCodeResponse, - RoomQuitResponse, - RoomTopicResponse, - StartResponse, - StopResponse, - TagContactAddResponse, - TagContactDeleteResponse, - TagContactListResponse, - TagContactRemoveResponse, - VersionResponse, - MessageSendMiniProgramResponse, - MessageImageResponse, - + puppet as pbPuppet, StringValue, - EventType, - MessageSendUrlResponse, - MessageTypeMap, - ContactPhoneResponse, - ContactDescriptionResponse, - ContactCorporationRemarkResponse, - MessageSendFileStreamResponse, - MessageImageStreamResponse, - MessageFileStreamResponse, } from 'wechaty-grpc' import { + log, FileBox, + Puppet, + FriendshipPayloadReceive, MiniProgramPayload, UrlLinkPayload, @@ -80,19 +25,15 @@ import { import { packFileBoxToPb, unpackConversationIdFileBoxArgsFromPb, -} from '../file-box-stream/mod' - -import { - log, -} from '../config' +} from '../file-box-stream/mod.js' -import { grpcError } from './grpc-error' -import { EventStreamManager } from './event-stream-manager' -import { serializeFileBox } from './serialize-file-box' +import { grpcError } from './grpc-error.js' +import { EventStreamManager } from './event-stream-manager.js' +import { serializeFileBox } from './serialize-file-box.js' function puppetImplementation ( puppet: Puppet, -): IPuppetServer { +): pbPuppet.IPuppetServer { /** * Save scan payload to send it to the puppet-service right after connected (if needed) @@ -101,7 +42,7 @@ function puppetImplementation ( */ let scanPayload: undefined | EventScanPayload let readyPayload: undefined | EventReadyPayload - let readyTimeout: undefined | NodeJS.Timeout + let readyTimeout: undefined | ReturnType puppet .on('scan', payload => { scanPayload = payload }) @@ -115,13 +56,13 @@ function puppetImplementation ( .on('login', _ => { scanPayload = undefined readyTimeout = setTimeout(() => { - readyPayload && eventStreamManager.grpcEmit(EventType.EVENT_TYPE_READY, readyPayload) + readyPayload && eventStreamManager.grpcEmit(pbPuppet.EventType.EVENT_TYPE_READY, readyPayload) }, 5 * 1000) }) const eventStreamManager = new EventStreamManager(puppet) - const puppetServerImpl: IPuppetServer = { + const puppetServerImpl: pbPuppet.IPuppetServer = { contactAlias: async (call, callback) => { log.verbose('PuppetServiceImpl', 'contactAlias()') @@ -136,9 +77,9 @@ function puppetImplementation ( if (aliasWrapper) { try { await puppet.contactAlias(id, aliasWrapper.getValue()) - return callback(null, new ContactAliasResponse()) + return callback(null, new pbPuppet.ContactAliasResponse()) } catch (e) { - return grpcError('contactAlias', e, callback) + return grpcError('contactAlias', (e as Error), callback) } } } @@ -152,12 +93,12 @@ function puppetImplementation ( const aliasWrapper = new StringValue() aliasWrapper.setValue(alias) - const response = new ContactAliasResponse() + const response = new pbPuppet.ContactAliasResponse() response.setAlias(aliasWrapper) return callback(null, response) } catch (e) { - return grpcError('contactAlias', e, callback) + return grpcError('contactAlias', (e as Error), callback) } }, @@ -179,10 +120,10 @@ function puppetImplementation ( ) await puppet.contactAvatar(id, fileBox) - return callback(null, new ContactAvatarResponse()) + return callback(null, new pbPuppet.ContactAvatarResponse()) } } catch (e) { - return grpcError('contactAvatar', e, callback) + return grpcError('contactAvatar', (e as Error), callback) } /** @@ -196,12 +137,12 @@ function puppetImplementation ( JSON.stringify(fileBox) ) - const response = new ContactAvatarResponse() + const response = new pbPuppet.ContactAvatarResponse() response.setFilebox(fileBoxWrapper) return callback(null, response) } catch (e) { - return grpcError('contactAvatar', e, callback) + return grpcError('contactAvatar', (e as Error), callback) } }, @@ -216,9 +157,9 @@ function puppetImplementation ( corporationRemark = corporationRemarkWrapper.getValue() } await puppet.contactCorporationRemark(contactId, corporationRemark) - return callback(null, new ContactCorporationRemarkResponse()) + return callback(null, new pbPuppet.ContactCorporationRemarkResponse()) } catch (e) { - return grpcError('contactCorporationRemark', e, callback) + return grpcError('contactCorporationRemark', (e as Error), callback) } }, @@ -234,9 +175,9 @@ function puppetImplementation ( description = descriptionWrapper.getValue() } await puppet.contactDescription(contactId, description) - return callback(null, new ContactDescriptionResponse()) + return callback(null, new pbPuppet.ContactDescriptionResponse()) } catch (e) { - return grpcError('contactDescription', e, callback) + return grpcError('contactDescription', (e as Error), callback) } }, @@ -247,12 +188,12 @@ function puppetImplementation ( try { const idList = await puppet.contactList() - const response = new ContactListResponse() + const response = new pbPuppet.ContactListResponse() response.setIdsList(idList) return callback(null, response) } catch (e) { - return grpcError('contactList', e, callback) + return grpcError('contactList', (e as Error), callback) } }, @@ -264,7 +205,7 @@ function puppetImplementation ( try { const payload = await puppet.contactPayload(id) - const response = new ContactPayloadResponse() + const response = new pbPuppet.ContactPayloadResponse() response.setAddress(payload.address || '') response.setAlias(payload.alias || '') response.setAvatar(payload.avatar) @@ -286,7 +227,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('contactPayload', e, callback) + return grpcError('contactPayload', (e as Error), callback) } }, @@ -298,9 +239,9 @@ function puppetImplementation ( const phoneList = call.request.getPhoneListList() await puppet.contactPhone(contactId, phoneList) - return callback(null, new ContactPhoneResponse()) + return callback(null, new pbPuppet.ContactPhoneResponse()) } catch (e) { - return grpcError('contactPhone', e, callback) + return grpcError('contactPhone', (e as Error), callback) } }, @@ -311,10 +252,10 @@ function puppetImplementation ( const name = call.request.getName() await puppet.contactSelfName(name) - return callback(null, new ContactSelfNameResponse()) + return callback(null, new pbPuppet.ContactSelfNameResponse()) } catch (e) { - return grpcError('contactSelfName', e, callback) + return grpcError('contactSelfName', (e as Error), callback) } }, @@ -325,13 +266,13 @@ function puppetImplementation ( try { const qrcode = await puppet.contactSelfQRCode() - const response = new ContactSelfQRCodeResponse() + const response = new pbPuppet.ContactSelfQRCodeResponse() response.setQrcode(qrcode) return callback(null, response) } catch (e) { - return grpcError('contactSelfQRCode', e, callback) + return grpcError('contactSelfQRCode', (e as Error), callback) } }, @@ -343,10 +284,10 @@ function puppetImplementation ( const signature = call.request.getSignature() await puppet.contactSelfSignature(signature) - return callback(null, new ContactSelfSignatureResponse()) + return callback(null, new pbPuppet.ContactSelfSignatureResponse()) } catch (e) { - return grpcError('contactSelfSignature', e, callback) + return grpcError('contactSelfSignature', (e as Error), callback) } }, @@ -357,10 +298,10 @@ function puppetImplementation ( try { const data = call.request.getData() await puppet.ding(data) - return callback(null, new DingResponse()) + return callback(null, new pbPuppet.DingResponse()) } catch (e) { - return grpcError('ding', e, callback) + return grpcError('ding', (e as Error), callback) } }, @@ -372,9 +313,9 @@ function puppetImplementation ( const type: PayloadType = call.request.getType() await puppet.dirtyPayload(type, id) - return callback(null, new DirtyPayloadResponse()) + return callback(null, new pbPuppet.DirtyPayloadResponse()) } catch (e) { - return grpcError('dirtyPayload', e, callback) + return grpcError('dirtyPayload', (e as Error), callback) } }, @@ -414,7 +355,7 @@ function puppetImplementation ( * If `scanPayload` is not undefined, then we emit it to downstream immediatelly */ if (scanPayload) { - eventStreamManager.grpcEmit(EventType.EVENT_TYPE_SCAN, scanPayload) + eventStreamManager.grpcEmit(pbPuppet.EventType.EVENT_TYPE_SCAN, scanPayload) } }, @@ -424,10 +365,10 @@ function puppetImplementation ( try { const id = call.request.getId() await puppet.friendshipAccept(id) - return callback(null, new FriendshipAcceptResponse()) + return callback(null, new pbPuppet.FriendshipAcceptResponse()) } catch (e) { - return grpcError('friendshipAccept', e, callback) + return grpcError('friendshipAccept', (e as Error), callback) } }, @@ -451,10 +392,10 @@ function puppetImplementation ( } await puppet.friendshipAdd(contactId, friendshipAddOptions) - return callback(null, new FriendshipAddResponse()) + return callback(null, new pbPuppet.FriendshipAddResponse()) } catch (e) { - return grpcError('friendshipAdd', e, callback) + return grpcError('friendshipAdd', (e as Error), callback) } }, @@ -466,7 +407,7 @@ function puppetImplementation ( const payload = await puppet.friendshipPayload(id) const payloadReceive = payload as FriendshipPayloadReceive - const response = new FriendshipPayloadResponse() + const response = new pbPuppet.FriendshipPayloadResponse() response.setContactId(payload.contactId) response.setHello(payload.hello || '') @@ -479,7 +420,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('friendshipPayload', e, callback) + return grpcError('friendshipPayload', (e as Error), callback) } }, @@ -490,7 +431,7 @@ function puppetImplementation ( const phone = call.request.getPhone() const contactId = await puppet.friendshipSearchPhone(phone) - const response = new FriendshipSearchPhoneResponse() + const response = new pbPuppet.FriendshipSearchPhoneResponse() if (contactId) { const contactIdWrapper = new StringValue() @@ -501,7 +442,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('friendshipSearchPhone', e, callback) + return grpcError('friendshipSearchPhone', (e as Error), callback) } }, @@ -512,7 +453,7 @@ function puppetImplementation ( const weixin = call.request.getWeixin() const contactId = await puppet.friendshipSearchWeixin(weixin) - const response = new FriendshipSearchWeixinResponse() + const response = new pbPuppet.FriendshipSearchWeixinResponse() if (contactId) { const contactIdWrapper = new StringValue() @@ -523,7 +464,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('friendshipSearchWeixin', e, callback) + return grpcError('friendshipSearchWeixin', (e as Error), callback) } }, @@ -534,10 +475,10 @@ function puppetImplementation ( try { await puppet.logout() - return callback(null, new LogoutResponse()) + return callback(null, new pbPuppet.LogoutResponse()) } catch (e) { - return grpcError('logout', e, callback) + return grpcError('logout', (e as Error), callback) } }, @@ -549,13 +490,13 @@ function puppetImplementation ( const contactId = await puppet.messageContact(id) - const response = new MessageContactResponse() + const response = new pbPuppet.MessageContactResponse() response.setId(contactId) return callback(null, response) } catch (e) { - return grpcError('messageContact', e, callback) + return grpcError('messageContact', (e as Error), callback) } }, @@ -571,13 +512,13 @@ function puppetImplementation ( const fileBox = await puppet.messageFile(id) - const response = new MessageFileResponse() + const response = new pbPuppet.MessageFileResponse() response.setFilebox(await serializeFileBox(fileBox)) return callback(null, response) } catch (e) { - return grpcError('messageFile', e, callback) + return grpcError('messageFile', (e as Error), callback) } }, @@ -588,14 +529,14 @@ function puppetImplementation ( const id = call.request.getId() const fileBox = await puppet.messageFile(id) - const response = await packFileBoxToPb(MessageFileStreamResponse)(fileBox) + const response = await packFileBoxToPb(pbPuppet.MessageFileStreamResponse)(fileBox) - response.on('error', e => call.destroy(e)) + response.on('error', e => call.destroy(e as Error)) response.pipe(call) } catch (e) { - log.error('PuppetServiceImpl', 'grpcError() messageFileStream() rejection: %s', e && e.message) - call.destroy(e) + log.error('PuppetServiceImpl', 'grpcError() messageFileStream() rejection: %s', e && (e as Error).message) + call.destroy(e as Error) } }, @@ -608,7 +549,7 @@ function puppetImplementation ( const id = await puppet.messageForward(conversationId, messageId) - const response = new MessageForwardResponse() + const response = new pbPuppet.MessageForwardResponse() if (id) { const idWrapper = new StringValue() idWrapper.setValue(id) @@ -618,7 +559,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('messageForward', e, callback) + return grpcError('messageForward', (e as Error), callback) } }, @@ -635,13 +576,13 @@ function puppetImplementation ( const fileBox = await puppet.messageImage(id, type as number as ImageType) - const response = new MessageImageResponse() + const response = new pbPuppet.MessageImageResponse() response.setFilebox(await serializeFileBox(fileBox)) return callback(null, response) } catch (e) { - return grpcError('messageImage', e, callback) + return grpcError('messageImage', (e as Error), callback) } }, @@ -653,14 +594,14 @@ function puppetImplementation ( const type = call.request.getType() const fileBox = await puppet.messageImage(id, type as number as ImageType) - const response = await packFileBoxToPb(MessageImageStreamResponse)(fileBox) + const response = await packFileBoxToPb(pbPuppet.MessageImageStreamResponse)(fileBox) - response.on('error', e => call.destroy(e)) + response.on('error', e => call.destroy(e as Error)) response.pipe(call) } catch (e) { - log.error('PuppetServiceImpl', 'grpcError() messageImageStream() rejection: %s', e && e.message) - call.destroy(e) + log.error('PuppetServiceImpl', 'grpcError() messageImageStream() rejection: %s', (e as Error) && (e as Error).message) + call.destroy(e as Error) } }, @@ -672,13 +613,13 @@ function puppetImplementation ( const payload = await puppet.messageMiniProgram(id) - const response = new MessageMiniProgramResponse() + const response = new pbPuppet.MessageMiniProgramResponse() response.setMiniProgram(JSON.stringify(payload)) return callback(null, response) } catch (e) { - return grpcError('messageMiniProgram', e, callback) + return grpcError('messageMiniProgram', (e as Error), callback) } }, @@ -694,7 +635,7 @@ function puppetImplementation ( ? payload.mentionIdList || [] : [] - const response = new MessagePayloadResponse() + const response = new pbPuppet.MessagePayloadResponse() response.setFilename(payload.filename || '') response.setFromId(payload.fromId || '') response.setId(payload.id) @@ -703,12 +644,12 @@ function puppetImplementation ( response.setText(payload.text || '') response.setTimestamp(Math.floor(payload.timestamp)) response.setToId(payload.toId || '') - response.setType(payload.type as MessageTypeMap[keyof MessageTypeMap]) + response.setType(payload.type as pbPuppet.MessageTypeMap[keyof pbPuppet.MessageTypeMap]) return callback(null, response) } catch (e) { - return grpcError('messagePayload', e, callback) + return grpcError('messagePayload', (e as Error), callback) } }, @@ -720,13 +661,13 @@ function puppetImplementation ( const success = await puppet.messageRecall(id) - const response = new MessageRecallResponse() + const response = new pbPuppet.MessageRecallResponse() response.setSuccess(success) return callback(null, response) } catch (e) { - return grpcError('messageRecall', e, callback) + return grpcError('messageRecall', (e as Error), callback) } }, @@ -739,7 +680,7 @@ function puppetImplementation ( const messageId = await puppet.messageSendContact(conversationId, contactId) - const response = new MessageSendContactResponse() + const response = new pbPuppet.MessageSendContactResponse() if (messageId) { const idWrapper = new StringValue() @@ -750,7 +691,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('messageSendContact', e, callback) + return grpcError('messageSendContact', (e as Error), callback) } }, @@ -765,7 +706,7 @@ function puppetImplementation ( const messageId = await puppet.messageSendFile(conversationId, fileBox) - const response = new MessageSendFileResponse() + const response = new pbPuppet.MessageSendFileResponse() if (messageId) { const idWrapper = new StringValue() @@ -776,7 +717,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('messageSendFile', e, callback) + return grpcError('messageSendFile', (e as Error), callback) } }, @@ -790,7 +731,7 @@ function puppetImplementation ( const messageId = await puppet.messageSendFile(conversationId, fileBox) - const response = new MessageSendFileStreamResponse() + const response = new pbPuppet.MessageSendFileStreamResponse() if (messageId) { const idWrapper = new StringValue() @@ -801,7 +742,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('messageSendFileStream', e, callback) + return grpcError('messageSendFileStream', (e as Error), callback) } }, @@ -816,7 +757,7 @@ function puppetImplementation ( const messageId = await puppet.messageSendMiniProgram(conversationId, payload) - const response = new MessageSendMiniProgramResponse() + const response = new pbPuppet.MessageSendMiniProgramResponse() if (messageId) { const idWrapper = new StringValue() @@ -827,7 +768,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('messageSendMiniProgram', e, callback) + return grpcError('messageSendMiniProgram', (e as Error), callback) } }, @@ -841,7 +782,7 @@ function puppetImplementation ( const messageId = await puppet.messageSendText(conversationId, text, mentionIdList) - const response = new MessageSendTextResponse() + const response = new pbPuppet.MessageSendTextResponse() if (messageId) { const idWrapper = new StringValue() @@ -852,7 +793,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('messageSendText', e, callback) + return grpcError('messageSendText', (e as Error), callback) } }, @@ -867,7 +808,7 @@ function puppetImplementation ( const messageId = await puppet.messageSendUrl(conversationId, payload) - const response = new MessageSendUrlResponse() + const response = new pbPuppet.MessageSendUrlResponse() if (messageId) { const idWrapper = new StringValue() @@ -878,7 +819,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('messageSendUrl', e, callback) + return grpcError('messageSendUrl', (e as Error), callback) } }, @@ -889,13 +830,13 @@ function puppetImplementation ( const id = call.request.getId() const payload = await puppet.messageUrl(id) - const response = new MessageUrlResponse() + const response = new pbPuppet.MessageUrlResponse() response.setUrlLink(JSON.stringify(payload)) return callback(null, response) } catch (e) { - return grpcError('messageUrl', e, callback) + return grpcError('messageUrl', (e as Error), callback) } }, @@ -909,10 +850,10 @@ function puppetImplementation ( await puppet.roomAdd(roomId, contactId, inviteOnly) - return callback(null, new RoomAddResponse()) + return callback(null, new pbPuppet.RoomAddResponse()) } catch (e) { - return grpcError('roomAdd', e, callback) + return grpcError('roomAdd', (e as Error), callback) } }, @@ -932,7 +873,7 @@ function puppetImplementation ( const text = textWrapper.getValue() await puppet.roomAnnounce(roomId, text) - return callback(null, new RoomAnnounceResponse()) + return callback(null, new pbPuppet.RoomAnnounceResponse()) } } @@ -944,13 +885,13 @@ function puppetImplementation ( const textWrapper = new StringValue() textWrapper.setValue(text) - const response = new RoomAnnounceResponse() + const response = new pbPuppet.RoomAnnounceResponse() response.setText(textWrapper) return callback(null, response) } catch (e) { - return grpcError('roomAnnounce', e, callback) + return grpcError('roomAnnounce', (e as Error), callback) } }, @@ -962,13 +903,13 @@ function puppetImplementation ( const fileBox = await puppet.roomAvatar(roomId) - const response = new RoomAvatarResponse() + const response = new pbPuppet.RoomAvatarResponse() response.setFilebox(await serializeFileBox(fileBox)) return callback(null, response) } catch (e) { - return grpcError('roomAvatar', e, callback) + return grpcError('roomAvatar', (e as Error), callback) } }, @@ -981,13 +922,13 @@ function puppetImplementation ( const roomId = await puppet.roomCreate(contactIdList, topic) - const response = new RoomCreateResponse() + const response = new pbPuppet.RoomCreateResponse() response.setId(roomId) return callback(null, response) } catch (e) { - return grpcError('roomCreate', e, callback) + return grpcError('roomCreate', (e as Error), callback) } }, @@ -1000,10 +941,10 @@ function puppetImplementation ( await puppet.roomDel(roomId, contactId) - return callback(null, new RoomDelResponse()) + return callback(null, new pbPuppet.RoomDelResponse()) } catch (e) { - return grpcError('roomDel', e, callback) + return grpcError('roomDel', (e as Error), callback) } }, @@ -1015,10 +956,10 @@ function puppetImplementation ( await puppet.roomInvitationAccept(id) - return callback(null, new RoomInvitationAcceptResponse()) + return callback(null, new pbPuppet.RoomInvitationAcceptResponse()) } catch (e) { - return grpcError('roomInvitationAccept', e, callback) + return grpcError('roomInvitationAccept', (e as Error), callback) } }, @@ -1038,7 +979,7 @@ function puppetImplementation ( const payload = JSON.parse(jsonText) as RoomInvitationPayload await puppet.roomInvitationPayload(roomInvitationId, payload) - return callback(null, new RoomInvitationPayloadResponse()) + return callback(null, new pbPuppet.RoomInvitationPayloadResponse()) } } @@ -1047,7 +988,7 @@ function puppetImplementation ( */ const payload = await puppet.roomInvitationPayload(roomInvitationId) - const response = new RoomInvitationPayloadResponse() + const response = new pbPuppet.RoomInvitationPayloadResponse() response.setAvatar(payload.avatar) response.setId(payload.id) response.setInvitation(payload.invitation) @@ -1061,7 +1002,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('roomInvitationPayload', e, callback) + return grpcError('roomInvitationPayload', (e as Error), callback) } }, @@ -1072,13 +1013,13 @@ function puppetImplementation ( try { const roomIdList = await puppet.roomList() - const response = new RoomListResponse() + const response = new pbPuppet.RoomListResponse() response.setIdsList(roomIdList) return callback(null, response) } catch (e) { - return grpcError('roomList', e, callback) + return grpcError('roomList', (e as Error), callback) } }, @@ -1090,13 +1031,13 @@ function puppetImplementation ( const roomMemberIdList = await puppet.roomMemberList(roomId) - const response = new RoomMemberListResponse() + const response = new pbPuppet.RoomMemberListResponse() response.setMemberIdsList(roomMemberIdList) return callback(null, response) } catch (e) { - return grpcError('roomMemberList', e, callback) + return grpcError('roomMemberList', (e as Error), callback) } }, @@ -1109,7 +1050,7 @@ function puppetImplementation ( const payload = await puppet.roomMemberPayload(roomId, memberId) - const response = new RoomMemberPayloadResponse() + const response = new pbPuppet.RoomMemberPayloadResponse() response.setAvatar(payload.avatar) response.setId(payload.id) @@ -1120,7 +1061,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('roomMemberPayload', e, callback) + return grpcError('roomMemberPayload', (e as Error), callback) } }, @@ -1132,7 +1073,7 @@ function puppetImplementation ( const payload = await puppet.roomPayload(roomId) - const response = new RoomPayloadResponse() + const response = new pbPuppet.RoomPayloadResponse() response.setAdminIdsList(payload.adminIdList) response.setAvatar(payload.avatar || '') response.setId(payload.id) @@ -1143,7 +1084,7 @@ function puppetImplementation ( return callback(null, response) } catch (e) { - return grpcError('roomPayload', e, callback) + return grpcError('roomPayload', (e as Error), callback) } }, @@ -1155,13 +1096,13 @@ function puppetImplementation ( const qrcode = await puppet.roomQRCode(roomId) - const response = new RoomQRCodeResponse() + const response = new pbPuppet.RoomQRCodeResponse() response.setQrcode(qrcode) return callback(null, response) } catch (e) { - return grpcError('roomQRCode', e, callback) + return grpcError('roomQRCode', (e as Error), callback) } }, @@ -1173,10 +1114,10 @@ function puppetImplementation ( await puppet.roomQuit(roomId) - return callback(null, new RoomQuitResponse()) + return callback(null, new pbPuppet.RoomQuitResponse()) } catch (e) { - return grpcError('roomQuit', e, callback) + return grpcError('roomQuit', (e as Error), callback) } }, @@ -1196,7 +1137,7 @@ function puppetImplementation ( await puppet.roomTopic(roomId, topic) - return callback(null, new RoomTopicResponse()) + return callback(null, new pbPuppet.RoomTopicResponse()) } } @@ -1209,13 +1150,13 @@ function puppetImplementation ( const topicWrapper = new StringValue() topicWrapper.setValue(topic) - const response = new RoomTopicResponse() + const response = new pbPuppet.RoomTopicResponse() response.setTopic(topicWrapper) return callback(null, response) } catch (e) { - return grpcError('roomTopic', e, callback) + return grpcError('roomTopic', (e as Error), callback) } }, @@ -1226,10 +1167,10 @@ function puppetImplementation ( try { await puppet.start() - return callback(null, new StartResponse()) + return callback(null, new pbPuppet.StartResponse()) } catch (e) { - return grpcError('start', e, callback) + return grpcError('start', (e as Error), callback) } }, @@ -1248,10 +1189,10 @@ function puppetImplementation ( await puppet.stop() readyPayload = undefined - return callback(null, new StopResponse()) + return callback(null, new pbPuppet.StopResponse()) } catch (e) { - return grpcError('stop', e, callback) + return grpcError('stop', (e as Error), callback) } }, @@ -1264,10 +1205,10 @@ function puppetImplementation ( await puppet.tagContactAdd(tagId, contactId) - return callback(null, new TagContactAddResponse()) + return callback(null, new pbPuppet.TagContactAddResponse()) } catch (e) { - return grpcError('tagContactAdd', e, callback) + return grpcError('tagContactAdd', (e as Error), callback) } }, @@ -1279,10 +1220,10 @@ function puppetImplementation ( await puppet.tagContactDelete(tagId) - return callback(null, new TagContactDeleteResponse()) + return callback(null, new pbPuppet.TagContactDeleteResponse()) } catch (e) { - return grpcError('tagContactDelete', e, callback) + return grpcError('tagContactDelete', (e as Error), callback) } }, @@ -1300,10 +1241,10 @@ function puppetImplementation ( const tagIdList = await puppet.tagContactList(contactId) - const response = new TagContactListResponse() + const response = new pbPuppet.TagContactListResponse() response.setIdsList(tagIdList) - return callback(null, new TagContactListResponse()) + return callback(null, new pbPuppet.TagContactListResponse()) } /** @@ -1311,13 +1252,13 @@ function puppetImplementation ( */ const tagIdList = await puppet.tagContactList() - const response = new TagContactListResponse() + const response = new pbPuppet.TagContactListResponse() response.setIdsList(tagIdList) return callback(null, response) } catch (e) { - return grpcError('tagContactList', e, callback) + return grpcError('tagContactList', (e as Error), callback) } }, @@ -1330,10 +1271,10 @@ function puppetImplementation ( await puppet.tagContactRemove(tagId, contactId) - return callback(null, new TagContactRemoveResponse()) + return callback(null, new pbPuppet.TagContactRemoveResponse()) } catch (e) { - return grpcError('tagContactRemove', e, callback) + return grpcError('tagContactRemove', (e as Error), callback) } }, @@ -1344,13 +1285,13 @@ function puppetImplementation ( try { const version = puppet.version() - const response = new VersionResponse() + const response = new pbPuppet.VersionResponse() response.setVersion(version) return callback(null, response) } catch (e) { - return grpcError('version', e, callback) + return grpcError('version', (e as Error), callback) } }, diff --git a/src/server/puppet-server.spec.ts b/src/server/puppet-server.spec.ts index 56ce9c1d..17855cce 100644 --- a/src/server/puppet-server.spec.ts +++ b/src/server/puppet-server.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' @@ -7,7 +7,7 @@ import { Puppet } from 'wechaty-puppet' import { PuppetServer, PuppetServerOptions, -} from './puppet-server' +} from './puppet-server.js' test('version()', async t => { const options: PuppetServerOptions = { diff --git a/src/server/puppet-server.ts b/src/server/puppet-server.ts index 5fa4e836..38b7727d 100644 --- a/src/server/puppet-server.ts +++ b/src/server/puppet-server.ts @@ -2,29 +2,28 @@ import util from 'util' import { Puppet, + log, } from 'wechaty-puppet' - import { grpc, - PuppetService, -} from 'wechaty-grpc' + puppet as grpcPuppet, +} from 'wechaty-grpc' import { envVars, - log, VERSION, GRPC_OPTIONS, -} from '../config' +} from '../config.js' import { puppetImplementation, -} from './puppet-implementation' +} from './puppet-implementation.js' import { authImplToken, -} from '../auth/mod' +} from '../auth/mod.js' import { TLS_INSECURE_SERVER_CERT, TLS_INSECURE_SERVER_KEY, -} from '../auth/ca' +} from '../auth/ca.js' export interface PuppetServerOptions { endpoint : string, @@ -70,7 +69,7 @@ export class PuppetServer { this.grpcServer = new grpc.Server(GRPC_OPTIONS) this.grpcServer.addService( - PuppetService, + grpcPuppet.PuppetService, puppetImplAuth, ) diff --git a/src/version.spec.ts b/src/version.spec.ts deleted file mode 100755 index efc051a1..00000000 --- a/src/version.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env ts-node - -import { test } from 'tstest' - -import { VERSION } from './version' - -test('Make sure the VERSION is fresh in source code', async t => { - t.equal(VERSION, '0.0.0', 'version should be 0.0.0 in source code, only updated before publish to NPM') -}) diff --git a/src/version.ts b/src/version.ts deleted file mode 100644 index c36f2c5a..00000000 --- a/src/version.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * This file will be overwrite when we publish NPM module - * by scripts/generate_version.ts - */ - -export const VERSION = '0.0.0' diff --git a/tests/fixtures/smoke-testing.ts b/tests/fixtures/smoke-testing.ts index e9dcf10a..02298cac 100644 --- a/tests/fixtures/smoke-testing.ts +++ b/tests/fixtures/smoke-testing.ts @@ -1,14 +1,10 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { VERSION, PuppetService, } from 'wechaty-puppet-service' async function main () { - if (VERSION === '0.0.0') { - throw new Error('version should be set before publishing') - } - const puppetService = new PuppetService() const version = puppetService.version() @@ -22,6 +18,12 @@ async function main () { // } finally { // await bot.stop() // } + + if (VERSION === '0.0.0') { + throw new Error('version should be set before publishing') + } + + console.info('Wechaty Puppet Service v' + VERSION + ' passed.') return 0 } diff --git a/tests/grpc-client.spec.ts b/tests/grpc-client.spec.ts index d47d2d62..975ef1cd 100755 --- a/tests/grpc-client.spec.ts +++ b/tests/grpc-client.spec.ts @@ -1,16 +1,17 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test } from 'tstest' -import { PuppetOptions } from 'wechaty-puppet' +import { + PuppetOptions, + log, +} from 'wechaty-puppet' import PuppetMock from 'wechaty-puppet-mock' -import { log } from '../src/config' - -import { GrpcClient } from '../src/client/grpc-client' +import { GrpcClient } from '../src/client/grpc-client.js' import { PuppetServer, PuppetServerOptions, -} from '../src/mod' +} from '../src/mod.js' test('GrpcClient with TLS and valid token', async t => { const TOKEN = 'insecure_UUIDv4' diff --git a/tests/integration.spec.ts b/tests/integration.spec.ts index 706fb37e..6ec69911 100755 --- a/tests/integration.spec.ts +++ b/tests/integration.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm import { test, @@ -16,7 +16,7 @@ import { PuppetService, PuppetServer, PuppetServerOptions, -} from '../src/mod' +} from '../src/mod.js' test('integration testing', async t => { const TOKEN = 'insecure_UUIDv4' diff --git a/tests/performance.spec.ts b/tests/performance.spec.ts index 7a0c8786..5cea7036 100755 --- a/tests/performance.spec.ts +++ b/tests/performance.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env ts-node +#!/usr/bin/env node --no-warnings --loader ts-node/esm /** * Software performance testing @@ -13,11 +13,6 @@ import { sinon, } from 'tstest' -import { - PuppetService, - PuppetServer, - PuppetServerOptions, -} from '../src/mod' import { PuppetOptions, ContactPayload, @@ -30,6 +25,12 @@ import { PuppetMock, } from 'wechaty-puppet-mock' +import { + PuppetService, + PuppetServer, + PuppetServerOptions, +} from '../src/mod.js' + const idToName = (id: string) => { return `name of ${id}` } diff --git a/tsconfig.cjs.json b/tsconfig.cjs.json new file mode 100644 index 00000000..8693cd00 --- /dev/null +++ b/tsconfig.cjs.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "CommonJS", + "outDir": "dist/cjs", + }, +} diff --git a/tsconfig.json b/tsconfig.json index 728a055a..57358d30 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,10 @@ { "extends": "@chatie/tsconfig", "compilerOptions": { - "outDir": "dist", + "outDir": "dist/esm", + "target": "es2020", + "module": "es2020", + "moduleResolution": "node", }, "exclude": [ "node_modules/",