Add vite config. Add prettier (#7)

This commit is contained in:
Ildar Galeev 2023-11-02 14:27:11 +03:00 committed by GitHub
parent e8afd660ca
commit 397aa83ca5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 2910 additions and 7073 deletions

View File

@ -1,5 +0,0 @@
{
"presets": [
["@babel/preset-env"]
]
}

View File

@ -12,6 +12,7 @@ jobs:
- uses: actions/checkout@v3
- uses: valitydev/action-frontend/setup@v1
- run: npm ci
- run: npm run prettier:check
- run: npm run build
- uses: valitydev/action-frontend/publish@v1
with:

View File

@ -12,4 +12,5 @@ jobs:
- uses: actions/checkout@v3
- uses: valitydev/action-frontend/setup@v1
- run: npm ci
- run: npm run prettier:check
- run: npm run build

1
.npmrc Normal file
View File

@ -0,0 +1 @@
save-exact=true

5
.prettierignore Normal file
View File

@ -0,0 +1,5 @@
package.json
package-lock.json
node_modules
.github
dist

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
{
"printWidth": 100,
"singleQuote": true,
"tabWidth": 4
}

View File

@ -1,9 +1,40 @@
# woody_js
JS адаптация клиентской части [Библиотеки RPC вызовов для общения между микросервисами](http://coredocs.rbkmoney.com/design/ms/platform/rpc-lib/) для запуска в браузере.
# Woody js
## Publish
Browser-Compatible Node.js Thrift Binary Protocol Connection
```sh
npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease [--preid=<prerelease-id>] | from-git]
npm publish
## Installation
```bash
npm install @vality/woody
```
## Usage Example
```typescript
import connectClient from '@vality/woody';
const host = 'localhost';
const port = '8080';
const path = '/some/path';
// Generated Thrift client
const genClient = {
/* ... your thrift client ... */
};
// Connection options
const connectOptions = {
https: true,
// ... other options ...
};
// Error callback
const errorCb = (err) => {
console.error('An error occurred:', err);
};
// Create a client connection
const client = connectClient(host, port, path, genClient, connectOptions, errorCb);
// Now you can use 'client' to interact with Thrift service
```

9563
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,16 @@
{
"name": "@vality/woody",
"version": "0.1.2",
"description": "Woody client side implementation for js",
"version": "0.1.3",
"description": "Browser-Compatible Node.js Thrift Binary Protocol Connection",
"repository": {
"type": "git",
"url": "git+https://github.com/valitydev/woody_js.git"
},
"main": "dist/connect-client.js",
"main": "dist/connect-client.mjs",
"typings": "src/connect-client.d.ts",
"files": [
"dist",
"src"
"dist/*",
"src/**/*.d.ts"
],
"license": "Apache-2.0",
"publishConfig": {
@ -18,25 +18,17 @@
"registry": "https://registry.npmjs.org/"
},
"scripts": {
"build": "webpack --config webpack.config.js",
"clean": "rimraf dist"
"build": "vite build",
"prettier:check": "prettier \"**\" --list-different --ignore-unknown",
"prettier:write": "prettier \"**\" --write --ignore-unknown"
},
"dependencies": {
"buffer": "6.0.3",
"https-browserify": "1.0.0",
"node-int64": "0.4.0",
"q": "1.5.x",
"rimraf": "2.6.2",
"stream-http": "2.3.1",
"url": "0.11.3",
"util": "0.12.5",
"ws": "6.0.0"
"node-int64": "0.4.0"
},
"devDependencies": {
"@babel/preset-env": "7.23.2",
"babel-core": "6.26.3",
"babel-loader": "9.1.3",
"webpack": "5.89.0",
"webpack-cli": "5.1.4"
"prettier": "3.0.3",
"vite": "4.5.0",
"vite-plugin-commonjs": "0.10.0",
"vite-plugin-node-polyfills": "0.15.0"
}
}

View File

@ -73,8 +73,8 @@ exports.writeI32 = function (buff, v) {
exports.readDouble = function (buff, off) {
off = off || 0;
var signed = buff[off] & 0x80;
var e = (buff[off + 1] & 0xF0) >> 4;
e += (buff[off] & 0x7F) << 4;
var e = (buff[off + 1] & 0xf0) >> 4;
e += (buff[off] & 0x7f) << 4;
var m = buff[off + 7];
m += buff[off + 6] << 8;
@ -82,14 +82,14 @@ exports.readDouble = function (buff, off) {
m += buff[off + 4] * POW_24;
m += buff[off + 3] * POW_32;
m += buff[off + 2] * POW_40;
m += (buff[off + 1] & 0x0F) * POW_48;
m += (buff[off + 1] & 0x0f) * POW_48;
switch (e) {
case 0:
e = -1022;
break;
case 2047:
return m ? NaN : (signed ? -Infinity : Infinity);
return m ? NaN : signed ? -Infinity : Infinity;
default:
m += POW_52;
e -= 1023;
@ -109,7 +109,7 @@ exports.readDouble = function (buff, off) {
exports.writeDouble = function (buff, v) {
var m, e, c;
buff[0] = (v < 0 ? 0x80 : 0x00);
buff[0] = v < 0 ? 0x80 : 0x00;
v = Math.abs(v);
if (v !== v) {
@ -131,15 +131,13 @@ exports.writeDouble = function (buff, v) {
// Overflow
m = 0;
e = 2047;
}
else if (e + 1023 >= 1) {
} else if (e + 1023 >= 1) {
// Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow
m = (v * c - 1) * POW_52;
e += 1023;
}
else {
} else {
// Denormalized - also catches the '0' case, somewhat by chance
m = (v * POW_1022) * POW_52;
m = v * POW_1022 * POW_52;
e = 0;
}
}

View File

@ -35,8 +35,8 @@ var VERSION_MASK = -65536, // 0xffff0000
function TBinaryProtocol(trans, strictRead, strictWrite) {
this.trans = trans;
this.strictRead = (strictRead !== undefined ? strictRead : false);
this.strictWrite = (strictWrite !== undefined ? strictWrite : true);
this.strictRead = strictRead !== undefined ? strictRead : false;
this.strictWrite = strictWrite !== undefined ? strictWrite : true;
}
TBinaryProtocol.prototype.flush = function () {
@ -56,7 +56,7 @@ TBinaryProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
// Record client seqid to find callback again
if (this._seqid) {
// TODO better logging log warning
log.warning('SeqId already set', {'name': name});
log.warning('SeqId already set', { name: name });
} else {
this._seqid = seqid;
this.trans.setCurrSeqId(seqid);
@ -71,19 +71,16 @@ TBinaryProtocol.prototype.writeMessageEnd = function () {
}
};
TBinaryProtocol.prototype.writeStructBegin = function () {
};
TBinaryProtocol.prototype.writeStructBegin = function () {};
TBinaryProtocol.prototype.writeStructEnd = function () {
};
TBinaryProtocol.prototype.writeStructEnd = function () {};
TBinaryProtocol.prototype.writeFieldBegin = function (name, type, id) {
this.writeByte(type);
this.writeI16(id);
};
TBinaryProtocol.prototype.writeFieldEnd = function () {
};
TBinaryProtocol.prototype.writeFieldEnd = function () {};
TBinaryProtocol.prototype.writeFieldStop = function () {
this.writeByte(Type.STOP);
@ -95,24 +92,21 @@ TBinaryProtocol.prototype.writeMapBegin = function (ktype, vtype, size) {
this.writeI32(size);
};
TBinaryProtocol.prototype.writeMapEnd = function () {
};
TBinaryProtocol.prototype.writeMapEnd = function () {};
TBinaryProtocol.prototype.writeListBegin = function (etype, size) {
this.writeByte(etype);
this.writeI32(size);
};
TBinaryProtocol.prototype.writeListEnd = function () {
};
TBinaryProtocol.prototype.writeListEnd = function () {};
TBinaryProtocol.prototype.writeSetBegin = function (etype, size) {
this.writeByte(etype);
this.writeI32(size);
};
TBinaryProtocol.prototype.writeSetEnd = function () {
};
TBinaryProtocol.prototype.writeSetEnd = function () {};
TBinaryProtocol.prototype.writeBool = function (bool) {
if (bool) {
@ -147,11 +141,13 @@ TBinaryProtocol.prototype.writeDouble = function (dub) {
};
TBinaryProtocol.prototype.writeStringOrBinary = function (name, encoding, arg) {
if (typeof(arg) === 'string') {
if (typeof arg === 'string') {
this.writeI32(Buffer.byteLength(arg, encoding));
this.trans.write(new Buffer(arg, encoding));
} else if ((arg instanceof Buffer) ||
(Object.prototype.toString.call(arg) == '[object Uint8Array]')) {
} else if (
arg instanceof Buffer ||
Object.prototype.toString.call(arg) == '[object Uint8Array]'
) {
// Buffers in Node.js under Browserify may extend UInt8Array instead of
// defining a new object. We detect them here so we can write them
// correctly
@ -177,14 +173,20 @@ TBinaryProtocol.prototype.readMessageBegin = function () {
if (sz < 0) {
var version = sz & VERSION_MASK;
if (version != VERSION_1) {
throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, 'Bad version in readMessageBegin: ' + sz);
throw new Thrift.TProtocolException(
Thrift.TProtocolExceptionType.BAD_VERSION,
'Bad version in readMessageBegin: ' + sz,
);
}
type = sz & TYPE_MASK;
name = this.readString();
seqid = this.readI32();
} else {
if (this.strictRead) {
throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, 'No protocol version header');
throw new Thrift.TProtocolException(
Thrift.TProtocolExceptionType.BAD_VERSION,
'No protocol version header',
);
}
name = this.trans.read(sz);
type = this.readByte();
@ -193,15 +195,13 @@ TBinaryProtocol.prototype.readMessageBegin = function () {
return { fname: name, mtype: type, rseqid: seqid };
};
TBinaryProtocol.prototype.readMessageEnd = function () {
};
TBinaryProtocol.prototype.readMessageEnd = function () {};
TBinaryProtocol.prototype.readStructBegin = function () {
return { fname: '' };
};
TBinaryProtocol.prototype.readStructEnd = function () {
};
TBinaryProtocol.prototype.readStructEnd = function () {};
TBinaryProtocol.prototype.readFieldBegin = function () {
var type = this.readByte();
@ -212,8 +212,7 @@ TBinaryProtocol.prototype.readFieldBegin = function () {
return { fname: null, ftype: type, fid: id };
};
TBinaryProtocol.prototype.readFieldEnd = function () {
};
TBinaryProtocol.prototype.readFieldEnd = function () {};
TBinaryProtocol.prototype.readMapBegin = function () {
var ktype = this.readByte();
@ -222,8 +221,7 @@ TBinaryProtocol.prototype.readMapBegin = function () {
return { ktype: ktype, vtype: vtype, size: size };
};
TBinaryProtocol.prototype.readMapEnd = function () {
};
TBinaryProtocol.prototype.readMapEnd = function () {};
TBinaryProtocol.prototype.readListBegin = function () {
var etype = this.readByte();
@ -231,8 +229,7 @@ TBinaryProtocol.prototype.readListBegin = function () {
return { etype: etype, size: size };
};
TBinaryProtocol.prototype.readListEnd = function () {
};
TBinaryProtocol.prototype.readListEnd = function () {};
TBinaryProtocol.prototype.readSetBegin = function () {
var etype = this.readByte();
@ -240,8 +237,7 @@ TBinaryProtocol.prototype.readSetBegin = function () {
return { etype: etype, size: size };
};
TBinaryProtocol.prototype.readSetEnd = function () {
};
TBinaryProtocol.prototype.readSetEnd = function () {};
TBinaryProtocol.prototype.readBool = function () {
var b = this.readByte();
@ -279,7 +275,10 @@ TBinaryProtocol.prototype.readBinary = function () {
}
if (len < 0) {
throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, 'Negative binary size');
throw new Thrift.TProtocolException(
Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
'Negative binary size',
);
}
return this.trans.read(len);
};
@ -291,7 +290,10 @@ TBinaryProtocol.prototype.readString = function () {
}
if (len < 0) {
throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, 'Negative string size');
throw new Thrift.TProtocolException(
Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
'Negative string size',
);
}
return this.trans.readString(len);
};

View File

@ -49,11 +49,10 @@ TBufferedTransport.receiver = function (callback, seqid) {
};
};
TBufferedTransport.prototype.commitPosition = function () {
var unreadSize = this.writeCursor - this.readCursor;
var bufSize = (unreadSize * 2 > this.defaultReadBufferSize) ?
unreadSize * 2 : this.defaultReadBufferSize;
var bufSize =
unreadSize * 2 > this.defaultReadBufferSize ? unreadSize * 2 : this.defaultReadBufferSize;
var buf = new Buffer(bufSize);
if (unreadSize > 0) {
this.inBuf.copy(buf, 0, this.readCursor, this.writeCursor);
@ -65,18 +64,16 @@ TBufferedTransport.prototype.commitPosition = function () {
TBufferedTransport.prototype.rollbackPosition = function () {
this.readCursor = 0;
}
};
// TODO: Implement open/close support
TBufferedTransport.prototype.isOpen = function () {
return true;
};
TBufferedTransport.prototype.open = function () {
};
TBufferedTransport.prototype.open = function () {};
TBufferedTransport.prototype.close = function () {
};
TBufferedTransport.prototype.close = function () {};
// Set the seqid of the message in the client
// So that callbacks can be found
@ -141,7 +138,7 @@ TBufferedTransport.prototype.consume = function (bytesConsumed) {
};
TBufferedTransport.prototype.write = function (buf) {
if (typeof(buf) === 'string') {
if (typeof buf === 'string') {
buf = new Buffer(buf, 'utf8');
}
this.outBuffers.push(buf);

View File

@ -17,7 +17,7 @@
* under the License.
*/
var util = require('util');
var http = require('stream-http');
var http = require('http');
var https = require('https');
var EventEmitter = require('events').EventEmitter;
var thrift = require('./thrift');
@ -93,7 +93,7 @@ HttpConnection = exports.HttpConnection = function (host, port, options, errorCb
path: this.options.path || '/',
method: 'POST',
headers: this.options.headers || {},
responseType: this.options.responseType || null
responseType: this.options.responseType || null,
};
for (var attrname in this.options.nodeOptions) {
this.nodeOptions[attrname] = this.options.nodeOptions[attrname];
@ -148,13 +148,15 @@ HttpConnection = exports.HttpConnection = function (host, port, options, errorCb
client['recv_' + header.fname](proto, header.mtype, dummy_seqid);
} else {
delete client._reqs[dummy_seqid];
const WRONG_METHOD_NAME_ERROR = new thrift.TApplicationException(thrift.TApplicationExceptionType.WRONG_METHOD_NAME, 'Received a response to an unknown RPC function');
const WRONG_METHOD_NAME_ERROR = new thrift.TApplicationException(
thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
'Received a response to an unknown RPC function',
);
self.errorCb(WRONG_METHOD_NAME_ERROR);
self.emit('error', WRONG_METHOD_NAME_ERROR);
}
}
}
catch (e) {
} catch (e) {
if (e instanceof InputBufferUnderrunError) {
transport_with_data.rollbackPosition();
} else {
@ -164,7 +166,6 @@ HttpConnection = exports.HttpConnection = function (host, port, options, errorCb
}
}
//Response handler
//////////////////////////////////////////////////
this.responseCallback = function (response) {
@ -184,8 +185,10 @@ HttpConnection = exports.HttpConnection = function (host, port, options, errorCb
// however, when running in a Browser (e.g. Browserify), chunk
// will be a string or an ArrayBuffer.
response.on('data', function (chunk) {
if ((typeof chunk == 'string') ||
(Object.prototype.toString.call(chunk) == '[object Uint8Array]')) {
if (
typeof chunk == 'string' ||
Object.prototype.toString.call(chunk) == '[object Uint8Array]'
) {
// Wrap ArrayBuffer/string in a Buffer so data[i].copy will work
data.push(new Buffer(chunk));
} else {
@ -221,9 +224,9 @@ HttpConnection.prototype.write = function (data) {
self.nodeOptions.headers['Content-length'] = data.length;
self.nodeOptions.headers['Accept'] = 'application/x-thrift';
self.nodeOptions.headers['Content-Type'] = 'application/x-thrift';
var req = (self.https) ?
https.request(self.nodeOptions, self.responseCallback) :
http.request(self.nodeOptions, self.responseCallback);
var req = self.https
? https.request(self.nodeOptions, self.responseCallback)
: http.request(self.nodeOptions, self.responseCallback);
req.on('error', function (err) {
self.errorCb(err);
self.emit('error', err);

View File

@ -18,9 +18,9 @@
*/
module.exports = {
'info' : function logInfo() {},
'warning' : function logWarning() {},
'error' : function logError() {},
'debug' : function logDebug() {},
'trace' : function logTrace() {}
info: function logInfo() {},
warning: function logWarning() {},
error: function logError() {},
debug: function logDebug() {},
trace: function logTrace() {},
};

View File

@ -18,7 +18,7 @@
*/
var util = require('util');
var Type = exports.Type = {
var Type = (exports.Type = {
STOP: 0,
VOID: 1,
BOOL: 2,
@ -35,14 +35,14 @@ var Type = exports.Type = {
SET: 14,
LIST: 15,
UTF8: 16,
UTF16: 17
};
UTF16: 17,
});
exports.MessageType = {
CALL: 1,
REPLY: 2,
EXCEPTION: 3,
ONEWAY: 4
ONEWAY: 4,
};
exports.TException = TException;
@ -55,7 +55,7 @@ function TException(message) {
}
util.inherits(TException, Error);
var TApplicationExceptionType = exports.TApplicationExceptionType = {
var TApplicationExceptionType = (exports.TApplicationExceptionType = {
UNKNOWN: 0,
UNKNOWN_METHOD: 1,
INVALID_MESSAGE_TYPE: 2,
@ -66,8 +66,8 @@ var TApplicationExceptionType = exports.TApplicationExceptionType = {
PROTOCOL_ERROR: 7,
INVALID_TRANSFORM: 8,
INVALID_PROTOCOL: 9,
UNSUPPORTED_CLIENT_TYPE: 10
};
UNSUPPORTED_CLIENT_TYPE: 10,
});
exports.TApplicationException = TApplicationException;
@ -85,8 +85,7 @@ TApplicationException.prototype.read = function (input) {
while (1) {
ret = input.readFieldBegin();
if (ret.ftype == Type.STOP)
break;
if (ret.ftype == Type.STOP) break;
switch (ret.fid) {
case 1:
@ -155,7 +154,6 @@ exports.inherits = function (constructor, superConstructor) {
var copyList, copyMap;
copyList = function (lst, types) {
if (!lst) {
return lst;
}
@ -164,22 +162,22 @@ copyList = function (lst, types) {
if (types.shift === undefined) {
type = types;
}
else {
} else {
type = types[0];
}
var Type = type;
var len = lst.length, result = [], i, val;
var len = lst.length,
result = [],
i,
val;
for (i = 0; i < len; i++) {
val = lst[i];
if (type === null) {
result.push(val);
}
else if (type === copyMap || type === copyList) {
} else if (type === copyMap || type === copyList) {
result.push(type(val, types.slice(1)));
}
else {
} else {
result.push(new Type(val));
}
}
@ -187,7 +185,6 @@ copyList = function (lst, types) {
};
copyMap = function (obj, types) {
if (!obj) {
return obj;
}
@ -196,8 +193,7 @@ copyMap = function (obj, types) {
if (types.shift === undefined) {
type = types;
}
else {
} else {
type = types[0];
}
var Type = type;
@ -207,14 +203,12 @@ copyMap = function (obj, types) {
obj.forEach((val, prop) => {
if (type === null) {
result.set(prop, val);
}
else if (type === copyMap || type === copyList) {
} else if (type === copyMap || type === copyList) {
result.set(prop, type(val, types.slice(1)));
}
else {
} else {
result.set(prop, new Type(val));
}
})
});
return result;
};

View File

@ -1,5 +1,12 @@
import {ConnectOptions} from "./connect-options";
import { ConnectOptions } from './connect-options';
declare module '@vality/woody' {
export default function connectClient(host: string, port: string, path: string, genClient: object, connectOptions: ConnectOptions, errorCb: Function): object;
export default function connectClient(
host: string,
port: string,
path: string,
genClient: object,
connectOptions: ConnectOptions,
errorCb: Function,
): object;
}

View File

@ -3,10 +3,15 @@ const TBufferedTransport = require('./client/buffered_transport');
const httpConnection = require('./client/http_connection');
export default function connectClient(host, port, path, genClient, options = {}, errorCb) {
const connection = httpConnection.createHttpConnection(host, port, Object.assign(options, {
const connection = httpConnection.createHttpConnection(
host,
port,
Object.assign(options, {
transport: TBufferedTransport,
protocol: TBinaryProtocol,
path
}), errorCb);
path,
}),
errorCb,
);
return httpConnection.createHttpClient(genClient, connection);
}

28
vite.config.js Normal file
View File

@ -0,0 +1,28 @@
import { defineConfig } from 'vite';
import commonjs from 'vite-plugin-commonjs';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
export default defineConfig({
plugins: [
commonjs(),
nodePolyfills({
globals: {
Buffer: true,
process: true,
},
}),
],
build: {
outDir: 'dist',
sourcemap: true,
minify: true,
lib: {
entry: './src/connect-client.js',
formats: ['es'],
fileName: 'connect-client',
},
},
resolve: {
extensions: ['.js'],
},
});

View File

@ -1,35 +0,0 @@
const webpack = require('webpack');
module.exports = {
name: 'woody_js',
mode: 'production',
stats: 'errors-only',
entry: {
'connect-client': './src/connect-client.js',
thrift: './src/client/gen.js',
},
resolve: {
extensions: ['.js'],
fallback: {
https: require.resolve('https-browserify'),
http: require.resolve('stream-http'),
},
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: '/node_modules/',
},
],
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
library: {
name: 'woody_js',
type: 'umd',
},
},
};