diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index dde2dba1845..00000000000 --- a/.eslintignore +++ /dev/null @@ -1,9 +0,0 @@ -# TODO: Use eslint on js lib and generated code - -# Ignore lib/js for now, which uses jshint currently -lib/js/* -# Ignore all generated code for now -**/gen-* - -# Don't lint nested node_modules -**/node_modules diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 0aae820ecdb..00000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "env": { - "es6": true, - "node": true - }, - "extends": [ - "eslint:recommended", - "plugin:prettier/recommended" - ], - "parserOptions": { - "ecmaVersion": 2017 - }, - "rules": { - "no-console": "off", - "no-var": "error", - "prefer-const": "error", - "no-constant-condition": [ - "error", - { - "checkLoops": false - } - ] - } -} diff --git a/compiler/cpp/src/thrift/generate/t_go_generator.h b/compiler/cpp/src/thrift/generate/t_go_generator.h index d84b18686f1..72825bc9caa 100644 --- a/compiler/cpp/src/thrift/generate/t_go_generator.h +++ b/compiler/cpp/src/thrift/generate/t_go_generator.h @@ -288,7 +288,7 @@ class t_go_generator : public t_generator { static bool is_pointer_field(t_field* tfield, bool in_container = false); - std::string indent_str() const { + std::string indent_str() const override { return "\t"; } diff --git a/compiler/cpp/src/thrift/parse/t_function.h b/compiler/cpp/src/thrift/parse/t_function.h index d2cb19bbc3a..abe29039f95 100644 --- a/compiler/cpp/src/thrift/parse/t_function.h +++ b/compiler/cpp/src/thrift/parse/t_function.h @@ -83,7 +83,7 @@ class t_function : public t_doc { std::map> annotations_; - void validate() const { + void validate() const override { get_returntype()->validate(); #ifndef ALLOW_EXCEPTIONS_AS_TYPE diff --git a/compiler/cpp/src/thrift/parse/t_list.h b/compiler/cpp/src/thrift/parse/t_list.h index 162281cc088..9c1dfadea27 100644 --- a/compiler/cpp/src/thrift/parse/t_list.h +++ b/compiler/cpp/src/thrift/parse/t_list.h @@ -34,7 +34,7 @@ class t_list : public t_container { bool is_list() const override { return true; } - void validate() const { + void validate() const override { #ifndef ALLOW_EXCEPTIONS_AS_TYPE if( get_elem_type()->get_true_type()->is_xception()) { failure("exception type \"%s\" cannot be used inside a list", get_elem_type()->get_name().c_str()); diff --git a/compiler/cpp/src/thrift/parse/t_map.h b/compiler/cpp/src/thrift/parse/t_map.h index 30a8b06c9b9..6ec58cfbb13 100644 --- a/compiler/cpp/src/thrift/parse/t_map.h +++ b/compiler/cpp/src/thrift/parse/t_map.h @@ -37,7 +37,7 @@ class t_map : public t_container { bool is_map() const override { return true; } - void validate() const { + void validate() const override { #ifndef ALLOW_EXCEPTIONS_AS_TYPE if( get_key_type()->get_true_type()->is_xception()) { failure("exception type \"%s\" cannot be used inside a map", get_key_type()->get_name().c_str()); diff --git a/compiler/cpp/src/thrift/parse/t_set.h b/compiler/cpp/src/thrift/parse/t_set.h index 88de93f44c4..8f7599a5a60 100644 --- a/compiler/cpp/src/thrift/parse/t_set.h +++ b/compiler/cpp/src/thrift/parse/t_set.h @@ -36,7 +36,7 @@ class t_set : public t_container { bool is_set() const override { return true; } - void validate() const { + void validate() const override { #ifndef ALLOW_EXCEPTIONS_AS_TYPE if( get_elem_type()->get_true_type()->is_xception()) { failure("exception type \"%s\" cannot be used inside a set", get_elem_type()->get_name().c_str()); diff --git a/compiler/cpp/src/thrift/parse/t_struct.h b/compiler/cpp/src/thrift/parse/t_struct.h index 3aa67c0e16a..8b33ee6c4b3 100644 --- a/compiler/cpp/src/thrift/parse/t_struct.h +++ b/compiler/cpp/src/thrift/parse/t_struct.h @@ -130,7 +130,7 @@ class t_struct : public t_type { return nullptr; } - void validate() const { + void validate() const override { std::string what = "struct"; if( is_union()) { what = "union"; diff --git a/compiler/cpp/test/compiler/staleness_check.py b/compiler/cpp/test/compiler/staleness_check.py index 6b67798d6a4..4dcec15ce89 100755 --- a/compiler/cpp/test/compiler/staleness_check.py +++ b/compiler/cpp/test/compiler/staleness_check.py @@ -17,7 +17,6 @@ # specific language governing permissions and limitations # under the License. # -from __future__ import print_function import os import shutil import subprocess diff --git a/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py b/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py index 5c8f409c1af..62a729e1d8f 100644 --- a/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py +++ b/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py @@ -19,7 +19,6 @@ # under the License. # -from __future__ import print_function import sys import os from optparse import OptionParser diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 00000000000..a27b211ec7f --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,44 @@ +import globals from "globals"; +import js from "@eslint/js"; +import eslintPluginPrettierRecommended from "eslint-plugin-prettier/recommended"; + +export default [ + { + ignores: [ + // TODO: Use eslint on js lib and generated code + + // Ignore lib/js for now, which uses jshint currently + "lib/js/*", + // Ignore all generated code for now + "**/gen-*/", + + // Don't lint nested node_modules + "**/node_modules/", + ], + }, + js.configs.recommended, + eslintPluginPrettierRecommended, + { + languageOptions: { + globals: { + ...globals.node, + }, + + ecmaVersion: 2017, + sourceType: "commonjs", + }, + + rules: { + "no-console": "off", + "no-var": "error", + "prefer-const": "error", + + "no-constant-condition": [ + "error", + { + checkLoops: false, + }, + ], + }, + }, +]; diff --git a/lib/cpp/src/thrift/Thrift.h b/lib/cpp/src/thrift/Thrift.h index d5066ee7107..338694b7f3f 100644 --- a/lib/cpp/src/thrift/Thrift.h +++ b/lib/cpp/src/thrift/Thrift.h @@ -58,12 +58,14 @@ class TEnumIterator int operator++() { return ++ii_; } - bool operator!=(const TEnumIterator& end) { - THRIFT_UNUSED_VARIABLE(end); - assert(end.n_ == -1); - return (ii_ != n_); + bool operator==(const TEnumIterator& rhs) const { + bool is_end = ii_ == n_ || n_ == -1; + bool is_rhs_end = rhs.ii_ == rhs.n_ || rhs.n_ == -1; + return (ii_ == rhs.ii_ && n_ == rhs.n_) || (is_end && is_rhs_end); } + bool operator!=(const TEnumIterator& rhs) const { return !(*this == rhs); } + std::pair operator*() const { return std::make_pair(enums_[ii_], names_[ii_]); } private: diff --git a/lib/cpp/src/thrift/transport/THttpServer.cpp b/lib/cpp/src/thrift/transport/THttpServer.cpp index 91a1c39afcd..6fc2816748c 100644 --- a/lib/cpp/src/thrift/transport/THttpServer.cpp +++ b/lib/cpp/src/thrift/transport/THttpServer.cpp @@ -25,7 +25,7 @@ #include #include #if defined(_MSC_VER) || defined(__MINGW32__) - #include + #include #endif using std::string; diff --git a/lib/cpp/src/thrift/transport/TPipeServer.cpp b/lib/cpp/src/thrift/transport/TPipeServer.cpp index e4234b180b5..fd1aeee9514 100644 --- a/lib/cpp/src/thrift/transport/TPipeServer.cpp +++ b/lib/cpp/src/thrift/transport/TPipeServer.cpp @@ -27,8 +27,8 @@ #ifdef _WIN32 #include #include -#include -#include +#include +#include #include #endif //_WIN32 diff --git a/lib/cpp/src/thrift/transport/TServerSocket.cpp b/lib/cpp/src/thrift/transport/TServerSocket.cpp index 7cab0eefa77..ffe9ed3a504 100644 --- a/lib/cpp/src/thrift/transport/TServerSocket.cpp +++ b/lib/cpp/src/thrift/transport/TServerSocket.cpp @@ -73,7 +73,7 @@ // adds problematic macros like min() and max(). Try to work around: #define NOMINMAX #define WIN32_LEAN_AND_MEAN -#include +#include #undef NOMINMAX #undef WIN32_LEAN_AND_MEAN #endif diff --git a/lib/cpp/src/thrift/transport/TWebSocketServer.h b/lib/cpp/src/thrift/transport/TWebSocketServer.h index 7f39f36b95e..2a3e076cf04 100644 --- a/lib/cpp/src/thrift/transport/TWebSocketServer.h +++ b/lib/cpp/src/thrift/transport/TWebSocketServer.h @@ -31,7 +31,7 @@ #include #include #if defined(_MSC_VER) || defined(__MINGW32__) -#include +#include #define THRIFT_strncasecmp(str1, str2, len) _strnicmp(str1, str2, len) #define THRIFT_strcasestr(haystack, needle) StrStrIA(haystack, needle) #else diff --git a/lib/cpp/src/thrift/windows/Operators.h b/lib/cpp/src/thrift/windows/Operators.h index 9b860968002..406e11eb6ec 100644 --- a/lib/cpp/src/thrift/windows/Operators.h +++ b/lib/cpp/src/thrift/windows/Operators.h @@ -29,11 +29,6 @@ namespace thrift { class TEnumIterator; -inline bool operator==(const TEnumIterator&, const TEnumIterator&) { - // Not entirely sure what the test should be here. It is only to enable - // iterator debugging and is not used in release mode. - return true; -} } } // apache::thrift diff --git a/lib/cpp/src/thrift/windows/SocketPair.cpp b/lib/cpp/src/thrift/windows/SocketPair.cpp index 2650b37d475..9271b02943b 100644 --- a/lib/cpp/src/thrift/windows/SocketPair.cpp +++ b/lib/cpp/src/thrift/windows/SocketPair.cpp @@ -34,7 +34,7 @@ #include // Win32 -#include +#include int thrift_socketpair(int d, int type, int protocol, THRIFT_SOCKET sv[2]) { THRIFT_UNUSED_VARIABLE(protocol); diff --git a/lib/cpp/src/thrift/windows/Sync.h b/lib/cpp/src/thrift/windows/Sync.h index 89aaead7795..e143b863418 100644 --- a/lib/cpp/src/thrift/windows/Sync.h +++ b/lib/cpp/src/thrift/windows/Sync.h @@ -37,7 +37,7 @@ #define WIN32_LEAN_AND_MEAN #define _THRIFT_UNDEF_WIN32_LEAN_AND_MEAN #endif -#include +#include #ifdef _THRIFT_UNDEF_NOMINMAX #undef NOMINMAX #undef _THRIFT_UNDEF_NOMINMAX diff --git a/lib/cpp/test/CMakeLists.txt b/lib/cpp/test/CMakeLists.txt index a73b3e6f772..31acf124404 100644 --- a/lib/cpp/test/CMakeLists.txt +++ b/lib/cpp/test/CMakeLists.txt @@ -133,7 +133,7 @@ target_link_libraries(TInterruptTest ${Boost_LIBRARIES} ) target_link_libraries(TInterruptTest thrift) -if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT MINGW) +if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD" AND NOT MINGW) target_link_libraries(TInterruptTest -lrt) endif () add_test(NAME TInterruptTest COMMAND TInterruptTest -- "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") @@ -144,7 +144,7 @@ target_link_libraries(TServerIntegrationTest ${Boost_LIBRARIES} ) target_link_libraries(TServerIntegrationTest thrift) -if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT MINGW) +if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD" AND NOT MINGW) target_link_libraries(TServerIntegrationTest -lrt) endif () add_test(NAME TServerIntegrationTest COMMAND TServerIntegrationTest) @@ -347,7 +347,7 @@ target_link_libraries(SecurityTest ${Boost_LIBRARIES} ) target_link_libraries(SecurityTest thrift) -if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT MINGW) +if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD" AND NOT MINGW) target_link_libraries(SecurityTest -lrt) endif () add_test(NAME SecurityTest COMMAND SecurityTest -- "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") @@ -358,7 +358,7 @@ target_link_libraries(SecurityFromBufferTest ${Boost_LIBRARIES} ) target_link_libraries(SecurityFromBufferTest thrift) -if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT MINGW) +if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD" AND NOT MINGW) target_link_libraries(SecurityFromBufferTest -lrt) endif () add_test(NAME SecurityFromBufferTest COMMAND SecurityFromBufferTest -- "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") diff --git a/lib/delphi/src/Thrift.Configuration.pas b/lib/delphi/src/Thrift.Configuration.pas index 0cb11af350e..562dba16fef 100644 --- a/lib/delphi/src/Thrift.Configuration.pas +++ b/lib/delphi/src/Thrift.Configuration.pas @@ -33,33 +33,36 @@ interface type IThriftConfiguration = interface - ['{ADD75449-1A67-4B78-9B75-502A1E338CFC}'] - function GetRecursionLimit : Cardinal; - procedure SetRecursionLimit( const value : Cardinal); - function GetMaxFrameSize : Cardinal; - procedure SetMaxFrameSize( const value : Cardinal); - function GetMaxMessageSize : Cardinal; - procedure SetMaxMessageSize( const value : Cardinal); - - property RecursionLimit : Cardinal read GetRecursionLimit write SetRecursionLimit; - property MaxFrameSize : Cardinal read GetMaxFrameSize write SetMaxFrameSize; - property MaxMessageSize : Cardinal read GetMaxMessageSize write SetMaxMessageSize; + ['{666F7848-744A-4746-BDD5-43DC9B1D5520}'] + function GetRecursionLimit : Integer; + procedure SetRecursionLimit( const value : Integer); + function GetMaxFrameSize : Integer; + procedure SetMaxFrameSize( const value : Integer); + function GetMaxMessageSize : Integer; + procedure SetMaxMessageSize( const value : Integer); + + property RecursionLimit : Integer read GetRecursionLimit write SetRecursionLimit; + property MaxFrameSize : Integer read GetMaxFrameSize write SetMaxFrameSize; + property MaxMessageSize : Integer read GetMaxMessageSize write SetMaxMessageSize; end; TThriftConfigurationImpl = class( TInterfacedObject, IThriftConfiguration) + strict private + class procedure ValidateLimitArgument( const value : Integer); inline; + strict protected FRecursionLimit : Cardinal; FMaxFrameSize : Cardinal; FMaxMessageSize : Cardinal; // IThriftConfiguration - function GetRecursionLimit : Cardinal; - procedure SetRecursionLimit( const value : Cardinal); - function GetMaxFrameSize : Cardinal; - procedure SetMaxFrameSize( const value : Cardinal); - function GetMaxMessageSize : Cardinal; - procedure SetMaxMessageSize( const value : Cardinal); + function GetRecursionLimit : Integer; + procedure SetRecursionLimit( const value : Integer); + function GetMaxFrameSize : Integer; + procedure SetMaxFrameSize( const value : Integer); + function GetMaxMessageSize : Integer; + procedure SetMaxMessageSize( const value : Integer); public constructor Create; @@ -82,39 +85,55 @@ constructor TThriftConfigurationImpl.Create; end; -function TThriftConfigurationImpl.GetRecursionLimit: Cardinal; +class procedure TThriftConfigurationImpl.ValidateLimitArgument( const value : Integer); +begin + if value <= 0 // zero makes not much sense either + then raise EArgumentOutOfRangeException.Create('Value must be positive'); +end; + + +function TThriftConfigurationImpl.GetRecursionLimit: Integer; begin - result := FRecursionLimit; + result := FRecursionLimit and MAXINT; + ASSERT( result > 0); end; -procedure TThriftConfigurationImpl.SetRecursionLimit(const value: Cardinal); +procedure TThriftConfigurationImpl.SetRecursionLimit(const value: Integer); begin - FRecursionLimit := value; + ValidateLimitArgument( value); + ASSERT( value > 0); + FRecursionLimit := value and MAXINT; end; -function TThriftConfigurationImpl.GetMaxFrameSize: Cardinal; +function TThriftConfigurationImpl.GetMaxFrameSize: Integer; begin - result := FMaxFrameSize; + result := FMaxFrameSize and MAXINT; + ASSERT( result > 0); end; -procedure TThriftConfigurationImpl.SetMaxFrameSize(const value: Cardinal); +procedure TThriftConfigurationImpl.SetMaxFrameSize(const value: Integer); begin - FMaxFrameSize := value; + ValidateLimitArgument( value); + ASSERT( value > 0); + FMaxFrameSize := value and MAXINT; end; -function TThriftConfigurationImpl.GetMaxMessageSize: Cardinal; +function TThriftConfigurationImpl.GetMaxMessageSize: Integer; begin - result := FMaxMessageSize; + result := FMaxMessageSize and MAXINT; + ASSERT( result > 0); end; -procedure TThriftConfigurationImpl.SetMaxMessageSize(const value: Cardinal); +procedure TThriftConfigurationImpl.SetMaxMessageSize(const value: Integer); begin - FMaxMessageSize := value; + ValidateLimitArgument( value); + ASSERT( value > 0); + FMaxMessageSize := value and MAXINT; end; diff --git a/lib/delphi/src/Thrift.Protocol.pas b/lib/delphi/src/Thrift.Protocol.pas index c09728311a8..969fbcd0788 100644 --- a/lib/delphi/src/Thrift.Protocol.pas +++ b/lib/delphi/src/Thrift.Protocol.pas @@ -680,7 +680,7 @@ function TProtocolImpl.Configuration : IThriftConfiguration; procedure TProtocolImpl.Reset; begin - FTrans.ResetConsumedMessageSize; + FTrans.ResetMessageSizeAndConsumedBytes; end; function TProtocolImpl.ReadString: string; diff --git a/lib/delphi/src/Thrift.Stream.pas b/lib/delphi/src/Thrift.Stream.pas index 6c1320d998e..56823312656 100644 --- a/lib/delphi/src/Thrift.Stream.pas +++ b/lib/delphi/src/Thrift.Stream.pas @@ -37,7 +37,7 @@ interface type IThriftStream = interface - ['{3A61A8A6-3639-4B91-A260-EFCA23944F3A}'] + ['{67801A9F-3B85-41CF-9025-D18AC6849B58}'] procedure Write( const buffer: TBytes; offset: Integer; count: Integer); overload; procedure Write( const pBuf : Pointer; offset: Integer; count: Integer); overload; function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; overload; @@ -47,6 +47,7 @@ interface procedure Flush; function IsOpen: Boolean; function ToArray: TBytes; + function CanSeek : Boolean; function Size : Int64; function Position : Int64; end; @@ -66,6 +67,7 @@ TThriftStreamImpl = class abstract( TInterfacedObject, IThriftStream) procedure Flush; virtual; abstract; function IsOpen: Boolean; virtual; abstract; function ToArray: TBytes; virtual; abstract; + function CanSeek : Boolean; virtual; function Size : Int64; virtual; function Position : Int64; virtual; end; @@ -83,6 +85,7 @@ TThriftStreamAdapterDelphi = class( TThriftStreamImpl) procedure Flush; override; function IsOpen: Boolean; override; function ToArray: TBytes; override; + function CanSeek : Boolean; override; function Size : Int64; override; function Position : Int64; override; public @@ -102,6 +105,7 @@ TThriftStreamAdapterCOM = class( TThriftStreamImpl) procedure Flush; override; function IsOpen: Boolean; override; function ToArray: TBytes; override; + function CanSeek : Boolean; override; function Size : Int64; override; function Position : Int64; override; public @@ -176,6 +180,12 @@ procedure TThriftStreamAdapterCOM.Flush; end; end; +function TThriftStreamAdapterCOM.CanSeek : Boolean; +var statstg: TStatStg; +begin + result := IsOpen and Succeeded( FStream.Stat( statstg, STATFLAG_NONAME)); +end; + function TThriftStreamAdapterCOM.Size : Int64; var statstg: TStatStg; begin @@ -290,6 +300,11 @@ procedure TThriftStreamImpl.Write( const pBuf : Pointer; offset: Integer; count: CheckSizeAndOffset( pBuf, offset+count, offset, count); end; +function TThriftStreamImpl.CanSeek : Boolean; +begin + result := FALSE; // TRUE indicates Size and Position are implemented +end; + function TThriftStreamImpl.Size : Int64; begin ASSERT(FALSE); @@ -332,6 +347,15 @@ procedure TThriftStreamAdapterDelphi.Flush; // nothing to do end; +function TThriftStreamAdapterDelphi.CanSeek : Boolean; +begin + try + result := IsOpen and (FStream.Size >= 0); // throws if not implemented + except + result := FALSE; // seek not implemented + end; +end; + function TThriftStreamAdapterDelphi.Size : Int64; begin result := FStream.Size; diff --git a/lib/delphi/src/Thrift.Transport.MsxmlHTTP.pas b/lib/delphi/src/Thrift.Transport.MsxmlHTTP.pas index b0c7acd22cf..2cc3bfeaf9d 100644 --- a/lib/delphi/src/Thrift.Transport.MsxmlHTTP.pas +++ b/lib/delphi/src/Thrift.Transport.MsxmlHTTP.pas @@ -256,7 +256,7 @@ procedure TMsxmlHTTPClientImpl.SendRequest; xmlhttp.send( IUnknown( TStreamAdapter.Create( ms, soReference ))); FInputStream := nil; FInputStream := TThriftStreamAdapterCOM.Create( IUnknown( xmlhttp.responseStream) as IStream); - ResetConsumedMessageSize; + ResetMessageSizeAndConsumedBytes; UpdateKnownMessageSize( FInputStream.Size); finally ms.Free; diff --git a/lib/delphi/src/Thrift.Transport.Pipes.pas b/lib/delphi/src/Thrift.Transport.Pipes.pas index 10f4dec23e6..d3980d79811 100644 --- a/lib/delphi/src/Thrift.Transport.Pipes.pas +++ b/lib/delphi/src/Thrift.Transport.Pipes.pas @@ -679,22 +679,22 @@ procedure THandlePipeStreamImpl.Open; function TPipeTransportBase.GetIsOpen: Boolean; begin - result := (FInputStream <> nil) and (FInputStream.IsOpen) - and (FOutputStream <> nil) and (FOutputStream.IsOpen); + result := (InputStream <> nil) and (InputStream.IsOpen) + and (OutputStream <> nil) and (OutputStream.IsOpen); end; procedure TPipeTransportBase.Open; begin - FInputStream.Open; - FOutputStream.Open; + InputStream.Open; + OutputStream.Open; end; procedure TPipeTransportBase.Close; begin - FInputStream.Close; - FOutputStream.Close; + InputStream.Close; + OutputStream.Close; end; @@ -709,8 +709,8 @@ constructor TNamedPipeTransportClientEndImpl.Create( const aPipeName : string; // Named pipe constructor begin inherited Create( nil, nil, aConfig); - FInputStream := TNamedPipeStreamImpl.Create( aPipeName, TRUE, aShareMode, aSecurityAttributes, aTimeOut, aOpenTimeOut); - FOutputStream := FInputStream; // true for named pipes + SetInputStream( TNamedPipeStreamImpl.Create( aPipeName, TRUE, aShareMode, aSecurityAttributes, aTimeOut, aOpenTimeOut)); + SetOutputStream( InputStream); // true for named pipes end; @@ -721,8 +721,8 @@ constructor TNamedPipeTransportClientEndImpl.Create( const aPipe : THandle; // Named pipe constructor begin inherited Create( nil, nil, aConfig); - FInputStream := THandlePipeStreamImpl.Create( aPipe, aOwnsHandle, TRUE, aTimeOut); - FOutputStream := FInputStream; // true for named pipes + SetInputStream( THandlePipeStreamImpl.Create( aPipe, aOwnsHandle, TRUE, aTimeOut)); + SetOutputStream( InputStream); // true for named pipes end; @@ -761,8 +761,8 @@ constructor TAnonymousPipeTransportImpl.Create( const aPipeRead, aPipeWrite : TH begin inherited Create( nil, nil, aConfig); // overlapped is not supported with AnonPipes, see MSDN - FInputStream := THandlePipeStreamImpl.Create( aPipeRead, aOwnsHandles, FALSE, aTimeout); - FOutputStream := THandlePipeStreamImpl.Create( aPipeWrite, aOwnsHandles, FALSE, aTimeout); + SetInputStream( THandlePipeStreamImpl.Create( aPipeRead, aOwnsHandles, FALSE, aTimeout)); + SetOutputStream( THandlePipeStreamImpl.Create( aPipeWrite, aOwnsHandles, FALSE, aTimeout)); end; diff --git a/lib/delphi/src/Thrift.Transport.WinHTTP.pas b/lib/delphi/src/Thrift.Transport.WinHTTP.pas index 87a230996a2..9deda4acd5b 100644 --- a/lib/delphi/src/Thrift.Transport.WinHTTP.pas +++ b/lib/delphi/src/Thrift.Transport.WinHTTP.pas @@ -334,7 +334,7 @@ procedure TWinHTTPClientImpl.SendRequest; end; // we're about to receive a new message, so reset everyting - ResetConsumedMessageSize(-1); + ResetMessageSizeAndConsumedBytes(-1); FInputStream := THTTPResponseStream.Create( http); if http.QueryTotalResponseSize( dwSize) // FALSE indicates "no info available" then UpdateKnownMessageSize( dwSize); diff --git a/lib/delphi/src/Thrift.Transport.pas b/lib/delphi/src/Thrift.Transport.pas index fd088375d42..4ca38315d50 100644 --- a/lib/delphi/src/Thrift.Transport.pas +++ b/lib/delphi/src/Thrift.Transport.pas @@ -68,7 +68,7 @@ interface function Configuration : IThriftConfiguration; function MaxMessageSize : Integer; - procedure ResetConsumedMessageSize( const knownSize : Int64 = -1); + procedure ResetMessageSizeAndConsumedBytes( const knownSize : Int64 = -1); procedure CheckReadBytesAvailable( const numBytes : Int64); procedure UpdateKnownMessageSize( const size : Int64); end; @@ -106,10 +106,10 @@ TEndpointTransportBase = class abstract( TTransportBase, ITransport) function MaxMessageSize : Integer; property RemainingMessageSize : Int64 read FRemainingMessageSize; property KnownMessageSize : Int64 read FKnownMessageSize; - procedure ResetConsumedMessageSize( const newSize : Int64 = -1); + procedure ResetMessageSizeAndConsumedBytes( const newSize : Int64 = -1); procedure UpdateKnownMessageSize(const size : Int64); override; - procedure CheckReadBytesAvailable(const numBytes : Int64); inline; - procedure CountConsumedMessageBytes(const numBytes : Int64); inline; + procedure CheckReadBytesAvailable(const numBytes : Int64); {$IFNDEF Debug} inline; {$ENDIF} + procedure CountConsumedMessageBytes(const numBytes : Int64); {$IFNDEF Debug} inline; {$ENDIF} public constructor Create( const aConfig : IThriftConfiguration); reintroduce; end; @@ -124,7 +124,7 @@ TLayeredTransportBase = class abstract( TTransportBase, ITrans function Configuration : IThriftConfiguration; override; procedure UpdateKnownMessageSize( const size : Int64); override; function MaxMessageSize : Integer; inline; - procedure ResetConsumedMessageSize( const knownSize : Int64 = -1); inline; + procedure ResetMessageSizeAndConsumedBytes( const knownSize : Int64 = -1); inline; procedure CheckReadBytesAvailable( const numBytes : Int64); virtual; public constructor Create( const aTransport: T); reintroduce; @@ -303,14 +303,18 @@ TTcpSocketStreamImpl = class( TThriftStreamImpl) end; TStreamTransportImpl = class( TEndpointTransportBase, IStreamTransport) - strict protected - FInputStream : IThriftStream; - FOutputStream : IThriftStream; + strict private + FInternalInputStream : IThriftStream; + FInternalOutputStream : IThriftStream; + strict protected function GetIsOpen: Boolean; override; - function GetInputStream: IThriftStream; - function GetOutputStream: IThriftStream; + function GetInputStream: IThriftStream; inline; + procedure SetInputStream( const stream : IThriftStream); + + function GetOutputStream: IThriftStream; inline; + procedure SetOutputStream( const stream : IThriftStream); strict protected procedure Open; override; @@ -318,6 +322,8 @@ TStreamTransportImpl = class( TEndpointTransportBase, IStreamTransport) procedure Flush; override; function Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; override; procedure Write( const pBuf : Pointer; off, len : Integer); override; + + procedure UpdateKnownMessageSize(const size : Int64); override; public constructor Create( const aInputStream, aOutputStream : IThriftStream; const aConfig : IThriftConfiguration = nil); reintroduce; destructor Destroy; override; @@ -340,6 +346,7 @@ TBufferedStreamImpl = class( TThriftStreamImpl) procedure Flush; override; function IsOpen: Boolean; override; function ToArray: TBytes; override; + function CanSeek : Boolean; override; function Size : Int64; override; function Position : Int64; override; public @@ -545,7 +552,7 @@ constructor TEndpointTransportBase.Create( const aConfig : IThriftConfiguration) then FConfiguration := aConfig else FConfiguration := TThriftConfigurationImpl.Create; - ResetConsumedMessageSize; + ResetMessageSizeAndConsumedBytes; end; @@ -562,7 +569,7 @@ function TEndpointTransportBase.MaxMessageSize : Integer; end; -procedure TEndpointTransportBase.ResetConsumedMessageSize( const newSize : Int64); +procedure TEndpointTransportBase.ResetMessageSizeAndConsumedBytes( const newSize : Int64); // Resets RemainingMessageSize to the configured maximum begin // full reset @@ -583,12 +590,12 @@ procedure TEndpointTransportBase.ResetConsumedMessageSize( const newSize : Int64 procedure TEndpointTransportBase.UpdateKnownMessageSize( const size : Int64); -// Updates RemainingMessageSize to reflect then known real message size (e.g. framed transport). +// Updates RemainingMessageSize to reflect the known real message size (e.g. framed transport). // Will throw if we already consumed too many bytes. var consumed : Int64; begin consumed := KnownMessageSize - RemainingMessageSize; - ResetConsumedMessageSize(size); + ResetMessageSizeAndConsumedBytes(size); CountConsumedMessageBytes(consumed); end; @@ -642,9 +649,9 @@ function TLayeredTransportBase.MaxMessageSize : Integer; end; -procedure TLayeredTransportBase.ResetConsumedMessageSize( const knownSize : Int64 = -1); +procedure TLayeredTransportBase.ResetMessageSizeAndConsumedBytes( const knownSize : Int64 = -1); begin - InnerTransport.ResetConsumedMessageSize( knownSize); + InnerTransport.ResetMessageSizeAndConsumedBytes( knownSize); end; @@ -964,8 +971,8 @@ procedure TSocketImpl.Close; begin inherited Close; - FInputStream := nil; - FOutputStream := nil; + SetInputStream( nil); + SetOutputStream( nil); if FOwnsClient then FreeAndNil( FClient) @@ -997,8 +1004,8 @@ procedure TSocketImpl.InitSocket; FOwnsClient := True; stream := TTcpSocketStreamImpl.Create( FClient, FTimeout); - FInputStream := stream; - FOutputStream := stream; + SetInputStream( stream); + SetOutputStream( stream); end; procedure TSocketImpl.Open; @@ -1026,8 +1033,8 @@ procedure TSocketImpl.Open; FClient.Open; {$ENDIF} - FInputStream := TTcpSocketStreamImpl.Create( FClient, FTimeout); - FOutputStream := FInputStream; + SetInputStream( TTcpSocketStreamImpl.Create( FClient, FTimeout)); + SetOutputStream( InputStream); // same end; { TBufferedStream } @@ -1156,6 +1163,12 @@ procedure TBufferedStreamImpl.Write( const pBuf : Pointer; offset: Integer; coun end; +function TBufferedStreamImpl.CanSeek : Boolean; +begin + result := TRUE; +end; + + function TBufferedStreamImpl.Size : Int64; begin result := FReadBuffer.Size; @@ -1173,45 +1186,57 @@ function TBufferedStreamImpl.Position : Int64; constructor TStreamTransportImpl.Create( const aInputStream, aOutputStream : IThriftStream; const aConfig : IThriftConfiguration); begin inherited Create( aConfig); - FInputStream := aInputStream; - FOutputStream := aOutputStream; + SetInputStream( aInputStream); + SetOutputStream( aOutputStream); end; destructor TStreamTransportImpl.Destroy; begin - FInputStream := nil; - FOutputStream := nil; + SetInputStream( nil); + SetInputStream( nil); inherited; end; procedure TStreamTransportImpl.Close; begin - FInputStream := nil; - FOutputStream := nil; + SetInputStream( nil); + SetInputStream( nil); end; procedure TStreamTransportImpl.Flush; begin - if FOutputStream = nil then begin + if OutputStream = nil then begin raise TTransportExceptionNotOpen.Create('Cannot flush null outputstream' ); end; - FOutputStream.Flush; + OutputStream.Flush; end; function TStreamTransportImpl.GetInputStream: IThriftStream; begin - Result := FInputStream; + Result := FInternalInputStream; end; -function TStreamTransportImpl.GetIsOpen: Boolean; +procedure TStreamTransportImpl.SetInputStream( const stream : IThriftStream); begin - Result := True; + FInternalInputStream := stream; + ResetMessageSizeAndConsumedBytes(-1); // full reset to configured maximum + UpdateKnownMessageSize( -1); // adjust to real stream size end; function TStreamTransportImpl.GetOutputStream: IThriftStream; begin - Result := FOutputStream; + Result := FInternalOutputStream; +end; + +procedure TStreamTransportImpl.SetOutputStream( const stream : IThriftStream); +begin + FInternalOutputStream := stream; +end; + +function TStreamTransportImpl.GetIsOpen: Boolean; +begin + Result := True; end; procedure TStreamTransportImpl.Open; @@ -1221,19 +1246,36 @@ procedure TStreamTransportImpl.Open; function TStreamTransportImpl.Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; begin - if FInputStream = nil + if InputStream = nil then raise TTransportExceptionNotOpen.Create('Cannot read from null inputstream' ); - Result := FInputStream.Read( pBuf,buflen, off, len ); + Result := InputStream.Read( pBuf,buflen, off, len ); CountConsumedMessageBytes( result); end; procedure TStreamTransportImpl.Write( const pBuf : Pointer; off, len : Integer); begin - if FOutputStream = nil + if OutputStream = nil then raise TTransportExceptionNotOpen.Create('Cannot write to null outputstream' ); - FOutputStream.Write( pBuf, off, len ); + OutputStream.Write( pBuf, off, len ); +end; + + +procedure TStreamTransportImpl.UpdateKnownMessageSize(const size : Int64); +var adjusted : Int64; +begin + if InputStream = nil + then adjusted := 0 + else begin + adjusted := MaxMessageSize; + if size > 0 + then adjusted := Math.Min( adjusted, size); + if InputStream.CanSeek + then adjusted := Math.Min( adjusted, InputStream.Size); + end; + + inherited UpdateKnownMessageSize( adjusted); end; { TBufferedTransportImpl } diff --git a/lib/java/build.gradle b/lib/java/build.gradle index e09a7e832b3..6ee454a026a 100644 --- a/lib/java/build.gradle +++ b/lib/java/build.gradle @@ -42,7 +42,7 @@ plugins { id 'pmd' id 'com.github.johnrengelman.shadow' version '8.1.1' id "com.github.spotbugs" version "5.2.5" - id "com.diffplug.spotless" version "6.25.0" + id "com.diffplug.spotless" version "7.0.2" } description = 'Apache Thrift Java Library' diff --git a/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java b/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java index fee495ca762..02a14d07eec 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java +++ b/lib/java/src/test/java/org/apache/thrift/test/EqualityTest.java @@ -20,10 +20,7 @@ /* This program was generated by the following Python script: -#!/usr/bin/python2.5 - -# Remove this when Python 2.6 hits the streets. -from __future__ import with_statement +#!/usr/bin/python3 import sys import os.path diff --git a/lib/js/Gruntfile.js b/lib/js/Gruntfile.js index 97713140a25..089ef8f6610 100644 --- a/lib/js/Gruntfile.js +++ b/lib/js/Gruntfile.js @@ -5,47 +5,48 @@ // Grunt Setup - npm install //reads the ./package.json and installs project dependencies // Run grunt - npx grunt // uses project-local installed version of grunt (from package.json) -module.exports = function(grunt) { - 'use strict'; +module.exports = function (grunt) { + "use strict"; grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), + pkg: grunt.file.readJSON("package.json"), concat: { options: { - separator: ';' + separator: ";", }, dist: { - src: ['src/**/*.js'], - dest: 'dist/<%= pkg.name %>.js' - } + src: ["src/**/*.js"], + dest: "dist/<%= pkg.name %>.js", + }, }, - jsdoc : { - dist : { - src: ['src/*.js', './README.md'], - options: { - destination: 'doc' - } - } + jsdoc: { + dist: { + src: ["src/*.js", "./README.md"], + options: { + destination: "doc", + }, + }, }, uglify: { options: { - banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' + banner: + '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n', }, dist: { files: { - 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] - } - } + "dist/<%= pkg.name %>.min.js": ["<%= concat.dist.dest %>"], + }, + }, }, shell: { InstallThriftJS: { - command: 'cp src/thrift.js test/build/js/thrift.js' + command: "cp src/thrift.js test/build/js/thrift.js", }, InstallThriftNodeJSDep: { - command: 'cd ../.. && npm install' + command: "cd ../.. && npm install", }, InstallTestLibs: { - command: 'cd test && ant download_jslibs' + command: "cd test && ant download_jslibs", }, ThriftGen: { command: [ @@ -55,34 +56,38 @@ module.exports = function(grunt) { '"../../compiler/cpp/thrift" -gen js:node --out test/gen-nodejs ../../test/v0.16/ThriftTest.thrift', '"../../compiler/cpp/thrift" -gen js:es6 --out test/gen-js-es6 ../../test/v0.16/ThriftTest.thrift', '"../../compiler/cpp/thrift" -gen js:node,es6 --out ./test/gen-nodejs-es6 ../../test/v0.16/ThriftTest.thrift', - ].join(' && ') + ].join(" && "), }, ThriftGenJQ: { - command: '../../compiler/cpp/thrift -gen js:jquery -gen js:node -o test ../../test/v0.16/ThriftTest.thrift' + command: + "../../compiler/cpp/thrift -gen js:jquery -gen js:node -o test ../../test/v0.16/ThriftTest.thrift", }, ThriftGenDeepConstructor: { - command: '../../compiler/cpp/thrift -gen js -o test ../../test/JsDeepConstructorTest.thrift' + command: + "../../compiler/cpp/thrift -gen js -o test ../../test/JsDeepConstructorTest.thrift", }, ThriftBrowserifyNodeInt64: { command: [ - './node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js', - './node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js', - './node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js' - ].join(' && ') + "./node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js", + "./node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js", + "./node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js", + ].join(" && "), }, ThriftGenInt64: { - command: '../../compiler/cpp/thrift -gen js -o test ../../test/Int64Test.thrift' + command: + "../../compiler/cpp/thrift -gen js -o test ../../test/Int64Test.thrift", }, ThriftGenDoubleConstants: { - command: '../../compiler/cpp/thrift -gen js -o test ../../test/DoubleConstantsTest.thrift' + command: + "../../compiler/cpp/thrift -gen js -o test ../../test/DoubleConstantsTest.thrift", }, ThriftTestServer: { options: { async: true, execOptions: { cwd: "./test", - env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} - } + env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" }, + }, }, command: "node server_http.js", }, @@ -91,8 +96,8 @@ module.exports = function(grunt) { async: true, execOptions: { cwd: "./test", - env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} - } + env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" }, + }, }, command: "node server_http.js --es6", }, @@ -101,8 +106,8 @@ module.exports = function(grunt) { async: true, execOptions: { cwd: "./test", - env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} - } + env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" }, + }, }, command: "node server_https.js", }, @@ -111,8 +116,8 @@ module.exports = function(grunt) { async: true, execOptions: { cwd: "./test", - env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} - } + env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" }, + }, }, command: "node server_https.js --es6", }, @@ -120,213 +125,201 @@ module.exports = function(grunt) { qunit: { ThriftJS: { options: { - urls: [ - 'http://localhost:8089/test-nojq.html' - ], + urls: ["http://localhost:8089/test-nojq.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], }, - } + }, }, ThriftJSJQ: { options: { - urls: [ - 'http://localhost:8089/test.html' - ], + urls: ["http://localhost:8089/test.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], }, - } + }, }, ThriftJS_DoubleRendering: { options: { - urls: [ - 'http://localhost:8089/test-double-rendering.html' - ], + urls: ["http://localhost:8089/test-double-rendering.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], ignoreHTTPSErrors: true, }, - } + }, }, ThriftJS_Int64: { options: { - urls: [ - 'http://localhost:8089/test-int64.html' - ], + urls: ["http://localhost:8089/test-int64.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], ignoreHTTPSErrors: true, }, - } + }, }, ThriftWS: { options: { - urls: [ - 'http://localhost:8089/testws.html' - ], + urls: ["http://localhost:8089/testws.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], }, - } + }, }, ThriftJS_TLS: { options: { - urls: [ - 'https://localhost:8091/test-nojq.html' - ], + urls: ["https://localhost:8091/test-nojq.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], ignoreHTTPSErrors: true, }, - } + }, }, ThriftJSJQ_TLS: { options: { - urls: [ - 'https://localhost:8091/test.html' - ], + urls: ["https://localhost:8091/test.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], ignoreHTTPSErrors: true, }, - } + }, }, ThriftWS_TLS: { options: { - urls: [ - 'https://localhost:8091/testws.html' - ], + urls: ["https://localhost:8091/testws.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], ignoreHTTPSErrors: true, }, - } + }, }, ThriftDeepConstructor: { options: { - urls: [ - 'http://localhost:8089/test-deep-constructor.html' - ], + urls: ["http://localhost:8089/test-deep-constructor.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], }, - } + }, }, ThriftWSES6: { options: { - urls: [ - 'http://localhost:8088/test-es6.html' - ], + urls: ["http://localhost:8088/test-es6.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], }, - } - } + }, + }, }, jshint: { // The main Thrift library file. not es6 yet :( lib: { - src: ['src/**/*.js'], + src: ["src/**/*.js"], }, // The test files use es6 test: { - src: ['Gruntfile.js', 'test/*.js'], + src: ["Gruntfile.js", "test/*.js"], options: { esversion: 6, - } + }, }, gen_js_code: { - src: ['test/gen-js/*.js', 'test/gen-js-jquery/*.js'], + src: ["test/gen-js/*.js", "test/gen-js-jquery/*.js"], }, gen_es6_code: { - src: ['test/gen-js-es6/*.js'], + src: ["test/gen-js-es6/*.js"], options: { esversion: 6, - } + }, }, gen_node_code: { - src: ['test/gen-nodejs/*.js'], + src: ["test/gen-nodejs/*.js"], options: { node: true, - } + }, }, gen_node_es6_code: { - src: ['test/gen-nodejs-es6/*.js'], + src: ["test/gen-nodejs-es6/*.js"], options: { node: true, esversion: 6, - } - } + }, + }, }, }); - grunt.loadNpmTasks('grunt-contrib-uglify'); - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-contrib-qunit'); - grunt.loadNpmTasks('grunt-contrib-concat'); - grunt.loadNpmTasks('grunt-jsdoc'); - grunt.loadNpmTasks('grunt-shell-spawn'); + grunt.loadNpmTasks("grunt-contrib-uglify"); + grunt.loadNpmTasks("grunt-contrib-jshint"); + grunt.loadNpmTasks("grunt-contrib-qunit"); + grunt.loadNpmTasks("grunt-contrib-concat"); + grunt.loadNpmTasks("grunt-jsdoc"); + grunt.loadNpmTasks("grunt-shell-spawn"); - grunt.registerTask('wait', 'Wait just one second for the server to start', function () { - var done = this.async(); - setTimeout(function() { - done(true); - }, 1000); - }); + grunt.registerTask( + "wait", + "Wait just one second for the server to start", + function () { + var done = this.async(); + setTimeout(function () { + done(true); + }, 1000); + }, + ); - grunt.registerTask('CreateDirectories', 'Creating required local directories', function () { - grunt.file.mkdir('test/build/js/lib'); - grunt.file.mkdir('test/gen-js'); - grunt.file.mkdir('test/gen-js-jquery'); - grunt.file.mkdir('test/gen-nodejs'); - grunt.file.mkdir('test/gen-js-es6'); - grunt.file.mkdir('test/gen-nodejs-es6'); -}); + grunt.registerTask( + "CreateDirectories", + "Creating required local directories", + function () { + grunt.file.mkdir("test/build/js/lib"); + grunt.file.mkdir("test/gen-js"); + grunt.file.mkdir("test/gen-js-jquery"); + grunt.file.mkdir("test/gen-nodejs"); + grunt.file.mkdir("test/gen-js-es6"); + grunt.file.mkdir("test/gen-nodejs-es6"); + }, + ); - grunt.registerTask('installAndGenerate', [ - 'CreateDirectories', - 'shell:InstallThriftJS', - 'shell:InstallThriftNodeJSDep', - 'shell:ThriftGen', - 'shell:ThriftGenDeepConstructor', - 'shell:ThriftGenDoubleConstants', - 'shell:InstallTestLibs', - 'shell:ThriftBrowserifyNodeInt64', - 'shell:ThriftGenInt64' + grunt.registerTask("installAndGenerate", [ + "CreateDirectories", + "shell:InstallThriftJS", + "shell:InstallThriftNodeJSDep", + "shell:ThriftGen", + "shell:ThriftGenDeepConstructor", + "shell:ThriftGenDoubleConstants", + "shell:InstallTestLibs", + "shell:ThriftBrowserifyNodeInt64", + "shell:ThriftGenInt64", ]); - grunt.registerTask('test', [ - 'installAndGenerate', - 'jshint', - 'shell:ThriftTestServer', - 'shell:ThriftTestServer_TLS', - 'shell:ThriftTestServerES6', - 'shell:ThriftTestServerES6_TLS', - 'wait', - 'qunit:ThriftDeepConstructor', - 'qunit:ThriftJS', - 'qunit:ThriftJS_TLS', - 'qunit:ThriftJS_DoubleRendering', - 'qunit:ThriftWS', - 'qunit:ThriftJSJQ', - 'qunit:ThriftJSJQ_TLS', - 'qunit:ThriftWSES6', - 'qunit:ThriftJS_Int64', - 'shell:ThriftTestServer:kill', - 'shell:ThriftTestServer_TLS:kill', - 'shell:ThriftTestServerES6:kill', - 'shell:ThriftTestServerES6_TLS:kill', + grunt.registerTask("test", [ + "installAndGenerate", + "jshint", + "shell:ThriftTestServer", + "shell:ThriftTestServer_TLS", + "shell:ThriftTestServerES6", + "shell:ThriftTestServerES6_TLS", + "wait", + "qunit:ThriftDeepConstructor", + "qunit:ThriftJS", + "qunit:ThriftJS_TLS", + "qunit:ThriftJS_DoubleRendering", + "qunit:ThriftWS", + "qunit:ThriftJSJQ", + "qunit:ThriftJSJQ_TLS", + "qunit:ThriftWSES6", + "qunit:ThriftJS_Int64", + "shell:ThriftTestServer:kill", + "shell:ThriftTestServer_TLS:kill", + "shell:ThriftTestServerES6:kill", + "shell:ThriftTestServerES6_TLS:kill", ]); - grunt.registerTask('default', ['test', 'concat', 'uglify', 'jsdoc']); + grunt.registerTask("default", ["test", "concat", "uglify", "jsdoc"]); }; diff --git a/lib/kotlin/settings.gradle.kts b/lib/kotlin/settings.gradle.kts index 1141390503d..77672a55512 100644 --- a/lib/kotlin/settings.gradle.kts +++ b/lib/kotlin/settings.gradle.kts @@ -18,7 +18,7 @@ */ pluginManagement { plugins { - kotlin("jvm") version "2.0.21" + kotlin("jvm") version "2.1.10" id("com.ncorti.ktfmt.gradle") version "0.20.1" } } diff --git a/lib/netstd/Thrift/Protocol/TBinaryProtocol.cs b/lib/netstd/Thrift/Protocol/TBinaryProtocol.cs index 186d220cbf7..44fa9f7d995 100644 --- a/lib/netstd/Thrift/Protocol/TBinaryProtocol.cs +++ b/lib/netstd/Thrift/Protocol/TBinaryProtocol.cs @@ -255,7 +255,7 @@ public override async ValueTask ReadMessageBeginAsync(CancellationToke public override Task ReadMessageEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - Transport.ResetConsumedMessageSize(); + Transport.ResetMessageSizeAndConsumedBytes(); return Task.CompletedTask; } diff --git a/lib/netstd/Thrift/Protocol/TCompactProtocol.cs b/lib/netstd/Thrift/Protocol/TCompactProtocol.cs index 8e5d00d14f6..1fd7e50ce54 100644 --- a/lib/netstd/Thrift/Protocol/TCompactProtocol.cs +++ b/lib/netstd/Thrift/Protocol/TCompactProtocol.cs @@ -461,7 +461,7 @@ public override async ValueTask ReadMessageBeginAsync(CancellationToke public override Task ReadMessageEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - Transport.ResetConsumedMessageSize(); + Transport.ResetMessageSizeAndConsumedBytes(); return Task.CompletedTask; } diff --git a/lib/netstd/Thrift/Protocol/TJSONProtocol.cs b/lib/netstd/Thrift/Protocol/TJSONProtocol.cs index 02cf3ed4e7f..ae37a807525 100644 --- a/lib/netstd/Thrift/Protocol/TJSONProtocol.cs +++ b/lib/netstd/Thrift/Protocol/TJSONProtocol.cs @@ -700,7 +700,7 @@ public override async Task ReadMessageEndAsync(CancellationToken cancellationTok { cancellationToken.ThrowIfCancellationRequested(); await ReadJsonArrayEndAsync(cancellationToken); - Transport.ResetConsumedMessageSize(); + Transport.ResetMessageSizeAndConsumedBytes(); } public override async ValueTask ReadStructBeginAsync(CancellationToken cancellationToken) diff --git a/lib/netstd/Thrift/Protocol/TProtocolDecorator.cs b/lib/netstd/Thrift/Protocol/TProtocolDecorator.cs index c75cc6319ac..8e7fb94b91f 100644 --- a/lib/netstd/Thrift/Protocol/TProtocolDecorator.cs +++ b/lib/netstd/Thrift/Protocol/TProtocolDecorator.cs @@ -158,7 +158,7 @@ public override async Task ReadMessageEndAsync(CancellationToken cancellationTok { cancellationToken.ThrowIfCancellationRequested(); await _wrappedProtocol.ReadMessageEndAsync(cancellationToken); - Transport.ResetConsumedMessageSize(); + Transport.ResetMessageSizeAndConsumedBytes(); } public override async ValueTask ReadStructBeginAsync(CancellationToken cancellationToken) diff --git a/lib/netstd/Thrift/Transport/Client/THttpTransport.cs b/lib/netstd/Thrift/Transport/Client/THttpTransport.cs index 16e228ba3d3..4467681ae1f 100644 --- a/lib/netstd/Thrift/Transport/Client/THttpTransport.cs +++ b/lib/netstd/Thrift/Transport/Client/THttpTransport.cs @@ -278,7 +278,7 @@ public override async Task FlushAsync(CancellationToken cancellationToken) finally { _outputStream = new MemoryStream(); - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); } } diff --git a/lib/netstd/Thrift/Transport/Client/TMemoryBufferTransport.cs b/lib/netstd/Thrift/Transport/Client/TMemoryBufferTransport.cs index 5773d30cb57..47013782c1f 100644 --- a/lib/netstd/Thrift/Transport/Client/TMemoryBufferTransport.cs +++ b/lib/netstd/Thrift/Transport/Client/TMemoryBufferTransport.cs @@ -115,7 +115,7 @@ public void Seek(int delta, SeekOrigin origin) throw new ArgumentException("Cannot seek outside of the valid range",nameof(origin)); Position = newPos; - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); CountConsumedMessageBytes(Position); } @@ -145,7 +145,7 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati public override Task FlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); return Task.CompletedTask; } diff --git a/lib/netstd/Thrift/Transport/Client/TNamedPipeTransport.cs b/lib/netstd/Thrift/Transport/Client/TNamedPipeTransport.cs index 8e60f9f5e60..3ed1b6cda88 100644 --- a/lib/netstd/Thrift/Transport/Client/TNamedPipeTransport.cs +++ b/lib/netstd/Thrift/Transport/Client/TNamedPipeTransport.cs @@ -54,7 +54,7 @@ public override async Task OpenAsync(CancellationToken cancellationToken) } await PipeStream.ConnectAsync( ConnectTimeout, cancellationToken); - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); } public override void Close() @@ -112,7 +112,7 @@ public override async Task WriteAsync(byte[] buffer, int offset, int length, Can public override async Task FlushAsync(CancellationToken cancellationToken) { await PipeStream.FlushAsync(cancellationToken); - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); } diff --git a/lib/netstd/Thrift/Transport/Client/TStreamTransport.cs b/lib/netstd/Thrift/Transport/Client/TStreamTransport.cs index 7237b8dd27d..a1950014a67 100644 --- a/lib/netstd/Thrift/Transport/Client/TStreamTransport.cs +++ b/lib/netstd/Thrift/Transport/Client/TStreamTransport.cs @@ -16,6 +16,7 @@ // under the License. using System; +using System.Drawing; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -46,10 +47,28 @@ protected Stream InputStream { get => _InputStream; set { _InputStream = value; - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(-1); // full reset to configured maximum + UpdateKnownMessageSize(-1); // adjust to real stream size } } + public override void UpdateKnownMessageSize(long size) + { + long adjusted = 0; + + if (InputStream != null) + { + adjusted = MaxMessageSize; + if (size > 0) + adjusted = Math.Min(adjusted, size); + if( InputStream.CanSeek) + adjusted = Math.Min(adjusted, InputStream.Length); + } + + base.UpdateKnownMessageSize(adjusted); + } + + public override bool IsOpen => true; public override Task OpenAsync(CancellationToken cancellationToken) @@ -106,7 +125,7 @@ public override async Task WriteAsync(byte[] buffer, int offset, int length, Can public override async Task FlushAsync(CancellationToken cancellationToken) { await OutputStream.FlushAsync(cancellationToken); - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); } diff --git a/lib/netstd/Thrift/Transport/Layered/TBufferedTransport.cs b/lib/netstd/Thrift/Transport/Layered/TBufferedTransport.cs index 7474b7f9359..977dcbfd119 100644 --- a/lib/netstd/Thrift/Transport/Layered/TBufferedTransport.cs +++ b/lib/netstd/Thrift/Transport/Layered/TBufferedTransport.cs @@ -179,10 +179,10 @@ public override void CheckReadBytesAvailable(long numBytes) } } - public override void ResetConsumedMessageSize(long newSize = -1) + public override void ResetMessageSizeAndConsumedBytes(long newSize = -1) { - base.ResetConsumedMessageSize(newSize); - ReadBuffer.ResetConsumedMessageSize(newSize); + base.ResetMessageSizeAndConsumedBytes(newSize); + ReadBuffer.ResetMessageSizeAndConsumedBytes(newSize); } private void CheckNotDisposed() diff --git a/lib/netstd/Thrift/Transport/Layered/TFramedTransport.cs b/lib/netstd/Thrift/Transport/Layered/TFramedTransport.cs index 5e67f10cda6..faa3fa6e90f 100644 --- a/lib/netstd/Thrift/Transport/Layered/TFramedTransport.cs +++ b/lib/netstd/Thrift/Transport/Layered/TFramedTransport.cs @@ -191,10 +191,10 @@ protected override void Dispose(bool disposing) IsDisposed = true; } - public override void ResetConsumedMessageSize(long newSize = -1) + public override void ResetMessageSizeAndConsumedBytes(long newSize = -1) { - base.ResetConsumedMessageSize(newSize); - ReadBuffer.ResetConsumedMessageSize(newSize); + base.ResetMessageSizeAndConsumedBytes(newSize); + ReadBuffer.ResetMessageSizeAndConsumedBytes(newSize); } } } diff --git a/lib/netstd/Thrift/Transport/Layered/TLayeredTransport.cs b/lib/netstd/Thrift/Transport/Layered/TLayeredTransport.cs index 3d855a4f5f0..f9a4ce477af 100644 --- a/lib/netstd/Thrift/Transport/Layered/TLayeredTransport.cs +++ b/lib/netstd/Thrift/Transport/Layered/TLayeredTransport.cs @@ -43,9 +43,9 @@ public override void CheckReadBytesAvailable(long numBytes) InnerTransport.CheckReadBytesAvailable(numBytes); } - public override void ResetConsumedMessageSize(long newSize = -1) + public override void ResetMessageSizeAndConsumedBytes(long newSize = -1) { - InnerTransport.ResetConsumedMessageSize(newSize); + InnerTransport.ResetMessageSizeAndConsumedBytes(newSize); } } } diff --git a/lib/netstd/Thrift/Transport/Server/TNamedPipeServerTransport.cs b/lib/netstd/Thrift/Transport/Server/TNamedPipeServerTransport.cs index 12fc9d3ef74..1b6a21f53e9 100644 --- a/lib/netstd/Thrift/Transport/Server/TNamedPipeServerTransport.cs +++ b/lib/netstd/Thrift/Transport/Server/TNamedPipeServerTransport.cs @@ -424,7 +424,7 @@ public override async Task WriteAsync(byte[] buffer, int offset, int length, Can public override async Task FlushAsync(CancellationToken cancellationToken) { await PipeStream.FlushAsync(cancellationToken); - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); } protected override void Dispose(bool disposing) diff --git a/lib/netstd/Thrift/Transport/TEndpointTransport.cs b/lib/netstd/Thrift/Transport/TEndpointTransport.cs index 6c781010583..27fb48daf96 100644 --- a/lib/netstd/Thrift/Transport/TEndpointTransport.cs +++ b/lib/netstd/Thrift/Transport/TEndpointTransport.cs @@ -37,13 +37,13 @@ public TEndpointTransport( TConfiguration config) _configuration = config ?? new TConfiguration(); Debug.Assert(Configuration != null); - ResetConsumedMessageSize(); + ResetMessageSizeAndConsumedBytes(); } /// /// Resets RemainingMessageSize to the configured maximum /// - public override void ResetConsumedMessageSize(long newSize = -1) + public override void ResetMessageSizeAndConsumedBytes(long newSize = -1) { // full reset if (newSize < 0) @@ -70,7 +70,7 @@ public override void ResetConsumedMessageSize(long newSize = -1) public override void UpdateKnownMessageSize(long size) { var consumed = KnownMessageSize - RemainingMessageSize; - ResetConsumedMessageSize(size); + ResetMessageSizeAndConsumedBytes(size); CountConsumedMessageBytes(consumed); } @@ -80,7 +80,7 @@ public override void UpdateKnownMessageSize(long size) /// public override void CheckReadBytesAvailable(long numBytes) { - if (RemainingMessageSize < numBytes) + if ((RemainingMessageSize < numBytes) || (numBytes < 0)) throw new TTransportException(TTransportException.ExceptionType.EndOfFile, "MaxMessageSize reached"); } diff --git a/lib/netstd/Thrift/Transport/TTransport.cs b/lib/netstd/Thrift/Transport/TTransport.cs index 44202249243..77ef281674e 100644 --- a/lib/netstd/Thrift/Transport/TTransport.cs +++ b/lib/netstd/Thrift/Transport/TTransport.cs @@ -39,7 +39,7 @@ public abstract class TTransport : IDisposable public abstract TConfiguration Configuration { get; } public abstract void UpdateKnownMessageSize(long size); public abstract void CheckReadBytesAvailable(long numBytes); - public abstract void ResetConsumedMessageSize(long newSize = -1); + public abstract void ResetMessageSizeAndConsumedBytes(long newSize = -1); public void Dispose() { Dispose(true); diff --git a/lib/nodejs/examples/client.js b/lib/nodejs/examples/client.js index c83b342349f..29dac26b98f 100644 --- a/lib/nodejs/examples/client.js +++ b/lib/nodejs/examples/client.js @@ -16,28 +16,30 @@ * specific language governing permissions and limitations * under the License. */ -var thrift = require('thrift'); +var thrift = require("thrift"); -var UserStorage = require('./gen-nodejs/UserStorage.js'), - ttypes = require('./gen-nodejs/user_types'); +var UserStorage = require("./gen-nodejs/UserStorage.js"), + ttypes = require("./gen-nodejs/user_types"); -var connection = thrift.createConnection('localhost', 9090), - client = thrift.createClient(UserStorage, connection); +var connection = thrift.createConnection("localhost", 9090), + client = thrift.createClient(UserStorage, connection); -var user = new ttypes.UserProfile({uid: 1, - name: "Mark Slee", - blurb: "I'll find something to put here."}); +var user = new ttypes.UserProfile({ + uid: 1, + name: "Mark Slee", + blurb: "I'll find something to put here.", +}); -connection.on('error', function(err) { +connection.on("error", function (err) { console.error(err); }); -client.store(user, function(err, response) { +client.store(user, function (err, response) { if (err) { console.error(err); } else { console.log("client stored:", user.uid); - client.retrieve(user.uid, function(err, responseUser) { + client.retrieve(user.uid, function (err, responseUser) { if (err) { console.error(err); } else { diff --git a/lib/nodejs/examples/client_multitransport.js b/lib/nodejs/examples/client_multitransport.js index 1e37de32f4f..05e5c315d22 100644 --- a/lib/nodejs/examples/client_multitransport.js +++ b/lib/nodejs/examples/client_multitransport.js @@ -16,43 +16,61 @@ * specific language governing permissions and limitations * under the License. */ -var thrift = require('thrift'), - ttransport = require('thrift/transport'); +var thrift = require("thrift"), + ttransport = require("thrift/transport"); -var UserStorage = require('./gen-nodejs/UserStorage'), - ttypes = require('./gen-nodejs/user_types'); +var UserStorage = require("./gen-nodejs/UserStorage"), + ttypes = require("./gen-nodejs/user_types"); -var f_conn = thrift.createConnection('localhost', 9090), // default: framed - f_client = thrift.createClient(UserStorage, f_conn); -var b_conn = thrift.createConnection('localhost', 9091, {transport: ttransport.TBufferedTransport}), - b_client = thrift.createClient(UserStorage, b_conn); -var user1 = new ttypes.UserProfile({uid: 1, - name: "Mark Slee", - blurb: "I'll find something to put here."}); -var user2 = new ttypes.UserProfile({uid: 2, - name: "Satoshi Tagomori", - blurb: "ok, let's test with buffered transport."}); +var f_conn = thrift.createConnection("localhost", 9090), // default: framed + f_client = thrift.createClient(UserStorage, f_conn); +var b_conn = thrift.createConnection("localhost", 9091, { + transport: ttransport.TBufferedTransport, + }), + b_client = thrift.createClient(UserStorage, b_conn); +var user1 = new ttypes.UserProfile({ + uid: 1, + name: "Mark Slee", + blurb: "I'll find something to put here.", +}); +var user2 = new ttypes.UserProfile({ + uid: 2, + name: "Satoshi Tagomori", + blurb: "ok, let's test with buffered transport.", +}); -f_conn.on('error', function(err) { +f_conn.on("error", function (err) { console.error("framed:", err); }); -f_client.store(user1, function(err, response) { - if (err) { console.error(err); return; } +f_client.store(user1, function (err, response) { + if (err) { + console.error(err); + return; + } console.log("stored:", user1.uid, " as ", user1.name); - b_client.retrieve(user1.uid, function(err, responseUser) { - if (err) { console.error(err); return; } + b_client.retrieve(user1.uid, function (err, responseUser) { + if (err) { + console.error(err); + return; + } console.log("retrieved:", responseUser.uid, " as ", responseUser.name); }); }); -b_client.store(user2, function(err, response) { - if (err) { console.error(err); return; } +b_client.store(user2, function (err, response) { + if (err) { + console.error(err); + return; + } console.log("stored:", user2.uid, " as ", user2.name); - f_client.retrieve(user2.uid, function(err, responseUser) { - if (err) { console.error(err); return; } + f_client.retrieve(user2.uid, function (err, responseUser) { + if (err) { + console.error(err); + return; + } console.log("retrieved:", responseUser.uid, " as ", responseUser.name); }); }); diff --git a/lib/nodejs/examples/hello.js b/lib/nodejs/examples/hello.js index 8b7c4e4ea00..5f1b6822519 100644 --- a/lib/nodejs/examples/hello.js +++ b/lib/nodejs/examples/hello.js @@ -16,46 +16,46 @@ * specific language governing permissions and limitations * under the License. */ -var thrift = require('thrift'); -var HelloSvc = require('./gen-nodejs/HelloSvc.js'); -var TimesTwoSvc = require('./gen-nodejs/TimesTwo.js'); +var thrift = require("thrift"); +var HelloSvc = require("./gen-nodejs/HelloSvc.js"); +var TimesTwoSvc = require("./gen-nodejs/TimesTwo.js"); var helloHandler = { - hello_func: function(result) { - this.call_counter = this.call_counter || 0; - console.log("Client call: " + (++this.call_counter)); - result(null, "Hello Apache Thrift for JavaScript " + this.call_counter); - } -} + hello_func: function (result) { + this.call_counter = this.call_counter || 0; + console.log("Client call: " + ++this.call_counter); + result(null, "Hello Apache Thrift for JavaScript " + this.call_counter); + }, +}; var timesTwoHandler = { - dbl: function(val, result) { - console.log("Client call: " + val); - result(null, val * 2); - } -} + dbl: function (val, result) { + console.log("Client call: " + val); + result(null, val * 2); + }, +}; var helloService = { - transport: thrift.TBufferedTransport, - protocol: thrift.TJSONProtocol, - processor: HelloSvc, - handler: helloHandler + transport: thrift.TBufferedTransport, + protocol: thrift.TJSONProtocol, + processor: HelloSvc, + handler: helloHandler, }; var dblService = { - transport: thrift.TBufferedTransport, - protocol: thrift.TJSONProtocol, - processor: TimesTwoSvc, - handler: timesTwoHandler + transport: thrift.TBufferedTransport, + protocol: thrift.TJSONProtocol, + processor: TimesTwoSvc, + handler: timesTwoHandler, }; var ServerOptions = { - files: ".", - services: { - "/hello": helloService, - "/dbl": dblService, - } -} + files: ".", + services: { + "/hello": helloService, + "/dbl": dblService, + }, +}; var server = thrift.createWebServer(ServerOptions); var port = 8585; diff --git a/lib/nodejs/examples/httpClient.js b/lib/nodejs/examples/httpClient.js index 19cc0c36278..155b5f48915 100644 --- a/lib/nodejs/examples/httpClient.js +++ b/lib/nodejs/examples/httpClient.js @@ -1,23 +1,21 @@ -var thrift = require('thrift'); -var helloSvc = require('./gen-nodejs/HelloSvc.js'); +var thrift = require("thrift"); +var helloSvc = require("./gen-nodejs/HelloSvc.js"); var options = { - transport: thrift.TBufferedTransport, - protocol: thrift.TJSONProtocol, - path: "/hello", - headers: {"Connection": "close"}, - https: false + transport: thrift.TBufferedTransport, + protocol: thrift.TJSONProtocol, + path: "/hello", + headers: { Connection: "close" }, + https: false, }; var connection = thrift.createHttpConnection("localhost", 9090, options); var client = thrift.createHttpClient(helloSvc, connection); -connection.on("error", function(err) { - console.log("Error: " + err); +connection.on("error", function (err) { + console.log("Error: " + err); }); -client.hello_func(function(error, result) { - console.log("Msg from server: " + result); +client.hello_func(function (error, result) { + console.log("Msg from server: " + result); }); - - diff --git a/lib/nodejs/examples/httpServer.js b/lib/nodejs/examples/httpServer.js index acae1369a2f..c4cbc9f8961 100644 --- a/lib/nodejs/examples/httpServer.js +++ b/lib/nodejs/examples/httpServer.js @@ -1,31 +1,30 @@ -var thrift = require('thrift'); -var helloSvc = require('./gen-nodejs/HelloSvc'); +var thrift = require("thrift"); +var helloSvc = require("./gen-nodejs/HelloSvc"); -//ServiceHandler: Implement the hello service +//ServiceHandler: Implement the hello service var helloHandler = { hello_func: function (result) { console.log("Received Hello call"); result(null, "Hello from Node.js"); - } + }, }; //ServiceOptions: The I/O stack for the service -var helloSvcOpt = { - handler: helloHandler, - processor: helloSvc, - protocol: thrift.TJSONProtocol, - transport: thrift.TBufferedTransport -}; +var helloSvcOpt = { + handler: helloHandler, + processor: helloSvc, + protocol: thrift.TJSONProtocol, + transport: thrift.TBufferedTransport, +}; //ServerOptions: Define server features -var serverOpt = { - services: { - "/hello": helloSvcOpt - } -} +var serverOpt = { + services: { + "/hello": helloSvcOpt, + }, +}; -//Create and start the web server -var port = 9090; -thrift.createWebServer(serverOpt).listen(port); +//Create and start the web server +var port = 9090; +thrift.createWebServer(serverOpt).listen(port); console.log("Http/Thrift Server running on port: " + port); - diff --git a/lib/nodejs/examples/parse.js b/lib/nodejs/examples/parse.js index 168a1aeeace..8513e4c2f02 100644 --- a/lib/nodejs/examples/parse.js +++ b/lib/nodejs/examples/parse.js @@ -35,11 +35,11 @@ */ function parseThrift(thriftEncodedData, callback) { - var thrift = require('thrift'); + var thrift = require("thrift"); var transport = new thrift.TFramedTransport(thriftEncodedData); - var protocol = new thrift.TBinaryProtocol(transport); + var protocol = new thrift.TBinaryProtocol(transport); - var clientClass = require('../gen-nodejs/GENERATED').YOUR_CLASS_NAME; + var clientClass = require("../gen-nodejs/GENERATED").YOUR_CLASS_NAME; var client = new clientClass(); client.read(protocol); callback(null, client); diff --git a/lib/nodejs/examples/server.js b/lib/nodejs/examples/server.js index 1c482fe71f7..41492cbe471 100644 --- a/lib/nodejs/examples/server.js +++ b/lib/nodejs/examples/server.js @@ -16,21 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -var thrift = require('thrift'); +var thrift = require("thrift"); -var UserStorage = require('./gen-nodejs/UserStorage.js'), - ttypes = require('./gen-nodejs/user_types'); +var UserStorage = require("./gen-nodejs/UserStorage.js"), + ttypes = require("./gen-nodejs/user_types"); var users = {}; var server = thrift.createServer(UserStorage, { - store: function(user, result) { + store: function (user, result) { console.log("server stored:", user.uid); users[user.uid] = user; result(null); }, - retrieve: function(uid, result) { + retrieve: function (uid, result) { console.log("server retrieved:", uid); result(null, users[uid]); }, diff --git a/lib/nodejs/examples/server_http.js b/lib/nodejs/examples/server_http.js index ef2dc83a295..235f6754885 100644 --- a/lib/nodejs/examples/server_http.js +++ b/lib/nodejs/examples/server_http.js @@ -16,38 +16,46 @@ * specific language governing permissions and limitations * under the License. */ -var connect = require('connect'); -var thrift = require('thrift'); +var connect = require("connect"); +var thrift = require("thrift"); -var UserStorage = require('./gen-nodejs/UserStorage'), - ttypes = require('./gen-nodejs/user_types'); +var UserStorage = require("./gen-nodejs/UserStorage"), + ttypes = require("./gen-nodejs/user_types"); var users = {}; -var store = function(user, result) { +var store = function (user, result) { console.log("stored:", user.uid); users[user.uid] = user; result(null); }; -var retrieve = function(uid, result) { +var retrieve = function (uid, result) { console.log("retrieved:", uid); result(null, users[uid]); }; var server_http = thrift.createHttpServer(UserStorage, { store: store, - retrieve: retrieve + retrieve: retrieve, }); server_http.listen(9090); -var server_connect = connect(thrift.httpMiddleware(UserStorage, { - store: store, - retrieve: retrieve -})); +var server_connect = connect( + thrift.httpMiddleware(UserStorage, { + store: store, + retrieve: retrieve, + }), +); server_http.listen(9091); -var server_connect_json = connect(thrift.httpMiddleware(UserStorage, { - store: store, - retrieve: retrieve -}, {protocol: thrift.TJSONProtocol})); +var server_connect_json = connect( + thrift.httpMiddleware( + UserStorage, + { + store: store, + retrieve: retrieve, + }, + { protocol: thrift.TJSONProtocol }, + ), +); server_connect_json.listen(9092); diff --git a/lib/nodejs/examples/server_multitransport.js b/lib/nodejs/examples/server_multitransport.js index a348e684798..3dc0b17113c 100644 --- a/lib/nodejs/examples/server_multitransport.js +++ b/lib/nodejs/examples/server_multitransport.js @@ -16,31 +16,35 @@ * specific language governing permissions and limitations * under the License. */ -var thrift = require('thrift'), - ttransport = require('thrift/transport'); +var thrift = require("thrift"), + ttransport = require("thrift/transport"); -var UserStorage = require('./gen-nodejs/UserStorage'), - ttypes = require('./gen-nodejs/user_types'); +var UserStorage = require("./gen-nodejs/UserStorage"), + ttypes = require("./gen-nodejs/user_types"); var users = {}; -var store = function(user, result) { +var store = function (user, result) { console.log("stored:", user.uid); users[user.uid] = user; result(null); }; -var retrieve = function(uid, result) { +var retrieve = function (uid, result) { console.log("retrieved:", uid); result(null, users[uid]); }; var server_framed = thrift.createServer(UserStorage, { store: store, - retrieve: retrieve + retrieve: retrieve, }); server_framed.listen(9090); -var server_buffered = thrift.createServer(UserStorage, { - store: store, - retrieve: retrieve -}, {transport: ttransport.TBufferedTransport}); +var server_buffered = thrift.createServer( + UserStorage, + { + store: store, + retrieve: retrieve, + }, + { transport: ttransport.TBufferedTransport }, +); server_buffered.listen(9091); diff --git a/lib/nodejs/lib/thrift/binary.js b/lib/nodejs/lib/thrift/binary.js index 9813ffdb146..e8bbee76f23 100644 --- a/lib/nodejs/lib/thrift/binary.js +++ b/lib/nodejs/lib/thrift/binary.js @@ -26,11 +26,11 @@ var POW_48 = Math.pow(2, 48); var POW_52 = Math.pow(2, 52); var POW_1022 = Math.pow(2, 1022); -exports.readByte = function(b){ - return b > 127 ? b-256 : b; +exports.readByte = function (b) { + return b > 127 ? b - 256 : b; }; -exports.readI16 = function(buff, off) { +exports.readI16 = function (buff, off) { off = off || 0; var v = buff[off + 1]; v += buff[off] << 8; @@ -40,7 +40,7 @@ exports.readI16 = function(buff, off) { return v; }; -exports.readI32 = function(buff, off) { +exports.readI32 = function (buff, off) { off = off || 0; var v = buff[off + 3]; v += buff[off + 2] << 8; @@ -52,14 +52,14 @@ exports.readI32 = function(buff, off) { return v; }; -exports.writeI16 = function(buff, v) { +exports.writeI16 = function (buff, v) { buff[1] = v & 0xff; v >>= 8; buff[0] = v & 0xff; return buff; }; -exports.writeI32 = function(buff, v) { +exports.writeI32 = function (buff, v) { buff[3] = v & 0xff; v >>= 8; buff[2] = v & 0xff; @@ -70,26 +70,26 @@ exports.writeI32 = function(buff, v) { return buff; }; -exports.readDouble = function(buff, off) { +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; - m += buff[off+5] << 16; - 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; + var m = buff[off + 7]; + m += buff[off + 6] << 8; + m += buff[off + 5] << 16; + 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; 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; @@ -106,10 +106,10 @@ exports.readDouble = function(buff, off) { * Based on code from the jspack module: * http://code.google.com/p/jspack/ */ -exports.writeDouble = function(buff, v) { +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) { @@ -127,22 +127,17 @@ exports.writeDouble = function(buff, v) { c *= 2; } - if (e + 1023 >= 2047) - { + if (e + 1023 >= 2047) { // 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; + 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; } } diff --git a/lib/nodejs/lib/thrift/binary_protocol.js b/lib/nodejs/lib/thrift/binary_protocol.js index af8836cf52c..fc4df4ae95e 100644 --- a/lib/nodejs/lib/thrift/binary_protocol.js +++ b/lib/nodejs/lib/thrift/binary_protocol.js @@ -17,10 +17,10 @@ * under the License. */ -var log = require('./log'); -var binary = require('./binary'); -var Int64 = require('node-int64'); -var Thrift = require('./thrift'); +var log = require("./log"); +var binary = require("./binary"); +var Int64 = require("node-int64"); +var Thrift = require("./thrift"); var Type = Thrift.Type; module.exports = TBinaryProtocol; @@ -29,96 +29,90 @@ module.exports = TBinaryProtocol; // The largest integer value which can be represented in JavaScript is +/-2^53. // Bitwise operations convert numbers to 32 bit integers but perform sign extension // upon assigning values back to variables. -var VERSION_MASK = -65536, // 0xffff0000 - VERSION_1 = -2147418112, // 0x80010000 - TYPE_MASK = 0x000000ff; +var VERSION_MASK = -65536, // 0xffff0000 + VERSION_1 = -2147418112, // 0x80010000 + TYPE_MASK = 0x000000ff; TBinaryProtocol.VERSION_MASK = VERSION_MASK; TBinaryProtocol.VERSION_1 = VERSION_1; -TBinaryProtocol.TYPE_MASK = TYPE_MASK +TBinaryProtocol.TYPE_MASK = TYPE_MASK; 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; this._seqid = null; -}; +} -TBinaryProtocol.prototype.flush = function() { +TBinaryProtocol.prototype.flush = function () { return this.trans.flush(); }; -TBinaryProtocol.prototype.writeMessageBegin = function(name, type, seqid) { - if (this.strictWrite) { - this.writeI32(VERSION_1 | type); - this.writeString(name); - this.writeI32(seqid); - } else { - this.writeString(name); - this.writeByte(type); - this.writeI32(seqid); - } - // Record client seqid to find callback again - if (this._seqid !== null) { - log.warning('SeqId already set', { 'name': name }); - } else { - this._seqid = seqid; - this.trans.setCurrSeqId(seqid); - } +TBinaryProtocol.prototype.writeMessageBegin = function (name, type, seqid) { + if (this.strictWrite) { + this.writeI32(VERSION_1 | type); + this.writeString(name); + this.writeI32(seqid); + } else { + this.writeString(name); + this.writeByte(type); + this.writeI32(seqid); + } + // Record client seqid to find callback again + if (this._seqid !== null) { + log.warning("SeqId already set", { name: name }); + } else { + this._seqid = seqid; + this.trans.setCurrSeqId(seqid); + } }; -TBinaryProtocol.prototype.writeMessageEnd = function() { - if (this._seqid !== null) { - this._seqid = null; - } else { - log.warning('No seqid to unset'); - } +TBinaryProtocol.prototype.writeMessageEnd = function () { + if (this._seqid !== null) { + this._seqid = null; + } else { + log.warning("No seqid to unset"); + } }; -TBinaryProtocol.prototype.writeStructBegin = function(name) { -}; +TBinaryProtocol.prototype.writeStructBegin = function (name) {}; -TBinaryProtocol.prototype.writeStructEnd = function() { -}; +TBinaryProtocol.prototype.writeStructEnd = function () {}; -TBinaryProtocol.prototype.writeFieldBegin = function(name, type, id) { +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() { +TBinaryProtocol.prototype.writeFieldStop = function () { this.writeByte(Type.STOP); }; -TBinaryProtocol.prototype.writeMapBegin = function(ktype, vtype, size) { +TBinaryProtocol.prototype.writeMapBegin = function (ktype, vtype, size) { this.writeByte(ktype); this.writeByte(vtype); this.writeI32(size); }; -TBinaryProtocol.prototype.writeMapEnd = function() { -}; +TBinaryProtocol.prototype.writeMapEnd = function () {}; -TBinaryProtocol.prototype.writeListBegin = function(etype, size) { +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) { +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) { +TBinaryProtocol.prototype.writeBool = function (bool) { if (bool) { this.writeByte(1); } else { @@ -126,19 +120,19 @@ TBinaryProtocol.prototype.writeBool = function(bool) { } }; -TBinaryProtocol.prototype.writeByte = function(b) { +TBinaryProtocol.prototype.writeByte = function (b) { this.trans.write(new Buffer([b])); }; -TBinaryProtocol.prototype.writeI16 = function(i16) { +TBinaryProtocol.prototype.writeI16 = function (i16) { this.trans.write(binary.writeI16(new Buffer(2), i16)); }; -TBinaryProtocol.prototype.writeI32 = function(i32) { +TBinaryProtocol.prototype.writeI32 = function (i32) { this.trans.write(binary.writeI32(new Buffer(4), i32)); }; -TBinaryProtocol.prototype.writeI64 = function(i64) { +TBinaryProtocol.prototype.writeI64 = function (i64) { if (i64.buffer) { this.trans.write(i64.buffer); } else { @@ -146,108 +140,110 @@ TBinaryProtocol.prototype.writeI64 = function(i64) { } }; -TBinaryProtocol.prototype.writeDouble = function(dub) { +TBinaryProtocol.prototype.writeDouble = function (dub) { this.trans.write(binary.writeDouble(new Buffer(8), dub)); }; -TBinaryProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) { - if (typeof(arg) === 'string') { +TBinaryProtocol.prototype.writeStringOrBinary = function (name, encoding, arg) { + 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 this.writeI32(arg.length); this.trans.write(arg); } else { - throw new Error(name + ' called without a string/Buffer argument: ' + arg); + throw new Error(name + " called without a string/Buffer argument: " + arg); } }; -TBinaryProtocol.prototype.writeString = function(arg) { - this.writeStringOrBinary('writeString', 'utf8', arg); +TBinaryProtocol.prototype.writeString = function (arg) { + this.writeStringOrBinary("writeString", "utf8", arg); }; -TBinaryProtocol.prototype.writeBinary = function(arg) { - this.writeStringOrBinary('writeBinary', 'binary', arg); +TBinaryProtocol.prototype.writeBinary = function (arg) { + this.writeStringOrBinary("writeBinary", "binary", arg); }; -TBinaryProtocol.prototype.readMessageBegin = function() { +TBinaryProtocol.prototype.readMessageBegin = function () { var sz = this.readI32(); var type, name, seqid; 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(); seqid = this.readI32(); } - return {fname: name, mtype: type, rseqid: seqid}; + return { fname: name, mtype: type, rseqid: seqid }; }; -TBinaryProtocol.prototype.readMessageEnd = function() { -}; +TBinaryProtocol.prototype.readMessageEnd = function () {}; -TBinaryProtocol.prototype.readStructBegin = function() { - return {fname: ''}; +TBinaryProtocol.prototype.readStructBegin = function () { + return { fname: "" }; }; -TBinaryProtocol.prototype.readStructEnd = function() { -}; +TBinaryProtocol.prototype.readStructEnd = function () {}; -TBinaryProtocol.prototype.readFieldBegin = function() { +TBinaryProtocol.prototype.readFieldBegin = function () { var type = this.readByte(); if (type == Type.STOP) { - return {fname: null, ftype: type, fid: 0}; + return { fname: null, ftype: type, fid: 0 }; } var id = this.readI16(); - return {fname: null, ftype: type, fid: id}; + return { fname: null, ftype: type, fid: id }; }; -TBinaryProtocol.prototype.readFieldEnd = function() { -}; +TBinaryProtocol.prototype.readFieldEnd = function () {}; -TBinaryProtocol.prototype.readMapBegin = function() { +TBinaryProtocol.prototype.readMapBegin = function () { var ktype = this.readByte(); var vtype = this.readByte(); var size = this.readI32(); - return {ktype: ktype, vtype: vtype, size: size}; + return { ktype: ktype, vtype: vtype, size: size }; }; -TBinaryProtocol.prototype.readMapEnd = function() { -}; +TBinaryProtocol.prototype.readMapEnd = function () {}; -TBinaryProtocol.prototype.readListBegin = function() { +TBinaryProtocol.prototype.readListBegin = function () { var etype = this.readByte(); var size = this.readI32(); - return {etype: etype, size: size}; + return { etype: etype, size: size }; }; -TBinaryProtocol.prototype.readListEnd = function() { -}; +TBinaryProtocol.prototype.readListEnd = function () {}; -TBinaryProtocol.prototype.readSetBegin = function() { +TBinaryProtocol.prototype.readSetBegin = function () { var etype = this.readByte(); var size = this.readI32(); - return {etype: etype, size: size}; + return { etype: etype, size: size }; }; -TBinaryProtocol.prototype.readSetEnd = function() { -}; +TBinaryProtocol.prototype.readSetEnd = function () {}; -TBinaryProtocol.prototype.readBool = function() { +TBinaryProtocol.prototype.readBool = function () { var b = this.readByte(); if (b === 0) { return false; @@ -255,56 +251,62 @@ TBinaryProtocol.prototype.readBool = function() { return true; }; -TBinaryProtocol.prototype.readByte = function() { +TBinaryProtocol.prototype.readByte = function () { return this.trans.readByte(); }; -TBinaryProtocol.prototype.readI16 = function() { +TBinaryProtocol.prototype.readI16 = function () { return this.trans.readI16(); }; -TBinaryProtocol.prototype.readI32 = function() { +TBinaryProtocol.prototype.readI32 = function () { return this.trans.readI32(); }; -TBinaryProtocol.prototype.readI64 = function() { +TBinaryProtocol.prototype.readI64 = function () { var buff = this.trans.read(8); return new Int64(buff); }; -TBinaryProtocol.prototype.readDouble = function() { +TBinaryProtocol.prototype.readDouble = function () { return this.trans.readDouble(); }; -TBinaryProtocol.prototype.readBinary = function() { +TBinaryProtocol.prototype.readBinary = function () { var len = this.readI32(); if (len === 0) { return new Buffer(0); } 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); }; -TBinaryProtocol.prototype.readString = function() { +TBinaryProtocol.prototype.readString = function () { var len = this.readI32(); if (len === 0) { return ""; } 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); }; -TBinaryProtocol.prototype.getTransport = function() { +TBinaryProtocol.prototype.getTransport = function () { return this.trans; }; -TBinaryProtocol.prototype.skip = function(type) { +TBinaryProtocol.prototype.skip = function (type) { switch (type) { case Type.BOOL: this.readBool(); @@ -362,6 +364,6 @@ TBinaryProtocol.prototype.skip = function(type) { this.readListEnd(); break; default: - throw new Error("Invalid type: " + type); + throw new Error("Invalid type: " + type); } }; diff --git a/lib/nodejs/lib/thrift/browser.js b/lib/nodejs/lib/thrift/browser.js index e217704d66d..5c843d07137 100644 --- a/lib/nodejs/lib/thrift/browser.js +++ b/lib/nodejs/lib/thrift/browser.js @@ -16,38 +16,42 @@ * specific language governing permissions and limitations * under the License. */ -exports.Thrift = require('./thrift'); +exports.Thrift = require("./thrift"); -var wsConnection = require('./ws_connection'); +var wsConnection = require("./ws_connection"); exports.WSConnection = wsConnection.WSConnection; exports.createWSConnection = wsConnection.createWSConnection; exports.createWSClient = wsConnection.createWSClient; -var xhrConnection = require('./xhr_connection'); +var xhrConnection = require("./xhr_connection"); exports.XHRConnection = xhrConnection.XHRConnection; exports.createXHRConnection = xhrConnection.createXHRConnection; exports.createXHRClient = xhrConnection.createXHRClient; -var ohosConnection = require('./ohos_connection'); +var ohosConnection = require("./ohos_connection"); exports.OhosConnection = ohosConnection.OhosConnection; exports.createOhosConnection = ohosConnection.createOhosConnection; exports.createOhosClient = ohosConnection.createOhosClient; -exports.Int64 = require('node-int64'); -exports.Q = require('q'); +exports.createClient = require("./create_client"); -var mpxProtocol = require('./multiplexed_protocol'); +exports.Int64 = require("node-int64"); +exports.Q = require("q"); + +var mpxProtocol = require("./multiplexed_protocol"); exports.Multiplexer = mpxProtocol.Multiplexer; /* * Export transport and protocol so they can be used outside of a * cassandra/server context */ -exports.TBufferedTransport = require('./buffered_transport'); -exports.TFramedTransport = require('./framed_transport'); -exports.TWebSocketTransport = require('./ws_transport'); - -exports.Protocol = require('./json_protocol'); -exports.TJSONProtocol = require('./json_protocol'); -exports.TBinaryProtocol = require('./binary_protocol'); -exports.TCompactProtocol = require('./compact_protocol'); +exports.TBufferedTransport = require("./buffered_transport"); +exports.TFramedTransport = require("./framed_transport"); +exports.TWebSocketTransport = require("./ws_transport"); + +exports.Protocol = require("./json_protocol"); +exports.TJSONProtocol = require("./json_protocol"); +exports.TBinaryProtocol = require("./binary_protocol"); +exports.TCompactProtocol = require("./compact_protocol"); + +exports.InputBufferUnderrunError = require("./input_buffer_underrun_error"); diff --git a/lib/nodejs/lib/thrift/buffered_transport.js b/lib/nodejs/lib/thrift/buffered_transport.js index f0d5d4aa1e4..27d682d8fd0 100644 --- a/lib/nodejs/lib/thrift/buffered_transport.js +++ b/lib/nodejs/lib/thrift/buffered_transport.js @@ -17,9 +17,9 @@ * under the License. */ -var binary = require('./binary'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); -var THeaderTransport = require('./header_transport'); +var binary = require("./binary"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); +var THeaderTransport = require("./header_transport"); module.exports = TBufferedTransport; @@ -33,22 +33,22 @@ function TBufferedTransport(buffer, callback) { this.outBuffers = []; this.outCount = 0; this.onFlush = callback; -}; +} Object.setPrototypeOf(TBufferedTransport.prototype, THeaderTransport.prototype); -TBufferedTransport.prototype.reset = function() { +TBufferedTransport.prototype.reset = function () { this.inBuf = new Buffer(this.defaultReadBufferSize); this.readCursor = 0; this.writeCursor = 0; this.outBuffers = []; this.outCount = 0; -} +}; -TBufferedTransport.receiver = function(callback, seqid) { +TBufferedTransport.receiver = function (callback, seqid) { var reader = new TBufferedTransport(); - return function(data) { + return function (data) { if (reader.writeCursor + data.length > reader.inBuf.length) { var buf = new Buffer(reader.writeCursor + data.length); reader.inBuf.copy(buf, 0, 0, reader.writeCursor); @@ -61,11 +61,12 @@ TBufferedTransport.receiver = function(callback, seqid) { }; }; - -TBufferedTransport.prototype.commitPosition = function(){ +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); @@ -75,34 +76,32 @@ TBufferedTransport.prototype.commitPosition = function(){ this.inBuf = buf; }; -TBufferedTransport.prototype.rollbackPosition = function(){ +TBufferedTransport.prototype.rollbackPosition = function () { this.readCursor = 0; -} +}; - // TODO: Implement open/close support -TBufferedTransport.prototype.isOpen = function() { +// 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 -TBufferedTransport.prototype.setCurrSeqId = function(seqid) { +// Set the seqid of the message in the client +// So that callbacks can be found +TBufferedTransport.prototype.setCurrSeqId = function (seqid) { this._seqid = seqid; }; -TBufferedTransport.prototype.ensureAvailable = function(len) { +TBufferedTransport.prototype.ensureAvailable = function (len) { if (this.readCursor + len > this.writeCursor) { throw new InputBufferUnderrunError(); } }; -TBufferedTransport.prototype.read = function(len) { +TBufferedTransport.prototype.read = function (len) { this.ensureAvailable(len); var buf = new Buffer(len); this.inBuf.copy(buf, 0, this.readCursor, this.readCursor + len); @@ -110,57 +109,61 @@ TBufferedTransport.prototype.read = function(len) { return buf; }; -TBufferedTransport.prototype.readByte = function() { +TBufferedTransport.prototype.readByte = function () { this.ensureAvailable(1); return binary.readByte(this.inBuf[this.readCursor++]); }; -TBufferedTransport.prototype.readI16 = function() { +TBufferedTransport.prototype.readI16 = function () { this.ensureAvailable(2); var i16 = binary.readI16(this.inBuf, this.readCursor); this.readCursor += 2; return i16; }; -TBufferedTransport.prototype.readI32 = function() { +TBufferedTransport.prototype.readI32 = function () { this.ensureAvailable(4); var i32 = binary.readI32(this.inBuf, this.readCursor); this.readCursor += 4; return i32; }; -TBufferedTransport.prototype.readDouble = function() { +TBufferedTransport.prototype.readDouble = function () { this.ensureAvailable(8); var d = binary.readDouble(this.inBuf, this.readCursor); this.readCursor += 8; return d; }; -TBufferedTransport.prototype.readString = function(len) { +TBufferedTransport.prototype.readString = function (len) { this.ensureAvailable(len); - var str = this.inBuf.toString('utf8', this.readCursor, this.readCursor + len); + var str = this.inBuf.toString("utf8", this.readCursor, this.readCursor + len); this.readCursor += len; return str; }; -TBufferedTransport.prototype.borrow = function() { - var obj = {buf: this.inBuf, readIndex: this.readCursor, writeIndex: this.writeCursor}; +TBufferedTransport.prototype.borrow = function () { + var obj = { + buf: this.inBuf, + readIndex: this.readCursor, + writeIndex: this.writeCursor, + }; return obj; }; -TBufferedTransport.prototype.consume = function(bytesConsumed) { +TBufferedTransport.prototype.consume = function (bytesConsumed) { this.readCursor += bytesConsumed; }; -TBufferedTransport.prototype.write = function(buf) { - if (typeof(buf) === "string") { - buf = new Buffer(buf, 'utf8'); +TBufferedTransport.prototype.write = function (buf) { + if (typeof buf === "string") { + buf = new Buffer(buf, "utf8"); } this.outBuffers.push(buf); this.outCount += buf.length; }; -TBufferedTransport.prototype.flush = function() { +TBufferedTransport.prototype.flush = function () { // If the seqid of the callback is available pass it to the onFlush // Then remove the current seqid var seqid = this._seqid; @@ -171,8 +174,8 @@ TBufferedTransport.prototype.flush = function() { } var msg = new Buffer(this.outCount), - pos = 0; - this.outBuffers.forEach(function(buf) { + pos = 0; + this.outBuffers.forEach(function (buf) { buf.copy(msg, pos, 0); pos += buf.length; }); @@ -184,4 +187,4 @@ TBufferedTransport.prototype.flush = function() { this.outBuffers = []; this.outCount = 0; -} +}; diff --git a/lib/nodejs/lib/thrift/compact_protocol.js b/lib/nodejs/lib/thrift/compact_protocol.js index 302a88d4d84..e946dc886c0 100644 --- a/lib/nodejs/lib/thrift/compact_protocol.js +++ b/lib/nodejs/lib/thrift/compact_protocol.js @@ -17,9 +17,9 @@ * under the License. */ -var log = require('./log'); -var Int64 = require('node-int64'); -var Thrift = require('./thrift'); +var log = require("./log"); +var Int64 = require("node-int64"); +var Thrift = require("./thrift"); var Type = Thrift.Type; module.exports = TCompactProtocol; @@ -50,59 +50,58 @@ function TCompactProtocol(trans) { this.container_limit_ = 0; this.booleanField_ = { name: null, - hasBoolValue: false + hasBoolValue: false, }; this.boolValue_ = { hasBoolValue: false, - boolValue: false + boolValue: false, }; -}; - +} // // Compact Protocol Constants // /** - * Compact Protocol ID number. - * @readonly - * @const {number} PROTOCOL_ID - */ -TCompactProtocol.PROTOCOL_ID = -126; //1000 0010 + * Compact Protocol ID number. + * @readonly + * @const {number} PROTOCOL_ID + */ +TCompactProtocol.PROTOCOL_ID = -126; //1000 0010 /** - * Compact Protocol version number. - * @readonly - * @const {number} VERSION_N - */ + * Compact Protocol version number. + * @readonly + * @const {number} VERSION_N + */ TCompactProtocol.VERSION_N = 1; /** - * Compact Protocol version mask for combining protocol version and message type in one byte. - * @readonly - * @const {number} VERSION_MASK - */ + * Compact Protocol version mask for combining protocol version and message type in one byte. + * @readonly + * @const {number} VERSION_MASK + */ TCompactProtocol.VERSION_MASK = 0x1f; //0001 1111 /** - * Compact Protocol message type mask for combining protocol version and message type in one byte. - * @readonly - * @const {number} TYPE_MASK - */ -TCompactProtocol.TYPE_MASK = -32; //1110 0000 + * Compact Protocol message type mask for combining protocol version and message type in one byte. + * @readonly + * @const {number} TYPE_MASK + */ +TCompactProtocol.TYPE_MASK = -32; //1110 0000 /** - * Compact Protocol message type bits for ensuring message type bit size. - * @readonly - * @const {number} TYPE_BITS - */ + * Compact Protocol message type bits for ensuring message type bit size. + * @readonly + * @const {number} TYPE_BITS + */ TCompactProtocol.TYPE_BITS = 7; //0000 0111 /** - * Compact Protocol message type shift amount for combining protocol version and message type in one byte. - * @readonly - * @const {number} TYPE_SHIFT_AMOUNT - */ + * Compact Protocol message type shift amount for combining protocol version and message type in one byte. + * @readonly + * @const {number} TYPE_SHIFT_AMOUNT + */ TCompactProtocol.TYPE_SHIFT_AMOUNT = 5; /** @@ -123,19 +122,19 @@ TCompactProtocol.TYPE_SHIFT_AMOUNT = 5; * @property {number} CT_STRUCT - A multifield type. */ TCompactProtocol.Types = { - CT_STOP: 0x00, - CT_BOOLEAN_TRUE: 0x01, - CT_BOOLEAN_FALSE: 0x02, - CT_BYTE: 0x03, - CT_I16: 0x04, - CT_I32: 0x05, - CT_I64: 0x06, - CT_DOUBLE: 0x07, - CT_BINARY: 0x08, - CT_LIST: 0x09, - CT_SET: 0x0A, - CT_MAP: 0x0B, - CT_STRUCT: 0x0C + CT_STOP: 0x00, + CT_BOOLEAN_TRUE: 0x01, + CT_BOOLEAN_FALSE: 0x02, + CT_BYTE: 0x03, + CT_I16: 0x04, + CT_I32: 0x05, + CT_I64: 0x06, + CT_DOUBLE: 0x07, + CT_BINARY: 0x08, + CT_LIST: 0x09, + CT_SET: 0x0a, + CT_MAP: 0x0b, + CT_STRUCT: 0x0c, }; /** @@ -143,25 +142,24 @@ TCompactProtocol.Types = { * @readonly */ TCompactProtocol.TTypeToCType = [ - TCompactProtocol.Types.CT_STOP, // T_STOP - 0, // unused + TCompactProtocol.Types.CT_STOP, // T_STOP + 0, // unused TCompactProtocol.Types.CT_BOOLEAN_TRUE, // T_BOOL - TCompactProtocol.Types.CT_BYTE, // T_BYTE - TCompactProtocol.Types.CT_DOUBLE, // T_DOUBLE - 0, // unused - TCompactProtocol.Types.CT_I16, // T_I16 - 0, // unused - TCompactProtocol.Types.CT_I32, // T_I32 - 0, // unused - TCompactProtocol.Types.CT_I64, // T_I64 - TCompactProtocol.Types.CT_BINARY, // T_STRING - TCompactProtocol.Types.CT_STRUCT, // T_STRUCT - TCompactProtocol.Types.CT_MAP, // T_MAP - TCompactProtocol.Types.CT_SET, // T_SET - TCompactProtocol.Types.CT_LIST, // T_LIST + TCompactProtocol.Types.CT_BYTE, // T_BYTE + TCompactProtocol.Types.CT_DOUBLE, // T_DOUBLE + 0, // unused + TCompactProtocol.Types.CT_I16, // T_I16 + 0, // unused + TCompactProtocol.Types.CT_I32, // T_I32 + 0, // unused + TCompactProtocol.Types.CT_I64, // T_I64 + TCompactProtocol.Types.CT_BINARY, // T_STRING + TCompactProtocol.Types.CT_STRUCT, // T_STRUCT + TCompactProtocol.Types.CT_MAP, // T_MAP + TCompactProtocol.Types.CT_SET, // T_SET + TCompactProtocol.Types.CT_LIST, // T_LIST ]; - // // Compact Protocol Utilities // @@ -169,7 +167,7 @@ TCompactProtocol.TTypeToCType = [ /** * Returns the underlying transport layer. * @return {object} The underlying transport layer. - */TCompactProtocol.prototype.getTransport = function() { + */ TCompactProtocol.prototype.getTransport = function () { return this.trans; }; @@ -179,7 +177,7 @@ TCompactProtocol.TTypeToCType = [ * @param {number} ttype - Thrift type value * @returns {number} Compact protocol type value */ -TCompactProtocol.prototype.getCompactType = function(ttype) { +TCompactProtocol.prototype.getCompactType = function (ttype) { return TCompactProtocol.TTypeToCType[ttype]; }; @@ -189,7 +187,7 @@ TCompactProtocol.prototype.getCompactType = function(ttype) { * @param {number} type - Compact Protocol type value * @returns {number} Thrift Type value */ -TCompactProtocol.prototype.getTType = function(type) { +TCompactProtocol.prototype.getTType = function (type) { switch (type) { case Type.STOP: return Type.STOP; @@ -217,12 +215,14 @@ TCompactProtocol.prototype.getTType = function(type) { case TCompactProtocol.Types.CT_STRUCT: return Type.STRUCT; default: - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Unknown type: " + type); + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.INVALID_DATA, + "Unknown type: " + type, + ); } return Type.STOP; }; - // // Compact Protocol write operations // @@ -230,7 +230,7 @@ TCompactProtocol.prototype.getTType = function(type) { /** * Send any buffered bytes to the end point. */ -TCompactProtocol.prototype.flush = function() { +TCompactProtocol.prototype.flush = function () { return this.trans.flush(); }; @@ -240,31 +240,33 @@ TCompactProtocol.prototype.flush = function() { * @param {number} type - The type of message (CALL, REPLY, EXCEPTION, ONEWAY). * @param {number} seqid - The call sequence number (if any). */ -TCompactProtocol.prototype.writeMessageBegin = function(name, type, seqid) { +TCompactProtocol.prototype.writeMessageBegin = function (name, type, seqid) { this.writeByte(TCompactProtocol.PROTOCOL_ID); - this.writeByte((TCompactProtocol.VERSION_N & TCompactProtocol.VERSION_MASK) | - ((type << TCompactProtocol.TYPE_SHIFT_AMOUNT) & TCompactProtocol.TYPE_MASK)); + this.writeByte( + (TCompactProtocol.VERSION_N & TCompactProtocol.VERSION_MASK) | + ((type << TCompactProtocol.TYPE_SHIFT_AMOUNT) & + TCompactProtocol.TYPE_MASK), + ); this.writeVarint32(seqid); this.writeString(name); // Record client seqid to find callback again if (this._seqid) { - log.warning('SeqId already set', { 'name': name }); + log.warning("SeqId already set", { name: name }); } else { this._seqid = seqid; this.trans.setCurrSeqId(seqid); } }; -TCompactProtocol.prototype.writeMessageEnd = function() { -}; +TCompactProtocol.prototype.writeMessageEnd = function () {}; -TCompactProtocol.prototype.writeStructBegin = function(name) { +TCompactProtocol.prototype.writeStructBegin = function (name) { this.lastField_.push(this.lastFieldId_); this.lastFieldId_ = 0; }; -TCompactProtocol.prototype.writeStructEnd = function() { +TCompactProtocol.prototype.writeStructEnd = function () { this.lastFieldId_ = this.lastField_.pop(); }; @@ -274,7 +276,7 @@ TCompactProtocol.prototype.writeStructEnd = function() { * @param {number} type - The field data type (a normal Thrift field Type). * @param {number} id - The IDL field Id. */ -TCompactProtocol.prototype.writeFieldBegin = function(name, type, id) { +TCompactProtocol.prototype.writeFieldBegin = function (name, type, id) { if (type != Type.BOOL) { return this.writeFieldBeginInternal(name, type, id, -1); } @@ -284,10 +286,9 @@ TCompactProtocol.prototype.writeFieldBegin = function(name, type, id) { this.booleanField_.fieldId = id; }; -TCompactProtocol.prototype.writeFieldEnd = function() { -}; +TCompactProtocol.prototype.writeFieldEnd = function () {}; -TCompactProtocol.prototype.writeFieldStop = function() { +TCompactProtocol.prototype.writeFieldStop = function () { this.writeByte(TCompactProtocol.Types.CT_STOP); }; @@ -297,80 +298,85 @@ TCompactProtocol.prototype.writeFieldStop = function() { * @param {number} valType - The Thrift type of the map values. * @param {number} size - The number of k/v pairs in the map. */ -TCompactProtocol.prototype.writeMapBegin = function(keyType, valType, size) { +TCompactProtocol.prototype.writeMapBegin = function (keyType, valType, size) { if (size === 0) { this.writeByte(0); } else { this.writeVarint32(size); - this.writeByte(this.getCompactType(keyType) << 4 | this.getCompactType(valType)); + this.writeByte( + (this.getCompactType(keyType) << 4) | this.getCompactType(valType), + ); } }; -TCompactProtocol.prototype.writeMapEnd = function() { -}; +TCompactProtocol.prototype.writeMapEnd = function () {}; /** * Writes a list collection header * @param {number} elemType - The Thrift type of the list elements. * @param {number} size - The number of elements in the list. */ -TCompactProtocol.prototype.writeListBegin = function(elemType, size) { +TCompactProtocol.prototype.writeListBegin = function (elemType, size) { this.writeCollectionBegin(elemType, size); }; -TCompactProtocol.prototype.writeListEnd = function() { -}; +TCompactProtocol.prototype.writeListEnd = function () {}; /** * Writes a set collection header * @param {number} elemType - The Thrift type of the set elements. * @param {number} size - The number of elements in the set. */ -TCompactProtocol.prototype.writeSetBegin = function(elemType, size) { +TCompactProtocol.prototype.writeSetBegin = function (elemType, size) { this.writeCollectionBegin(elemType, size); }; -TCompactProtocol.prototype.writeSetEnd = function() { -}; +TCompactProtocol.prototype.writeSetEnd = function () {}; -TCompactProtocol.prototype.writeBool = function(value) { +TCompactProtocol.prototype.writeBool = function (value) { if (this.booleanField_.name !== null) { // we haven't written the field header yet - this.writeFieldBeginInternal(this.booleanField_.name, - this.booleanField_.fieldType, - this.booleanField_.fieldId, - (value ? TCompactProtocol.Types.CT_BOOLEAN_TRUE - : TCompactProtocol.Types.CT_BOOLEAN_FALSE)); + this.writeFieldBeginInternal( + this.booleanField_.name, + this.booleanField_.fieldType, + this.booleanField_.fieldId, + value + ? TCompactProtocol.Types.CT_BOOLEAN_TRUE + : TCompactProtocol.Types.CT_BOOLEAN_FALSE, + ); this.booleanField_.name = null; } else { // we're not part of a field, so just write the value - this.writeByte((value ? TCompactProtocol.Types.CT_BOOLEAN_TRUE - : TCompactProtocol.Types.CT_BOOLEAN_FALSE)); + this.writeByte( + value + ? TCompactProtocol.Types.CT_BOOLEAN_TRUE + : TCompactProtocol.Types.CT_BOOLEAN_FALSE, + ); } }; -TCompactProtocol.prototype.writeByte = function(b) { +TCompactProtocol.prototype.writeByte = function (b) { this.trans.write(new Buffer([b])); }; -TCompactProtocol.prototype.writeI16 = function(i16) { +TCompactProtocol.prototype.writeI16 = function (i16) { this.writeVarint32(this.i32ToZigzag(i16)); }; -TCompactProtocol.prototype.writeI32 = function(i32) { +TCompactProtocol.prototype.writeI32 = function (i32) { this.writeVarint32(this.i32ToZigzag(i32)); }; -TCompactProtocol.prototype.writeI64 = function(i64) { +TCompactProtocol.prototype.writeI64 = function (i64) { this.writeVarint64(this.i64ToZigzag(i64)); }; // Little-endian, unlike TBinaryProtocol -TCompactProtocol.prototype.writeDouble = function(v) { +TCompactProtocol.prototype.writeDouble = function (v) { var buff = new Buffer(8); var m, e, c; - buff[7] = (v < 0 ? 0x80 : 0x00); + buff[7] = v < 0 ? 0x80 : 0x00; v = Math.abs(v); if (v !== v) { @@ -388,22 +394,17 @@ TCompactProtocol.prototype.writeDouble = function(v) { c *= 2; } - if (e + 1023 >= 2047) - { + if (e + 1023 >= 2047) { // 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; + 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; } } @@ -428,45 +429,53 @@ TCompactProtocol.prototype.writeDouble = function(v) { this.trans.write(buff); }; -TCompactProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) { - if (typeof arg === 'string') { - this.writeVarint32(Buffer.byteLength(arg, encoding)) ; +TCompactProtocol.prototype.writeStringOrBinary = function ( + name, + encoding, + arg, +) { + if (typeof arg === "string") { + this.writeVarint32(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 this.writeVarint32(arg.length); this.trans.write(arg); } else { - throw new Error(name + ' called without a string/Buffer argument: ' + arg); + throw new Error(name + " called without a string/Buffer argument: " + arg); } }; -TCompactProtocol.prototype.writeString = function(arg) { - this.writeStringOrBinary('writeString', 'utf8', arg); +TCompactProtocol.prototype.writeString = function (arg) { + this.writeStringOrBinary("writeString", "utf8", arg); }; -TCompactProtocol.prototype.writeBinary = function(arg) { - this.writeStringOrBinary('writeBinary', 'binary', arg); +TCompactProtocol.prototype.writeBinary = function (arg) { + this.writeStringOrBinary("writeBinary", "binary", arg); }; - // // Compact Protocol internal write methods // -TCompactProtocol.prototype.writeFieldBeginInternal = function(name, - fieldType, - fieldId, - typeOverride) { +TCompactProtocol.prototype.writeFieldBeginInternal = function ( + name, + fieldType, + fieldId, + typeOverride, +) { //If there's a type override, use that. - var typeToWrite = (typeOverride == -1 ? this.getCompactType(fieldType) : typeOverride); + var typeToWrite = + typeOverride == -1 ? this.getCompactType(fieldType) : typeOverride; //Check if we can delta encode the field id if (fieldId > this.lastFieldId_ && fieldId - this.lastFieldId_ <= 15) { //Include the type delta with the field ID - this.writeByte((fieldId - this.lastFieldId_) << 4 | typeToWrite); + this.writeByte(((fieldId - this.lastFieldId_) << 4) | typeToWrite); } else { //Write separate type and ID values this.writeByte(typeToWrite); @@ -475,10 +484,10 @@ TCompactProtocol.prototype.writeFieldBeginInternal = function(name, this.lastFieldId_ = fieldId; }; -TCompactProtocol.prototype.writeCollectionBegin = function(elemType, size) { +TCompactProtocol.prototype.writeCollectionBegin = function (elemType, size) { if (size <= 14) { //Combine size and type in one byte if possible - this.writeByte(size << 4 | this.getCompactType(elemType)); + this.writeByte((size << 4) | this.getCompactType(elemType)); } else { this.writeByte(0xf0 | this.getCompactType(elemType)); this.writeVarint32(size); @@ -488,20 +497,20 @@ TCompactProtocol.prototype.writeCollectionBegin = function(elemType, size) { /** * Write an i32 as a varint. Results in 1-5 bytes on the wire. */ -TCompactProtocol.prototype.writeVarint32 = function(n) { +TCompactProtocol.prototype.writeVarint32 = function (n) { var buf = new Buffer(5); var wsize = 0; while (true) { - if ((n & ~0x7F) === 0) { + if ((n & ~0x7f) === 0) { buf[wsize++] = n; break; } else { - buf[wsize++] = ((n & 0x7F) | 0x80); + buf[wsize++] = (n & 0x7f) | 0x80; n = n >>> 7; } } var wbuf = new Buffer(wsize); - buf.copy(wbuf,0,0,wsize); + buf.copy(wbuf, 0, 0, wsize); this.trans.write(wbuf); }; @@ -509,12 +518,15 @@ TCompactProtocol.prototype.writeVarint32 = function(n) { * Write an i64 as a varint. Results in 1-10 bytes on the wire. * N.B. node-int64 is always big endian */ -TCompactProtocol.prototype.writeVarint64 = function(n) { - if (typeof n === "number"){ +TCompactProtocol.prototype.writeVarint64 = function (n) { + if (typeof n === "number") { n = new Int64(n); } - if (! (n instanceof Int64)) { - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Expected Int64 or Number, found: " + n); + if (!(n instanceof Int64)) { + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.INVALID_DATA, + "Expected Int64 or Number, found: " + n, + ); } var buf = new Buffer(10); @@ -523,11 +535,11 @@ TCompactProtocol.prototype.writeVarint64 = function(n) { var lo = n.buffer.readUInt32BE(4, true); var mask = 0; while (true) { - if (((lo & ~0x7F) === 0) && (hi === 0)) { + if ((lo & ~0x7f) === 0 && hi === 0) { buf[wsize++] = lo; break; } else { - buf[wsize++] = ((lo & 0x7F) | 0x80); + buf[wsize++] = (lo & 0x7f) | 0x80; mask = hi << 25; lo = lo >>> 7; hi = hi >>> 7; @@ -535,7 +547,7 @@ TCompactProtocol.prototype.writeVarint64 = function(n) { } } var wbuf = new Buffer(wsize); - buf.copy(wbuf,0,0,wsize); + buf.copy(wbuf, 0, 0, wsize); this.trans.write(wbuf); }; @@ -543,20 +555,23 @@ TCompactProtocol.prototype.writeVarint64 = function(n) { * Convert l into a zigzag long. This allows negative numbers to be * represented compactly as a varint. */ -TCompactProtocol.prototype.i64ToZigzag = function(l) { - if (typeof l === 'string') { +TCompactProtocol.prototype.i64ToZigzag = function (l) { + if (typeof l === "string") { l = new Int64(parseInt(l, 10)); - } else if (typeof l === 'number') { + } else if (typeof l === "number") { l = new Int64(l); } - if (! (l instanceof Int64)) { - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Expected Int64 or Number, found: " + l); + if (!(l instanceof Int64)) { + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.INVALID_DATA, + "Expected Int64 or Number, found: " + l, + ); } var hi = l.buffer.readUInt32BE(0, true); var lo = l.buffer.readUInt32BE(4, true); var sign = hi >>> 31; - hi = ((hi << 1) | (lo >>> 31)) ^ ((!!sign) ? 0xFFFFFFFF : 0); - lo = (lo << 1) ^ ((!!sign) ? 0xFFFFFFFF : 0); + hi = ((hi << 1) | (lo >>> 31)) ^ (!!sign ? 0xffffffff : 0); + lo = (lo << 1) ^ (!!sign ? 0xffffffff : 0); return new Int64(hi, lo); }; @@ -564,29 +579,36 @@ TCompactProtocol.prototype.i64ToZigzag = function(l) { * Convert n into a zigzag int. This allows negative numbers to be * represented compactly as a varint. */ -TCompactProtocol.prototype.i32ToZigzag = function(n) { - return (n << 1) ^ ((n & 0x80000000) ? 0xFFFFFFFF : 0); +TCompactProtocol.prototype.i32ToZigzag = function (n) { + return (n << 1) ^ (n & 0x80000000 ? 0xffffffff : 0); }; - // // Compact Protocol read operations // -TCompactProtocol.prototype.readMessageBegin = function() { +TCompactProtocol.prototype.readMessageBegin = function () { //Read protocol ID var protocolId = this.trans.readByte(); if (protocolId != TCompactProtocol.PROTOCOL_ID) { - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad protocol identifier " + protocolId); + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.BAD_VERSION, + "Bad protocol identifier " + protocolId, + ); } //Read Version and Type var versionAndType = this.trans.readByte(); - var version = (versionAndType & TCompactProtocol.VERSION_MASK); + var version = versionAndType & TCompactProtocol.VERSION_MASK; if (version != TCompactProtocol.VERSION_N) { - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad protocol version " + version); + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.BAD_VERSION, + "Bad protocol version " + version, + ); } - var type = ((versionAndType >> TCompactProtocol.TYPE_SHIFT_AMOUNT) & TCompactProtocol.TYPE_BITS); + var type = + (versionAndType >> TCompactProtocol.TYPE_SHIFT_AMOUNT) & + TCompactProtocol.TYPE_BITS; //Read SeqId var seqid = this.readVarint32(); @@ -594,62 +616,65 @@ TCompactProtocol.prototype.readMessageBegin = function() { //Read name var name = this.readString(); - return {fname: name, mtype: type, rseqid: seqid}; + return { fname: name, mtype: type, rseqid: seqid }; }; -TCompactProtocol.prototype.readMessageEnd = function() { -}; +TCompactProtocol.prototype.readMessageEnd = function () {}; -TCompactProtocol.prototype.readStructBegin = function() { +TCompactProtocol.prototype.readStructBegin = function () { this.lastField_.push(this.lastFieldId_); this.lastFieldId_ = 0; - return {fname: ''}; + return { fname: "" }; }; -TCompactProtocol.prototype.readStructEnd = function() { +TCompactProtocol.prototype.readStructEnd = function () { this.lastFieldId_ = this.lastField_.pop(); }; -TCompactProtocol.prototype.readFieldBegin = function() { +TCompactProtocol.prototype.readFieldBegin = function () { var fieldId = 0; var b = this.trans.readByte(b); - var type = (b & 0x0f); + var type = b & 0x0f; if (type == TCompactProtocol.Types.CT_STOP) { - return {fname: null, ftype: Thrift.Type.STOP, fid: 0}; + return { fname: null, ftype: Thrift.Type.STOP, fid: 0 }; } //Mask off the 4 MSB of the type header to check for field id delta. - var modifier = ((b & 0x000000f0) >>> 4); + var modifier = (b & 0x000000f0) >>> 4; if (modifier === 0) { //If not a delta read the field id. fieldId = this.readI16(); } else { //Recover the field id from the delta - fieldId = (this.lastFieldId_ + modifier); + fieldId = this.lastFieldId_ + modifier; } var fieldType = this.getTType(type); //Boolean are encoded with the type - if (type == TCompactProtocol.Types.CT_BOOLEAN_TRUE || - type == TCompactProtocol.Types.CT_BOOLEAN_FALSE) { + if ( + type == TCompactProtocol.Types.CT_BOOLEAN_TRUE || + type == TCompactProtocol.Types.CT_BOOLEAN_FALSE + ) { this.boolValue_.hasBoolValue = true; this.boolValue_.boolValue = - (type == TCompactProtocol.Types.CT_BOOLEAN_TRUE ? true : false); + type == TCompactProtocol.Types.CT_BOOLEAN_TRUE ? true : false; } //Save the new field for the next delta computation. this.lastFieldId_ = fieldId; - return {fname: null, ftype: fieldType, fid: fieldId}; + return { fname: null, ftype: fieldType, fid: fieldId }; }; -TCompactProtocol.prototype.readFieldEnd = function() { -}; +TCompactProtocol.prototype.readFieldEnd = function () {}; -TCompactProtocol.prototype.readMapBegin = function() { +TCompactProtocol.prototype.readMapBegin = function () { var msize = this.readVarint32(); if (msize < 0) { - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative map size"); + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.NEGATIVE_SIZE, + "Negative map size", + ); } var kvType = 0; @@ -659,13 +684,12 @@ TCompactProtocol.prototype.readMapBegin = function() { var keyType = this.getTType((kvType & 0xf0) >>> 4); var valType = this.getTType(kvType & 0xf); - return {ktype: keyType, vtype: valType, size: msize}; + return { ktype: keyType, vtype: valType, size: msize }; }; -TCompactProtocol.prototype.readMapEnd = function() { -}; +TCompactProtocol.prototype.readMapEnd = function () {}; -TCompactProtocol.prototype.readListBegin = function() { +TCompactProtocol.prototype.readListBegin = function () { var size_and_type = this.trans.readByte(); var lsize = (size_and_type >>> 4) & 0x0000000f; @@ -674,25 +698,26 @@ TCompactProtocol.prototype.readListBegin = function() { } if (lsize < 0) { - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative list size"); + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.NEGATIVE_SIZE, + "Negative list size", + ); } var elemType = this.getTType(size_and_type & 0x0000000f); - return {etype: elemType, size: lsize}; + return { etype: elemType, size: lsize }; }; -TCompactProtocol.prototype.readListEnd = function() { -}; +TCompactProtocol.prototype.readListEnd = function () {}; -TCompactProtocol.prototype.readSetBegin = function() { +TCompactProtocol.prototype.readSetBegin = function () { return this.readListBegin(); }; -TCompactProtocol.prototype.readSetEnd = function() { -}; +TCompactProtocol.prototype.readSetEnd = function () {}; -TCompactProtocol.prototype.readBool = function() { +TCompactProtocol.prototype.readBool = function () { var value = false; var rsize = 0; if (this.boolValue_.hasBoolValue === true) { @@ -701,50 +726,50 @@ TCompactProtocol.prototype.readBool = function() { } else { var res = this.trans.readByte(); rsize = res.rsize; - value = (res.value == TCompactProtocol.Types.CT_BOOLEAN_TRUE); + value = res.value == TCompactProtocol.Types.CT_BOOLEAN_TRUE; } return value; }; -TCompactProtocol.prototype.readByte = function() { +TCompactProtocol.prototype.readByte = function () { return this.trans.readByte(); }; -TCompactProtocol.prototype.readI16 = function() { +TCompactProtocol.prototype.readI16 = function () { return this.readI32(); }; -TCompactProtocol.prototype.readI32 = function() { +TCompactProtocol.prototype.readI32 = function () { return this.zigzagToI32(this.readVarint32()); }; -TCompactProtocol.prototype.readI64 = function() { +TCompactProtocol.prototype.readI64 = function () { return this.zigzagToI64(this.readVarint64()); }; // Little-endian, unlike TBinaryProtocol -TCompactProtocol.prototype.readDouble = function() { +TCompactProtocol.prototype.readDouble = function () { var buff = this.trans.read(8); var off = 0; var signed = buff[off + 7] & 0x80; - var e = (buff[off+6] & 0xF0) >> 4; - e += (buff[off+7] & 0x7F) << 4; + var e = (buff[off + 6] & 0xf0) >> 4; + e += (buff[off + 7] & 0x7f) << 4; var m = buff[off]; - m += buff[off+1] << 8; - m += buff[off+2] << 16; - m += buff[off+3] * POW_24; - m += buff[off+4] * POW_32; - m += buff[off+5] * POW_40; - m += (buff[off+6] & 0x0F) * POW_48; + m += buff[off + 1] << 8; + m += buff[off + 2] << 16; + m += buff[off + 3] * POW_24; + m += buff[off + 4] * POW_32; + m += buff[off + 5] * POW_40; + m += (buff[off + 6] & 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; @@ -757,19 +782,22 @@ TCompactProtocol.prototype.readDouble = function() { return m * Math.pow(2, e - 52); }; -TCompactProtocol.prototype.readBinary = function() { +TCompactProtocol.prototype.readBinary = function () { var size = this.readVarint32(); if (size === 0) { return new Buffer(0); } if (size < 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(size); }; -TCompactProtocol.prototype.readString = function() { +TCompactProtocol.prototype.readString = function () { var size = this.readVarint32(); // Catch empty string case if (size === 0) { @@ -778,12 +806,14 @@ TCompactProtocol.prototype.readString = function() { // Catch error cases if (size < 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(size); }; - // // Compact Protocol internal read operations // @@ -792,7 +822,7 @@ TCompactProtocol.prototype.readString = function() { * Read an i32 from the wire as a varint. The MSB of each byte is set * if there is another byte to follow. This can read up to 5 bytes. */ -TCompactProtocol.prototype.readVarint32 = function() { +TCompactProtocol.prototype.readVarint32 = function () { return this.readVarint64().toNumber(); }; @@ -800,28 +830,31 @@ TCompactProtocol.prototype.readVarint32 = function() { * Read an i64 from the wire as a proper varint. The MSB of each byte is set * if there is another byte to follow. This can read up to 10 bytes. */ -TCompactProtocol.prototype.readVarint64 = function() { +TCompactProtocol.prototype.readVarint64 = function () { var rsize = 0; var lo = 0; var hi = 0; var shift = 0; while (true) { var b = this.trans.readByte(); - rsize ++; + rsize++; if (shift <= 25) { lo = lo | ((b & 0x7f) << shift); } else if (25 < shift && shift < 32) { lo = lo | ((b & 0x7f) << shift); - hi = hi | ((b & 0x7f) >>> (32-shift)); + hi = hi | ((b & 0x7f) >>> (32 - shift)); } else { - hi = hi | ((b & 0x7f) << (shift-32)); + hi = hi | ((b & 0x7f) << (shift - 32)); } shift += 7; if (!(b & 0x80)) { break; } if (rsize >= 10) { - throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Variable-length int over 10 bytes."); + throw new Thrift.TProtocolException( + Thrift.TProtocolExceptionType.INVALID_DATA, + "Variable-length int over 10 bytes.", + ); } } return new Int64(hi, lo); @@ -830,14 +863,14 @@ TCompactProtocol.prototype.readVarint64 = function() { /** * Convert from zigzag int to int. */ -TCompactProtocol.prototype.zigzagToI32 = function(n) { +TCompactProtocol.prototype.zigzagToI32 = function (n) { return (n >>> 1) ^ (-1 * (n & 1)); }; /** * Convert from zigzag long to long. */ -TCompactProtocol.prototype.zigzagToI64 = function(n) { +TCompactProtocol.prototype.zigzagToI64 = function (n) { var hi = n.buffer.readUInt32BE(0, true); var lo = n.buffer.readUInt32BE(4, true); @@ -846,13 +879,13 @@ TCompactProtocol.prototype.zigzagToI64 = function(n) { var hi_neg = neg.buffer.readUInt32BE(0, true); var lo_neg = neg.buffer.readUInt32BE(4, true); - var hi_lo = (hi << 31); - hi = (hi >>> 1) ^ (hi_neg); - lo = ((lo >>> 1) | hi_lo) ^ (lo_neg); + var hi_lo = hi << 31; + hi = (hi >>> 1) ^ hi_neg; + lo = ((lo >>> 1) | hi_lo) ^ lo_neg; return new Int64(hi, lo); }; -TCompactProtocol.prototype.skip = function(type) { +TCompactProtocol.prototype.skip = function (type) { switch (type) { case Type.BOOL: this.readBool(); @@ -910,6 +943,6 @@ TCompactProtocol.prototype.skip = function(type) { this.readListEnd(); break; default: - throw new Error("Invalid type: " + type); + throw new Error("Invalid type: " + type); } }; diff --git a/lib/nodejs/lib/thrift/connection.js b/lib/nodejs/lib/thrift/connection.js index b4e5a05277d..dcade80dc88 100644 --- a/lib/nodejs/lib/thrift/connection.js +++ b/lib/nodejs/lib/thrift/connection.js @@ -16,29 +16,29 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); -var EventEmitter = require('events').EventEmitter; -var constants = require('constants'); -var net = require('net'); -var tls = require('tls'); -var thrift = require('./thrift'); -var log = require('./log'); +var util = require("util"); +var EventEmitter = require("events").EventEmitter; +var constants = require("constants"); +var net = require("net"); +var tls = require("tls"); +var thrift = require("./thrift"); +var log = require("./log"); -var TBufferedTransport = require('./buffered_transport'); -var TBinaryProtocol = require('./binary_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var TBufferedTransport = require("./buffered_transport"); +var TBinaryProtocol = require("./binary_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); -var createClient = require('./create_client'); +var createClient = require("./create_client"); -var binary = require('./binary'); +var binary = require("./binary"); -var Connection = exports.Connection = function(stream, options) { +var Connection = (exports.Connection = function (stream, options) { var self = this; EventEmitter.call(this); this.seqId2Service = {}; this.connection = stream; - this.ssl = (stream.encrypted); + this.ssl = stream.encrypted; this.options = options || {}; this.transport = this.options.transport || TBufferedTransport; this.protocol = this.options.protocol || TBinaryProtocol; @@ -48,123 +48,139 @@ var Connection = exports.Connection = function(stream, options) { this.initialize_retry_vars(); this._debug = this.options.debug || false; - if (this.options.max_attempts && - !isNaN(this.options.max_attempts) && - this.options.max_attempts > 0) { - this.max_attempts = +this.options.max_attempts; + if ( + this.options.max_attempts && + !isNaN(this.options.max_attempts) && + this.options.max_attempts > 0 + ) { + this.max_attempts = +this.options.max_attempts; } this.retry_max_delay = null; - if (this.options.retry_max_delay !== undefined && - !isNaN(this.options.retry_max_delay) && - this.options.retry_max_delay > 0) { - this.retry_max_delay = this.options.retry_max_delay; + if ( + this.options.retry_max_delay !== undefined && + !isNaN(this.options.retry_max_delay) && + this.options.retry_max_delay > 0 + ) { + this.retry_max_delay = this.options.retry_max_delay; } this.connect_timeout = false; - if (this.options.connect_timeout && - !isNaN(this.options.connect_timeout) && - this.options.connect_timeout > 0) { - this.connect_timeout = +this.options.connect_timeout; + if ( + this.options.connect_timeout && + !isNaN(this.options.connect_timeout) && + this.options.connect_timeout > 0 + ) { + this.connect_timeout = +this.options.connect_timeout; } - this.connection.addListener(this.ssl ? "secureConnect" : "connect", function() { - self.connected = true; + this.connection.addListener( + this.ssl ? "secureConnect" : "connect", + function () { + self.connected = true; - this.setTimeout(self.options.timeout || 0); - this.setNoDelay(); - this.frameLeft = 0; - this.framePos = 0; - this.frame = null; - self.initialize_retry_vars(); - self.flush_offline_queue(); + this.setTimeout(self.options.timeout || 0); + this.setNoDelay(); + this.frameLeft = 0; + this.framePos = 0; + this.frame = null; + self.initialize_retry_vars(); + self.flush_offline_queue(); - self.emit("connect"); - }); + self.emit("connect"); + }, + ); - this.connection.addListener("error", function(err) { + this.connection.addListener("error", function (err) { // Only emit the error if no-one else is listening on the connection // or if someone is listening on us, because Node turns unhandled // 'error' events into exceptions. - if (self.connection.listeners('error').length === 1 || - self.listeners('error').length > 0) { + if ( + self.connection.listeners("error").length === 1 || + self.listeners("error").length > 0 + ) { self.emit("error", err); } }); // Add a close listener - this.connection.addListener("close", function() { + this.connection.addListener("close", function () { self.connection_gone(); // handle close event. try to reconnect }); - this.connection.addListener("timeout", function() { + this.connection.addListener("timeout", function () { self.emit("timeout"); }); - this.connection.addListener("data", self.transport.receiver(function(transport_with_data) { - var message = new self.protocol(transport_with_data); - try { - while (true) { - var header = message.readMessageBegin(); - var dummy_seqid = header.rseqid * -1; - var client = self.client; - //The Multiplexed Protocol stores a hash of seqid to service names - // in seqId2Service. If the SeqId is found in the hash we need to - // lookup the appropriate client for this call. - // The connection.client object is a single client object when not - // multiplexing, when using multiplexing it is a service name keyed - // hash of client objects. - //NOTE: The 2 way interdependencies between protocols, transports, - // connections and clients in the Node.js implementation are irregular - // and make the implementation difficult to extend and maintain. We - // should bring this stuff inline with typical thrift I/O stack - // operation soon. - // --ra - var service_name = self.seqId2Service[header.rseqid]; - if (service_name) { - client = self.client[service_name]; - } - /*jshint -W083 */ - client._reqs[dummy_seqid] = function(err, success){ - transport_with_data.commitPosition(); - - var callback = client._reqs[header.rseqid]; - delete client._reqs[header.rseqid]; + this.connection.addListener( + "data", + self.transport.receiver(function (transport_with_data) { + var message = new self.protocol(transport_with_data); + try { + while (true) { + var header = message.readMessageBegin(); + var dummy_seqid = header.rseqid * -1; + var client = self.client; + //The Multiplexed Protocol stores a hash of seqid to service names + // in seqId2Service. If the SeqId is found in the hash we need to + // lookup the appropriate client for this call. + // The connection.client object is a single client object when not + // multiplexing, when using multiplexing it is a service name keyed + // hash of client objects. + //NOTE: The 2 way interdependencies between protocols, transports, + // connections and clients in the Node.js implementation are irregular + // and make the implementation difficult to extend and maintain. We + // should bring this stuff inline with typical thrift I/O stack + // operation soon. + // --ra + var service_name = self.seqId2Service[header.rseqid]; if (service_name) { - delete self.seqId2Service[header.rseqid]; + client = self.client[service_name]; } - if (callback) { - callback(err, success); + /*jshint -W083 */ + client._reqs[dummy_seqid] = function (err, success) { + transport_with_data.commitPosition(); + + var callback = client._reqs[header.rseqid]; + delete client._reqs[header.rseqid]; + if (service_name) { + delete self.seqId2Service[header.rseqid]; + } + if (callback) { + callback(err, success); + } + }; + /*jshint +W083 */ + + if (client["recv_" + header.fname]) { + client["recv_" + header.fname](message, header.mtype, dummy_seqid); + } else { + delete client._reqs[dummy_seqid]; + self.emit( + "error", + new thrift.TApplicationException( + thrift.TApplicationExceptionType.WRONG_METHOD_NAME, + "Received a response to an unknown RPC function", + ), + ); } - }; - /*jshint +W083 */ - - if(client['recv_' + header.fname]) { - client['recv_' + header.fname](message, header.mtype, dummy_seqid); + } + } catch (e) { + if (e instanceof InputBufferUnderrunError) { + transport_with_data.rollbackPosition(); } else { - delete client._reqs[dummy_seqid]; - self.emit("error", - new thrift.TApplicationException(thrift.TApplicationExceptionType.WRONG_METHOD_NAME, - "Received a response to an unknown RPC function")); + self.emit("error", e); } } - } - catch (e) { - if (e instanceof InputBufferUnderrunError) { - transport_with_data.rollbackPosition(); - } - else { - self.emit('error', e); - } - } - })); -}; + }), + ); +}); util.inherits(Connection, EventEmitter); -Connection.prototype.end = function() { +Connection.prototype.end = function () { this.forceClose = true; this.connection.end(); }; -Connection.prototype.destroy = function() { +Connection.prototype.destroy = function () { this.connection.destroy(); }; @@ -183,12 +199,12 @@ Connection.prototype.flush_offline_queue = function () { // Reset offline queue this.offline_queue = []; // Attempt to write queued items - offline_queue.forEach(function(data) { + offline_queue.forEach(function (data) { self.write(data); }); }; -Connection.prototype.write = function(data) { +Connection.prototype.write = function (data) { if (!this.connected) { this.offline_queue.push(data); return; @@ -201,7 +217,7 @@ Connection.prototype.connection_gone = function () { this.connected = false; // If closed by manual, emit close event and cancel reconnect process - if(this.forceClose) { + if (this.forceClose) { if (this.retry_timer) { clearTimeout(this.retry_timer); this.retry_timer = null; @@ -220,7 +236,10 @@ Connection.prototype.connection_gone = function () { return; } - if (this.retry_max_delay !== null && this.retry_delay >= this.retry_max_delay) { + if ( + this.retry_max_delay !== null && + this.retry_delay >= this.retry_max_delay + ) { this.retry_delay = this.retry_max_delay; } else { this.retry_delay = Math.floor(this.retry_delay * this.retry_backoff); @@ -230,7 +249,11 @@ Connection.prototype.connection_gone = function () { if (this.max_attempts && this.attempts >= this.max_attempts) { this.retry_timer = null; - console.error("thrift: Couldn't get thrift connection after " + this.max_attempts + " attempts."); + console.error( + "thrift: Couldn't get thrift connection after " + + this.max_attempts + + " attempts.", + ); self.emit("close"); return; } @@ -238,7 +261,7 @@ Connection.prototype.connection_gone = function () { this.attempts += 1; this.emit("reconnecting", { delay: self.retry_delay, - attempt: self.attempts + attempt: self.attempts, }); this.retry_timer = setTimeout(function () { @@ -247,10 +270,14 @@ Connection.prototype.connection_gone = function () { self.retry_totaltime += self.retry_delay; if (self.connect_timeout && self.retry_totaltime >= self.connect_timeout) { - self.retry_timer = null; - console.error("thrift: Couldn't get thrift connection after " + self.retry_totaltime + "ms."); - self.emit("close"); - return; + self.retry_timer = null; + console.error( + "thrift: Couldn't get thrift connection after " + + self.retry_totaltime + + "ms.", + ); + self.emit("close"); + return; } if (self.path !== undefined) { @@ -262,11 +289,11 @@ Connection.prototype.connection_gone = function () { }, this.retry_delay); }; -exports.createConnection = function(host, port, options) { - var stream = net.createConnection( { +exports.createConnection = function (host, port, options) { + var stream = net.createConnection({ port: port, host: host, - timeout: options.connect_timeout || options.timeout || 0 + timeout: options.connect_timeout || options.timeout || 0, }); var connection = new Connection(stream, options); connection.host = host; @@ -275,7 +302,7 @@ exports.createConnection = function(host, port, options) { return connection; }; -exports.createUDSConnection = function(path, options) { +exports.createUDSConnection = function (path, options) { var stream = net.createConnection(path); var connection = new Connection(stream, options); connection.path = path; @@ -283,10 +310,11 @@ exports.createUDSConnection = function(path, options) { return connection; }; -exports.createSSLConnection = function(host, port, options) { - if (!('secureProtocol' in options) && !('secureOptions' in options)) { +exports.createSSLConnection = function (host, port, options) { + if (!("secureProtocol" in options) && !("secureOptions" in options)) { options.secureProtocol = "SSLv23_method"; - options.secureOptions = constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3; + options.secureOptions = + constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3; } var stream = tls.connect(port, host, options); @@ -297,15 +325,14 @@ exports.createSSLConnection = function(host, port, options) { return connection; }; - exports.createClient = createClient; -var child_process = require('child_process'); -var StdIOConnection = exports.StdIOConnection = function(command, options) { - var command_parts = command.split(' '); +var child_process = require("child_process"); +var StdIOConnection = (exports.StdIOConnection = function (command, options) { + var command_parts = command.split(" "); command = command_parts[0]; - var args = command_parts.splice(1,command_parts.length -1); - var child = this.child = child_process.spawn(command,args); + var args = command_parts.splice(1, command_parts.length - 1); + var child = (this.child = child_process.spawn(command, args)); var self = this; EventEmitter.call(this); @@ -316,13 +343,13 @@ var StdIOConnection = exports.StdIOConnection = function(command, options) { this.protocol = this.options.protocol || TBinaryProtocol; this.offline_queue = []; - if (log.getLogLevel() === 'debug') { - this.child.stderr.on('data', function (err) { - log.debug(err.toString(), 'CHILD ERROR'); + if (log.getLogLevel() === "debug") { + this.child.stderr.on("data", function (err) { + log.debug(err.toString(), "CHILD ERROR"); }); - this.child.on('exit', function (code,signal) { - log.debug(code + ':' + signal, 'CHILD EXITED'); + this.child.on("exit", function (code, signal) { + log.debug(code + ":" + signal, "CHILD EXITED"); }); } @@ -333,46 +360,47 @@ var StdIOConnection = exports.StdIOConnection = function(command, options) { self.flush_offline_queue(); - this.connection.addListener("error", function(err) { + this.connection.addListener("error", function (err) { self.emit("error", err); }); // Add a close listener - this.connection.addListener("close", function() { + this.connection.addListener("close", function () { self.emit("close"); }); - child.stdout.addListener("data", self.transport.receiver(function(transport_with_data) { - var message = new self.protocol(transport_with_data); - try { - var header = message.readMessageBegin(); - var dummy_seqid = header.rseqid * -1; - var client = self.client; - client._reqs[dummy_seqid] = function(err, success){ - transport_with_data.commitPosition(); - - var callback = client._reqs[header.rseqid]; - delete client._reqs[header.rseqid]; - if (callback) { - callback(err, success); + child.stdout.addListener( + "data", + self.transport.receiver(function (transport_with_data) { + var message = new self.protocol(transport_with_data); + try { + var header = message.readMessageBegin(); + var dummy_seqid = header.rseqid * -1; + var client = self.client; + client._reqs[dummy_seqid] = function (err, success) { + transport_with_data.commitPosition(); + + var callback = client._reqs[header.rseqid]; + delete client._reqs[header.rseqid]; + if (callback) { + callback(err, success); + } + }; + client["recv_" + header.fname](message, header.mtype, dummy_seqid); + } catch (e) { + if (e instanceof InputBufferUnderrunError) { + transport_with_data.rollbackPosition(); + } else { + throw e; } - }; - client['recv_' + header.fname](message, header.mtype, dummy_seqid); - } - catch (e) { - if (e instanceof InputBufferUnderrunError) { - transport_with_data.rollbackPosition(); - } - else { - throw e; } - } - })); -}; + }), + ); +}); util.inherits(StdIOConnection, EventEmitter); -StdIOConnection.prototype.end = function() { +StdIOConnection.prototype.end = function () { this.connection.end(); }; @@ -383,12 +411,12 @@ StdIOConnection.prototype.flush_offline_queue = function () { // Reset offline queue this.offline_queue = []; // Attempt to write queued items - offline_queue.forEach(function(data) { + offline_queue.forEach(function (data) { self.write(data); }); }; -StdIOConnection.prototype.write = function(data) { +StdIOConnection.prototype.write = function (data) { if (!this.connected) { this.offline_queue.push(data); return; @@ -396,8 +424,8 @@ StdIOConnection.prototype.write = function(data) { this.connection.write(data); }; -exports.createStdIOConnection = function(command,options){ - return new StdIOConnection(command,options); +exports.createStdIOConnection = function (command, options) { + return new StdIOConnection(command, options); }; exports.createStdIOClient = createClient; diff --git a/lib/nodejs/lib/thrift/create_client.js b/lib/nodejs/lib/thrift/create_client.js index d6b77a8339d..b9021bd4290 100644 --- a/lib/nodejs/lib/thrift/create_client.js +++ b/lib/nodejs/lib/thrift/create_client.js @@ -43,7 +43,7 @@ function createClient(ServiceClient, connection) { // - Callback to call on flush // Wrap the write method - var writeCb = function(buf, seqid) { + var writeCb = function (buf, seqid) { connection.write(buf, seqid); }; var transport = new connection.transport(undefined, writeCb); @@ -51,4 +51,4 @@ function createClient(ServiceClient, connection) { transport.client = client; connection.client = client; return client; -}; +} diff --git a/lib/nodejs/lib/thrift/framed_transport.js b/lib/nodejs/lib/thrift/framed_transport.js index 058d2301ff3..7ede2225e5f 100644 --- a/lib/nodejs/lib/thrift/framed_transport.js +++ b/lib/nodejs/lib/thrift/framed_transport.js @@ -17,9 +17,9 @@ * under the License. */ -var binary = require('./binary'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); -var THeaderTransport = require('./header_transport'); +var binary = require("./binary"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); +var THeaderTransport = require("./header_transport"); module.exports = TFramedTransport; @@ -30,14 +30,14 @@ function TFramedTransport(buffer, callback) { this.outCount = 0; this.readPos = 0; this.onFlush = callback; -}; +} Object.setPrototypeOf(TFramedTransport.prototype, THeaderTransport.prototype); -TFramedTransport.receiver = function(callback, seqid) { +TFramedTransport.receiver = function (callback, seqid) { var residual = new Buffer(0); - return function(data) { + return function (data) { residual = Buffer.concat([residual, Buffer.from(data)]); while (residual.length > 0) { @@ -61,34 +61,34 @@ TFramedTransport.receiver = function(callback, seqid) { }; }; -TFramedTransport.prototype.commitPosition = function(){}, -TFramedTransport.prototype.rollbackPosition = function(){}, - +(TFramedTransport.prototype.commitPosition = function () {}), + (TFramedTransport.prototype.rollbackPosition = function () {}), // TODO: Implement open/close support -TFramedTransport.prototype.isOpen = function() { - return true; -}; -TFramedTransport.prototype.open = function() {}; -TFramedTransport.prototype.close = function() {}; + (TFramedTransport.prototype.isOpen = function () { + return true; + }); +TFramedTransport.prototype.open = function () {}; +TFramedTransport.prototype.close = function () {}; - // Set the seqid of the message in the client - // So that callbacks can be found -TFramedTransport.prototype.setCurrSeqId = function(seqid) { +// Set the seqid of the message in the client +// So that callbacks can be found +TFramedTransport.prototype.setCurrSeqId = function (seqid) { this._seqid = seqid; }; -TFramedTransport.prototype.ensureAvailable = function(len) { +TFramedTransport.prototype.ensureAvailable = function (len) { if (this.readPos + len > this.inBuf.length) { throw new InputBufferUnderrunError(); } }; -TFramedTransport.prototype.read = function(len) { // this function will be used for each frames. +TFramedTransport.prototype.read = function (len) { + // this function will be used for each frames. this.ensureAvailable(len); var end = this.readPos + len; if (this.inBuf.length < end) { - throw new Error('read(' + len + ') failed - not enough data'); + throw new Error("read(" + len + ") failed - not enough data"); } var buf = this.inBuf.slice(this.readPos, end); @@ -96,68 +96,68 @@ TFramedTransport.prototype.read = function(len) { // this function will be used return buf; }; -TFramedTransport.prototype.readByte = function() { +TFramedTransport.prototype.readByte = function () { this.ensureAvailable(1); return binary.readByte(this.inBuf[this.readPos++]); }; -TFramedTransport.prototype.readI16 = function() { +TFramedTransport.prototype.readI16 = function () { this.ensureAvailable(2); var i16 = binary.readI16(this.inBuf, this.readPos); this.readPos += 2; return i16; }; -TFramedTransport.prototype.readI32 = function() { +TFramedTransport.prototype.readI32 = function () { this.ensureAvailable(4); var i32 = binary.readI32(this.inBuf, this.readPos); this.readPos += 4; return i32; }; -TFramedTransport.prototype.readDouble = function() { +TFramedTransport.prototype.readDouble = function () { this.ensureAvailable(8); var d = binary.readDouble(this.inBuf, this.readPos); this.readPos += 8; return d; }; -TFramedTransport.prototype.readString = function(len) { +TFramedTransport.prototype.readString = function (len) { this.ensureAvailable(len); - var str = this.inBuf.toString('utf8', this.readPos, this.readPos + len); + var str = this.inBuf.toString("utf8", this.readPos, this.readPos + len); this.readPos += len; return str; }; -TFramedTransport.prototype.borrow = function() { +TFramedTransport.prototype.borrow = function () { return { buf: this.inBuf, readIndex: this.readPos, - writeIndex: this.inBuf.length + writeIndex: this.inBuf.length, }; }; -TFramedTransport.prototype.consume = function(bytesConsumed) { +TFramedTransport.prototype.consume = function (bytesConsumed) { this.readPos += bytesConsumed; }; -TFramedTransport.prototype.write = function(buf, encoding) { - if (typeof(buf) === "string") { - buf = new Buffer(buf, encoding || 'utf8'); +TFramedTransport.prototype.write = function (buf, encoding) { + if (typeof buf === "string") { + buf = new Buffer(buf, encoding || "utf8"); } this.outBuffers.push(buf); this.outCount += buf.length; }; -TFramedTransport.prototype.flush = function() { +TFramedTransport.prototype.flush = function () { // If the seqid of the callback is available pass it to the onFlush // Then remove the current seqid var seqid = this._seqid; this._seqid = null; var out = new Buffer(this.outCount), - pos = 0; - this.outBuffers.forEach(function(buf) { + pos = 0; + this.outBuffers.forEach(function (buf) { buf.copy(out, pos, 0); pos += buf.length; }); diff --git a/lib/nodejs/lib/thrift/header_protocol.js b/lib/nodejs/lib/thrift/header_protocol.js index 8971751fb75..2a48a4d7d2a 100644 --- a/lib/nodejs/lib/thrift/header_protocol.js +++ b/lib/nodejs/lib/thrift/header_protocol.js @@ -16,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); -var TBinaryProtocol = require('./binary_protocol'); -var TCompactProtocol = require('./compact_protocol'); -var THeaderTransport = require('./header_transport'); +var util = require("util"); +var TBinaryProtocol = require("./binary_protocol"); +var TCompactProtocol = require("./compact_protocol"); +var THeaderTransport = require("./header_transport"); var ProtocolMap = {}; ProtocolMap[THeaderTransport.SubprotocolId.BINARY] = TBinaryProtocol; @@ -54,204 +54,206 @@ util.inherits(THeaderProtocolError, Error); function THeaderProtocol(trans) { if (!(trans instanceof THeaderTransport)) { throw new THeaderProtocolError( - 'Only transports that inherit THeaderTransport can be' + - ' used with THeaderProtocol' + "Only transports that inherit THeaderTransport can be" + + " used with THeaderProtocol", ); } this.trans = trans; this.setProtocol(); -}; +} -THeaderProtocol.prototype.flush = function() { - // Headers must be written prior to flushing because because - // you need to calculate the length of the payload for the length - // field of the header +THeaderProtocol.prototype.flush = function () { + // Headers must be written prior to flushing because because + // you need to calculate the length of the payload for the length + // field of the header this.trans.writeHeaders(); return this.trans.flush(); }; -THeaderProtocol.prototype.writeMessageBegin = function(name, type, seqid) { +THeaderProtocol.prototype.writeMessageBegin = function (name, type, seqid) { return this.protocol.writeMessageBegin(name, type, seqid); }; -THeaderProtocol.prototype.writeMessageEnd = function() { +THeaderProtocol.prototype.writeMessageEnd = function () { return this.protocol.writeMessageEnd(); }; -THeaderProtocol.prototype.writeStructBegin = function(name) { +THeaderProtocol.prototype.writeStructBegin = function (name) { return this.protocol.writeStructBegin(name); }; -THeaderProtocol.prototype.writeStructEnd = function() { +THeaderProtocol.prototype.writeStructEnd = function () { return this.protocol.writeStructEnd(); }; -THeaderProtocol.prototype.writeFieldBegin = function(name, type, id) { +THeaderProtocol.prototype.writeFieldBegin = function (name, type, id) { return this.protocol.writeFieldBegin(name, type, id); -} +}; -THeaderProtocol.prototype.writeFieldEnd = function() { +THeaderProtocol.prototype.writeFieldEnd = function () { return this.protocol.writeFieldEnd(); }; -THeaderProtocol.prototype.writeFieldStop = function() { +THeaderProtocol.prototype.writeFieldStop = function () { return this.protocol.writeFieldStop(); }; -THeaderProtocol.prototype.writeMapBegin = function(ktype, vtype, size) { +THeaderProtocol.prototype.writeMapBegin = function (ktype, vtype, size) { return this.protocol.writeMapBegin(ktype, vtype, size); }; -THeaderProtocol.prototype.writeMapEnd = function() { +THeaderProtocol.prototype.writeMapEnd = function () { return this.protocol.writeMapEnd(); }; -THeaderProtocol.prototype.writeListBegin = function(etype, size) { +THeaderProtocol.prototype.writeListBegin = function (etype, size) { return this.protocol.writeListBegin(etype, size); }; -THeaderProtocol.prototype.writeListEnd = function() { +THeaderProtocol.prototype.writeListEnd = function () { return this.protocol.writeListEnd(); }; -THeaderProtocol.prototype.writeSetBegin = function(etype, size) { +THeaderProtocol.prototype.writeSetBegin = function (etype, size) { return this.protocol.writeSetBegin(etype, size); }; -THeaderProtocol.prototype.writeSetEnd = function() { +THeaderProtocol.prototype.writeSetEnd = function () { return this.protocol.writeSetEnd(); }; -THeaderProtocol.prototype.writeBool = function(b) { +THeaderProtocol.prototype.writeBool = function (b) { return this.protocol.writeBool(b); }; -THeaderProtocol.prototype.writeByte = function(b) { +THeaderProtocol.prototype.writeByte = function (b) { return this.protocol.writeByte(b); }; -THeaderProtocol.prototype.writeI16 = function(i16) { +THeaderProtocol.prototype.writeI16 = function (i16) { return this.protocol.writeI16(i16); }; -THeaderProtocol.prototype.writeI32 = function(i32) { +THeaderProtocol.prototype.writeI32 = function (i32) { return this.protocol.writeI32(i32); }; -THeaderProtocol.prototype.writeI64 = function(i64) { +THeaderProtocol.prototype.writeI64 = function (i64) { return this.protocol.writeI64(i64); }; -THeaderProtocol.prototype.writeDouble = function(dub) { +THeaderProtocol.prototype.writeDouble = function (dub) { return this.protocol.writeDouble(dub); }; -THeaderProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) { +THeaderProtocol.prototype.writeStringOrBinary = function (name, encoding, arg) { return this.protocol.writeStringOrBinary(name, encoding, arg); }; -THeaderProtocol.prototype.writeString = function(arg) { +THeaderProtocol.prototype.writeString = function (arg) { return this.protocol.writeString(arg); }; -THeaderProtocol.prototype.writeBinary = function(arg) { +THeaderProtocol.prototype.writeBinary = function (arg) { return this.protocol.writeBinary(arg); }; -THeaderProtocol.prototype.readMessageBegin = function() { +THeaderProtocol.prototype.readMessageBegin = function () { this.trans.readHeaders(); this.setProtocol(); return this.protocol.readMessageBegin(); }; -THeaderProtocol.prototype.readMessageEnd = function() { +THeaderProtocol.prototype.readMessageEnd = function () { return this.protocol.readMessageEnd(); }; -THeaderProtocol.prototype.readStructBegin = function() { +THeaderProtocol.prototype.readStructBegin = function () { return this.protocol.readStructBegin(); }; -THeaderProtocol.prototype.readStructEnd = function() { +THeaderProtocol.prototype.readStructEnd = function () { return this.protocol.readStructEnd(); }; -THeaderProtocol.prototype.readFieldBegin = function() { +THeaderProtocol.prototype.readFieldBegin = function () { return this.protocol.readFieldBegin(); }; -THeaderProtocol.prototype.readFieldEnd = function() { +THeaderProtocol.prototype.readFieldEnd = function () { return this.protocol.readFieldEnd(); }; -THeaderProtocol.prototype.readMapBegin = function() { +THeaderProtocol.prototype.readMapBegin = function () { return this.protocol.readMapBegin(); }; -THeaderProtocol.prototype.readMapEnd = function() { +THeaderProtocol.prototype.readMapEnd = function () { return this.protocol.readMapEnd(); }; -THeaderProtocol.prototype.readListBegin = function() { +THeaderProtocol.prototype.readListBegin = function () { return this.protocol.readListBegin(); }; -THeaderProtocol.prototype.readListEnd = function() { +THeaderProtocol.prototype.readListEnd = function () { return this.protocol.readListEnd(); }; -THeaderProtocol.prototype.readSetBegin = function() { +THeaderProtocol.prototype.readSetBegin = function () { return this.protocol.readSetBegin(); }; -THeaderProtocol.prototype.readSetEnd = function() { +THeaderProtocol.prototype.readSetEnd = function () { return this.protocol.readSetEnd(); }; -THeaderProtocol.prototype.readBool = function() { +THeaderProtocol.prototype.readBool = function () { return this.protocol.readBool(); }; -THeaderProtocol.prototype.readByte = function() { +THeaderProtocol.prototype.readByte = function () { return this.protocol.readByte(); }; -THeaderProtocol.prototype.readI16 = function() { +THeaderProtocol.prototype.readI16 = function () { return this.protocol.readI16(); }; -THeaderProtocol.prototype.readI32 = function() { +THeaderProtocol.prototype.readI32 = function () { return this.protocol.readI32(); }; -THeaderProtocol.prototype.readI64 = function() { +THeaderProtocol.prototype.readI64 = function () { return this.protocol.readI64(); }; -THeaderProtocol.prototype.readDouble = function() { +THeaderProtocol.prototype.readDouble = function () { return this.protocol.readDouble(); }; -THeaderProtocol.prototype.readBinary = function() { +THeaderProtocol.prototype.readBinary = function () { return this.protocol.readBinary(); }; -THeaderProtocol.prototype.readString = function() { +THeaderProtocol.prototype.readString = function () { return this.protocol.readString(); }; -THeaderProtocol.prototype.getTransport = function() { +THeaderProtocol.prototype.getTransport = function () { return this.trans; }; -THeaderProtocol.prototype.skip = function(type) { +THeaderProtocol.prototype.skip = function (type) { return this.protocol.skip(type); }; -THeaderProtocol.prototype.setProtocol = function(subProtocolId) { +THeaderProtocol.prototype.setProtocol = function (subProtocolId) { var subProtocolId = this.trans.getProtocolId(); if (!ProtocolMap[subProtocolId]) { - throw new THeaderProtocolError('Headers not supported for protocol ' + subProtocolId); + throw new THeaderProtocolError( + "Headers not supported for protocol " + subProtocolId, + ); } this.protocol = new ProtocolMap[subProtocolId](this.trans); diff --git a/lib/nodejs/lib/thrift/header_transport.js b/lib/nodejs/lib/thrift/header_transport.js index ec8624b02a7..37da4924129 100644 --- a/lib/nodejs/lib/thrift/header_transport.js +++ b/lib/nodejs/lib/thrift/header_transport.js @@ -17,10 +17,10 @@ * under the License. */ -var util = require('util'); -var TCompactProtocol = require('./compact_protocol'); -var TBinaryProtocol = require('./binary_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var util = require("util"); +var TCompactProtocol = require("./compact_protocol"); +var TBinaryProtocol = require("./binary_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); function THeaderTransportError(message) { Error.call(this); @@ -45,51 +45,51 @@ var SEQID_OFFSET = 64 / 8; var HEADER_SIZE_OFFSET = 96 / 8; var HEADER_START_OFFSET = 112 / 8; -var HEADER_MAGIC = 0x0FFF; +var HEADER_MAGIC = 0x0fff; var TINFO_HEADER_KEY_VALUE_TYPE = 0x01; -var MAX_FRAME_SIZE = 0x3FFFFFFF; +var MAX_FRAME_SIZE = 0x3fffffff; - // A helper class for reading/writing varints. Uses - // TCompactProtocol under the hood +// A helper class for reading/writing varints. Uses +// TCompactProtocol under the hood function VarintHelper(readBuffer) { - var TBufferedTransport = require('./buffered_transport'); + var TBufferedTransport = require("./buffered_transport"); this.outputBuffer = null; var _this = this; - this.transport = new TBufferedTransport(null, function(output) { + this.transport = new TBufferedTransport(null, function (output) { _this.outputBuffer = output; }); this.transport.inBuf = readBuffer || Buffer.alloc(0); this.transport.writeCursor = this.transport.inBuf.length; this.protocol = new TCompactProtocol(this.transport); -}; +} -VarintHelper.prototype.readVarint32 = function() { +VarintHelper.prototype.readVarint32 = function () { return this.protocol.readVarint32(); }; -VarintHelper.prototype.writeVarint32 = function(i) { +VarintHelper.prototype.writeVarint32 = function (i) { this.protocol.writeVarint32(i); }; -VarintHelper.prototype.readString = function() { +VarintHelper.prototype.readString = function () { return this.protocol.readString(); }; -VarintHelper.prototype.writeString = function(str) { +VarintHelper.prototype.writeString = function (str) { this.protocol.writeString(str); -} +}; -VarintHelper.prototype.getOutCount = function() { +VarintHelper.prototype.getOutCount = function () { return this.transport.outCount; }; -VarintHelper.prototype.write = function(str) { +VarintHelper.prototype.write = function (str) { this.transport.write(str); }; -VarintHelper.prototype.toBuffer = function() { +VarintHelper.prototype.toBuffer = function () { this.transport.flush(); return this.outputBuffer; }; @@ -127,87 +127,90 @@ function THeaderTransport() { this.flags = null; this.seqid = 0; this.shouldWriteHeaders = true; -}; +} -var validateHeaders = function(key, value) { - if (typeof key !== 'string' || typeof value !== 'string') { - throw new THeaderTransportError('Header key and values must be strings'); +var validateHeaders = function (key, value) { + if (typeof key !== "string" || typeof value !== "string") { + throw new THeaderTransportError("Header key and values must be strings"); } }; -var validateProtocolId = function(protocolId) { +var validateProtocolId = function (protocolId) { var protocols = Object.keys(THeaderTransport.SubprotocolId); for (var i = 0; i < protocols.length; i++) { - if (protocolId === THeaderTransport.SubprotocolId[protocols[i]]) return true; + if (protocolId === THeaderTransport.SubprotocolId[protocols[i]]) + return true; } - throw new Error(protocolId + ' is not a valid protocol id'); + throw new Error(protocolId + " is not a valid protocol id"); }; -THeaderTransport.prototype.setSeqId = function(seqid) { +THeaderTransport.prototype.setSeqId = function (seqid) { this.seqid = seqid; }; -THeaderTransport.prototype.getSeqId = function(seqid) { +THeaderTransport.prototype.getSeqId = function (seqid) { return this.seqid; }; -THeaderTransport.prototype.setFlags = function(flags) { +THeaderTransport.prototype.setFlags = function (flags) { this.flags = flags; }; -THeaderTransport.prototype.getReadHeaders = function() { +THeaderTransport.prototype.getReadHeaders = function () { return this.rheaders; }; -THeaderTransport.prototype.setReadHeader = function(key, value) { +THeaderTransport.prototype.setReadHeader = function (key, value) { validateHeaders(key, value); this.rheaders[key] = value; }; -THeaderTransport.prototype.clearReadHeaders = function() { +THeaderTransport.prototype.clearReadHeaders = function () { this.rheaders = {}; }; -THeaderTransport.prototype.getWriteHeaders = function() { +THeaderTransport.prototype.getWriteHeaders = function () { return this.wheaders; }; -THeaderTransport.prototype.setWriteHeader = function(key, value) { +THeaderTransport.prototype.setWriteHeader = function (key, value) { validateHeaders(key, value); this.wheaders[key] = value; }; -THeaderTransport.prototype.clearWriteHeaders = function() { +THeaderTransport.prototype.clearWriteHeaders = function () { this.wheaders = {}; }; -THeaderTransport.prototype.setMaxFrameSize = function(frameSize) { +THeaderTransport.prototype.setMaxFrameSize = function (frameSize) { this.maxFrameSize = frameSize; }; -THeaderTransport.prototype.setProtocolId = function(protocolId) { +THeaderTransport.prototype.setProtocolId = function (protocolId) { validateProtocolId(protocolId); this.protocolId = protocolId; }; -THeaderTransport.prototype.getProtocolId = function() { +THeaderTransport.prototype.getProtocolId = function () { return this.protocolId; }; -var isUnframedBinary = function(readBuffer) { +var isUnframedBinary = function (readBuffer) { var version = readBuffer.readInt32BE(); return (version & TBinaryProtocol.VERSION_MASK) === TBinaryProtocol.VERSION_1; -} +}; -var isUnframedCompact = function(readBuffer) { +var isUnframedCompact = function (readBuffer) { var protocolId = readBuffer.readInt8(COMPACT_PROTOCOL_OFFSET); var version = readBuffer.readInt8(COMPACT_PROTOCOL_VERSION_OFFSET); - return protocolId === TCompactProtocol.PROTOCOL_ID && - (version & TCompactProtocol.VERSION_MASK) === TCompactProtocol.VERSION_N; -} + return ( + protocolId === TCompactProtocol.PROTOCOL_ID && + (version & TCompactProtocol.VERSION_MASK) === TCompactProtocol.VERSION_N + ); +}; -THeaderTransport.prototype.readHeaders = function() { +THeaderTransport.prototype.readHeaders = function () { var readBuffer = this.inBuf; var isUnframed = false; @@ -228,7 +231,7 @@ THeaderTransport.prototype.readHeaders = function() { var frameSize = readBuffer.readInt32BE(FRAME_SIZE_OFFSET); if (frameSize > this.maxFrameSize) { - throw new THeaderTransportError('Frame exceeds maximum frame size'); + throw new THeaderTransportError("Frame exceeds maximum frame size"); } var headerMagic = readBuffer.readInt16BE(HEADER_MAGIC_OFFSET); @@ -242,7 +245,7 @@ THeaderTransport.prototype.readHeaders = function() { var headerSize = readBuffer.readInt16BE(HEADER_SIZE_OFFSET) * 4; var endOfHeaders = HEADER_START_OFFSET + headerSize; if (endOfHeaders > readBuffer.length) { - throw new THeaderTransportError('Header size is greater than frame size'); + throw new THeaderTransportError("Header size is greater than frame size"); } var headerBuffer = Buffer.alloc(headerSize); @@ -252,7 +255,7 @@ THeaderTransport.prototype.readHeaders = function() { this.setProtocolId(varintHelper.readVarint32()); var transformCount = varintHelper.readVarint32(); if (transformCount > 0) { - throw new THeaderTransportError('Transforms are not yet supported'); + throw new THeaderTransportError("Transforms are not yet supported"); } while (true) { @@ -281,7 +284,7 @@ THeaderTransport.prototype.readHeaders = function() { return this.getReadHeaders(); }; -THeaderTransport.prototype.writeHeaders = function() { +THeaderTransport.prototype.writeHeaders = function () { // only write headers on the server if the client contained headers if (!this.shouldWriteHeaders) { return; @@ -305,11 +308,13 @@ THeaderTransport.prototype.writeHeaders = function() { varintWriter.writeString(value); } } - var headerSizeWithoutPadding = varintWriter.getOutCount(); + var headerSizeWithoutPadding = varintWriter.getOutCount(); var paddingNeeded = (4 - (headerSizeWithoutPadding % 4)) % 4; var headerSize = Buffer.alloc(2); - headerSize.writeInt16BE(Math.floor((headerSizeWithoutPadding + paddingNeeded) / 4)); + headerSize.writeInt16BE( + Math.floor((headerSizeWithoutPadding + paddingNeeded) / 4), + ); var paddingBuffer = Buffer.alloc(paddingNeeded); paddingBuffer.fill(0x00); diff --git a/lib/nodejs/lib/thrift/http_connection.js b/lib/nodejs/lib/thrift/http_connection.js index 17e0d0c2995..50d3312baad 100644 --- a/lib/nodejs/lib/thrift/http_connection.js +++ b/lib/nodejs/lib/thrift/http_connection.js @@ -16,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); -var http = require('http'); -var https = require('https'); -var EventEmitter = require('events').EventEmitter; -var thrift = require('./thrift'); +var util = require("util"); +var http = require("http"); +var https = require("https"); +var EventEmitter = require("events").EventEmitter; +var thrift = require("./thrift"); -var TBufferedTransport = require('./buffered_transport'); -var TBinaryProtocol = require('./binary_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var TBufferedTransport = require("./buffered_transport"); +var TBinaryProtocol = require("./binary_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); -var createClient = require('./create_client'); +var createClient = require("./create_client"); /** * @class @@ -69,7 +69,7 @@ var createClient = require('./create_client'); * semantics implemented over the Node.js http.request() method. * @see {@link createHttpConnection} */ -var HttpConnection = exports.HttpConnection = function(options) { +var HttpConnection = (exports.HttpConnection = function (options) { //Initialize the emitter base object EventEmitter.call(this); @@ -88,17 +88,17 @@ var HttpConnection = exports.HttpConnection = function(options) { host: this.host, port: this.port, socketPath: this.socketPath, - path: this.options.path || '/', - method: 'POST', + 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]; } /*jshint -W069 */ - if (! this.nodeOptions.headers['Connection']) { - this.nodeOptions.headers['Connection'] = 'keep-alive'; + if (!this.nodeOptions.headers["Connection"]) { + this.nodeOptions.headers["Connection"] = "keep-alive"; } /*jshint +W069 */ @@ -131,41 +131,42 @@ var HttpConnection = exports.HttpConnection = function(options) { delete self.seqId2Service[header.rseqid]; } /*jshint -W083 */ - client._reqs[dummy_seqid] = function(err, success){ + client._reqs[dummy_seqid] = function (err, success) { transport_with_data.commitPosition(); var clientCallback = client._reqs[header.rseqid]; delete client._reqs[header.rseqid]; if (clientCallback) { - process.nextTick(function() { + process.nextTick(function () { clientCallback(err, success); }); } }; /*jshint +W083 */ - if(client['recv_' + header.fname]) { - client['recv_' + header.fname](proto, header.mtype, dummy_seqid); + if (client["recv_" + header.fname]) { + client["recv_" + header.fname](proto, header.mtype, dummy_seqid); } else { delete client._reqs[dummy_seqid]; - self.emit("error", - new thrift.TApplicationException( - thrift.TApplicationExceptionType.WRONG_METHOD_NAME, - "Received a response to an unknown RPC function")); + self.emit( + "error", + new thrift.TApplicationException( + thrift.TApplicationExceptionType.WRONG_METHOD_NAME, + "Received a response to an unknown RPC function", + ), + ); } } - } - catch (e) { + } catch (e) { if (e instanceof InputBufferUnderrunError) { transport_with_data.rollbackPosition(); } else { - self.emit('error', e); + self.emit("error", e); } } } - //Response handler ////////////////////////////////////////////////// - this.responseCallback = function(response) { + this.responseCallback = function (response) { var data = []; var dataLen = 0; @@ -173,16 +174,18 @@ var HttpConnection = exports.HttpConnection = function(options) { this.emit("error", new THTTPException(response)); } - response.on('error', function (e) { + response.on("error", function (e) { self.emit("error", e); }); // When running directly under node, chunk will be a buffer, // 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]')) { + response.on("data", function (chunk) { + 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 { @@ -191,9 +194,9 @@ var HttpConnection = exports.HttpConnection = function(options) { dataLen += chunk.length; }); - response.on('end', function(){ + response.on("end", function () { var buf = new Buffer(dataLen); - for (var i=0, len=data.length, pos=0; i (negative ? 20 : 19)) { - throw new RangeError('Too many digits for Int64: ' + text); + throw new RangeError("Too many digits for Int64: " + text); } else { // Most significant (up to 5) digits var high5 = +text.slice(negative ? 1 : 0, -15); - var low = +text.slice(-15) + high5 * 2764472320; // The literal is 10^15 % 2^32 - var high = Math.floor(low / POW2_32) + high5 * 232830; // The literal is 10^15 / 2^&32 + var low = +text.slice(-15) + high5 * 2764472320; // The literal is 10^15 % 2^32 + var high = Math.floor(low / POW2_32) + high5 * 232830; // The literal is 10^15 / 2^&32 low = low % POW2_32; - if (high >= POW2_31 && - !(negative && high == POW2_31 && low == 0) // Allow minimum Int64 - ) { - throw new RangeError('The magnitude is too large for Int64.'); + if ( + high >= POW2_31 && + !(negative && high == POW2_31 && low == 0) // Allow minimum Int64 + ) { + throw new RangeError("The magnitude is too large for Int64."); } if (negative) { // 2's complement diff --git a/lib/nodejs/lib/thrift/json_parse.js b/lib/nodejs/lib/thrift/json_parse.js index 93b0bf2ab95..3d111c08e53 100644 --- a/lib/nodejs/lib/thrift/json_parse.js +++ b/lib/nodejs/lib/thrift/json_parse.js @@ -12,7 +12,6 @@ * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ - /*jslint for */ /*property @@ -20,280 +19,260 @@ prototype, push, r, t, text */ -var Int64 = require('node-int64'); -var Int64Util = require('./int64_util'); - -var json_parse = module.exports = (function () { - "use strict"; - -// This is a function that can parse a JSON text, producing a JavaScript -// data structure. It is a simple, recursive descent parser. It does not use -// eval or regular expressions, so it can be used as a model for implementing -// a JSON parser in other languages. - -// We are defining the function inside of another function to avoid creating -// global variables. - - var at, // The index of the current character - ch, // The current character - escapee = { - '"': '"', - '\\': '\\', - '/': '/', - b: '\b', - f: '\f', - n: '\n', - r: '\r', - t: '\t' - }, - text, - - error = function (m) { - -// Call error when something is wrong. - - throw new SyntaxError(m); - }, - - next = function (c) { - -// If a c parameter is provided, verify that it matches the current character. - - if (c && c !== ch) { - error("Expected '" + c + "' instead of '" + ch + "'"); - } - -// Get the next character. When there are no more characters, -// return the empty string. - - ch = text.charAt(at); - at += 1; - return ch; - }, - - number = function () { - -// Parse a number value. - - var number, - string = ''; - - if (ch === '-') { - string = '-'; - next('-'); - } - while (ch >= '0' && ch <= '9') { - string += ch; - next(); - } - if (ch === '.') { - string += '.'; - while (next() && ch >= '0' && ch <= '9') { - string += ch; - } - } - if (ch === 'e' || ch === 'E') { - string += ch; - next(); - if (ch === '-' || ch === '+') { - string += ch; - next(); - } - while (ch >= '0' && ch <= '9') { - string += ch; - next(); +var Int64 = require("node-int64"); +var Int64Util = require("./int64_util"); + +var json_parse = (module.exports = (function () { + "use strict"; + + // This is a function that can parse a JSON text, producing a JavaScript + // data structure. It is a simple, recursive descent parser. It does not use + // eval or regular expressions, so it can be used as a model for implementing + // a JSON parser in other languages. + + // We are defining the function inside of another function to avoid creating + // global variables. + + var at, // The index of the current character + ch, // The current character + escapee = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + }, + text, + error = function (m) { + // Call error when something is wrong. + + throw new SyntaxError(m); + }, + next = function (c) { + // If a c parameter is provided, verify that it matches the current character. + + if (c && c !== ch) { + error("Expected '" + c + "' instead of '" + ch + "'"); + } + + // Get the next character. When there are no more characters, + // return the empty string. + + ch = text.charAt(at); + at += 1; + return ch; + }, + number = function () { + // Parse a number value. + + var number, + string = ""; + + if (ch === "-") { + string = "-"; + next("-"); + } + while (ch >= "0" && ch <= "9") { + string += ch; + next(); + } + if (ch === ".") { + string += "."; + while (next() && ch >= "0" && ch <= "9") { + string += ch; + } + } + if (ch === "e" || ch === "E") { + string += ch; + next(); + if (ch === "-" || ch === "+") { + string += ch; + next(); + } + while (ch >= "0" && ch <= "9") { + string += ch; + next(); + } + } + number = +string; + if (!isFinite(number)) { + error("Bad number"); + } else if (number >= Int64.MAX_INT || number <= Int64.MIN_INT) { + // Return raw string for further process in TJSONProtocol + return string; + } else { + return number; + } + }, + string = function () { + // Parse a string value. + + var hex, + i, + string = "", + uffff; + + // When parsing for string values, we must look for " and \ characters. + + if (ch === '"') { + while (next()) { + if (ch === '"') { + next(); + return string; + } + if (ch === "\\") { + next(); + if (ch === "u") { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; } - } - number = +string; - if (!isFinite(number)) { - error("Bad number"); - } else if (number >= Int64.MAX_INT || number <= Int64.MIN_INT) { - // Return raw string for further process in TJSONProtocol - return string; + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === "string") { + string += escapee[ch]; } else { - return number; - } - }, - - string = function () { - -// Parse a string value. - - var hex, - i, - string = '', - uffff; - -// When parsing for string values, we must look for " and \ characters. - - if (ch === '"') { - while (next()) { - if (ch === '"') { - next(); - return string; - } - if (ch === '\\') { - next(); - if (ch === 'u') { - uffff = 0; - for (i = 0; i < 4; i += 1) { - hex = parseInt(next(), 16); - if (!isFinite(hex)) { - break; - } - uffff = uffff * 16 + hex; - } - string += String.fromCharCode(uffff); - } else if (typeof escapee[ch] === 'string') { - string += escapee[ch]; - } else { - break; - } - } else { - string += ch; - } - } + break; } - error("Bad string"); - }, - - white = function () { - -// Skip whitespace. - - while (ch && ch <= ' ') { - next(); - } - }, - - word = function () { - -// true, false, or null. - - switch (ch) { - case 't': - next('t'); - next('r'); - next('u'); - next('e'); - return true; - case 'f': - next('f'); - next('a'); - next('l'); - next('s'); - next('e'); - return false; - case 'n': - next('n'); - next('u'); - next('l'); - next('l'); - return null; - } - error("Unexpected '" + ch + "'"); - }, - - value, // Place holder for the value function. - - array = function () { - -// Parse an array value. - - var array = []; - - if (ch === '[') { - next('['); - white(); - if (ch === ']') { - next(']'); - return array; // empty array - } - while (ch) { - array.push(value()); - white(); - if (ch === ']') { - next(']'); - return array; - } - next(','); - white(); - } - } - error("Bad array"); - }, - - object = function () { - -// Parse an object value. - - var key, - object = {}; - - if (ch === '{') { - next('{'); - white(); - if (ch === '}') { - next('}'); - return object; // empty object - } - while (ch) { - key = string(); - white(); - next(':'); - if (Object.hasOwnProperty.call(object, key)) { - error('Duplicate key "' + key + '"'); - } - object[key] = value(); - white(); - if (ch === '}') { - next('}'); - return object; - } - next(','); - white(); - } - } - error("Bad object"); - }; - - value = function () { - -// Parse a JSON value. It could be an object, an array, a string, a number, -// or a word. - + } else { + string += ch; + } + } + } + error("Bad string"); + }, + white = function () { + // Skip whitespace. + + while (ch && ch <= " ") { + next(); + } + }, + word = function () { + // true, false, or null. + + switch (ch) { + case "t": + next("t"); + next("r"); + next("u"); + next("e"); + return true; + case "f": + next("f"); + next("a"); + next("l"); + next("s"); + next("e"); + return false; + case "n": + next("n"); + next("u"); + next("l"); + next("l"); + return null; + } + error("Unexpected '" + ch + "'"); + }, + value, // Place holder for the value function. + array = function () { + // Parse an array value. + + var array = []; + + if (ch === "[") { + next("["); white(); - switch (ch) { - case '{': - return object(); - case '[': - return array(); - case '"': - return string(); - case '-': - return number(); - default: - return ch >= '0' && ch <= '9' - ? number() - : word(); + if (ch === "]") { + next("]"); + return array; // empty array } - }; - -// Return the json_parse function. It will have access to all of the above -// functions and variables. + while (ch) { + array.push(value()); + white(); + if (ch === "]") { + next("]"); + return array; + } + next(","); + white(); + } + } + error("Bad array"); + }, + object = function () { + // Parse an object value. - return function (source) { - var result; + var key, + object = {}; - text = source; - at = 0; - ch = ' '; - result = value(); + if (ch === "{") { + next("{"); white(); - if (ch) { - error("Syntax error"); + if (ch === "}") { + next("}"); + return object; // empty object } - - return result; + while (ch) { + key = string(); + white(); + next(":"); + if (Object.hasOwnProperty.call(object, key)) { + error('Duplicate key "' + key + '"'); + } + object[key] = value(); + white(); + if (ch === "}") { + next("}"); + return object; + } + next(","); + white(); + } + } + error("Bad object"); }; -}()); + + value = function () { + // Parse a JSON value. It could be an object, an array, a string, a number, + // or a word. + + white(); + switch (ch) { + case "{": + return object(); + case "[": + return array(); + case '"': + return string(); + case "-": + return number(); + default: + return ch >= "0" && ch <= "9" ? number() : word(); + } + }; + + // Return the json_parse function. It will have access to all of the above + // functions and variables. + + return function (source) { + var result; + + text = source; + at = 0; + ch = " "; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } + + return result; + }; +})()); diff --git a/lib/nodejs/lib/thrift/json_protocol.js b/lib/nodejs/lib/thrift/json_protocol.js index 7e2b7c90891..31dcb8196a7 100644 --- a/lib/nodejs/lib/thrift/json_protocol.js +++ b/lib/nodejs/lib/thrift/json_protocol.js @@ -17,15 +17,15 @@ * under the License. */ -var Int64 = require('node-int64'); -var Thrift = require('./thrift'); +var Int64 = require("node-int64"); +var Thrift = require("./thrift"); var Type = Thrift.Type; var util = require("util"); -var Int64Util = require('./int64_util'); -var json_parse = require('./json_parse'); +var Int64Util = require("./int64_util"); +var json_parse = require("./json_parse"); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); module.exports = TJSONProtocol; @@ -43,7 +43,7 @@ function TJSONProtocol(trans) { this.tstack = []; this.tpos = []; this.trans = trans; -}; +} /** * Thrift IDL type Id to string mapping. @@ -89,12 +89,12 @@ TJSONProtocol.RType.set = Type.SET; */ TJSONProtocol.Version = 1; -TJSONProtocol.prototype.flush = function() { +TJSONProtocol.prototype.flush = function () { this.writeToTransportIfStackIsFlushable(); return this.trans.flush(); }; -TJSONProtocol.prototype.writeToTransportIfStackIsFlushable = function() { +TJSONProtocol.prototype.writeToTransportIfStackIsFlushable = function () { if (this.tstack.length === 1) { this.trans.write(this.tstack.pop()); } @@ -106,20 +106,29 @@ TJSONProtocol.prototype.writeToTransportIfStackIsFlushable = function() { * @param {Thrift.MessageType} messageType - The type of method call. * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift). */ -TJSONProtocol.prototype.writeMessageBegin = function(name, messageType, seqid) { - this.tstack.push([TJSONProtocol.Version, '"' + name + '"', messageType, seqid]); +TJSONProtocol.prototype.writeMessageBegin = function ( + name, + messageType, + seqid, +) { + this.tstack.push([ + TJSONProtocol.Version, + '"' + name + '"', + messageType, + seqid, + ]); }; /** * Serializes the end of a Thrift RPC message. */ -TJSONProtocol.prototype.writeMessageEnd = function() { +TJSONProtocol.prototype.writeMessageEnd = function () { var obj = this.tstack.pop(); this.wobj = this.tstack.pop(); this.wobj.push(obj); - this.wbuf = '[' + this.wobj.join(',') + ']'; + this.wbuf = "[" + this.wobj.join(",") + "]"; // we assume there is nothing more to come so we write this.trans.write(this.wbuf); @@ -129,7 +138,7 @@ TJSONProtocol.prototype.writeMessageEnd = function() { * Serializes the beginning of a struct. * @param {string} name - The name of the struct. */ -TJSONProtocol.prototype.writeStructBegin = function(name) { +TJSONProtocol.prototype.writeStructBegin = function (name) { this.tpos.push(this.tstack.length); this.tstack.push({}); }; @@ -137,22 +146,22 @@ TJSONProtocol.prototype.writeStructBegin = function(name) { /** * Serializes the end of a struct. */ -TJSONProtocol.prototype.writeStructEnd = function() { +TJSONProtocol.prototype.writeStructEnd = function () { var p = this.tpos.pop(); var struct = this.tstack[p]; - var str = '{'; + var str = "{"; var first = true; for (var key in struct) { if (first) { first = false; } else { - str += ','; + str += ","; } - str += key + ':' + struct[key]; + str += key + ":" + struct[key]; } - str += '}'; + str += "}"; this.tstack[p] = str; this.writeToTransportIfStackIsFlushable(); @@ -164,26 +173,27 @@ TJSONProtocol.prototype.writeStructEnd = function() { * @param {Thrift.Protocol.Type} fieldType - The data type of the field. * @param {number} fieldId - The field's unique identifier. */ -TJSONProtocol.prototype.writeFieldBegin = function(name, fieldType, fieldId) { +TJSONProtocol.prototype.writeFieldBegin = function (name, fieldType, fieldId) { this.tpos.push(this.tstack.length); - this.tstack.push({ 'fieldId': '"' + - fieldId + '"', 'fieldType': TJSONProtocol.Type[fieldType] + this.tstack.push({ + fieldId: '"' + fieldId + '"', + fieldType: TJSONProtocol.Type[fieldType], }); }; /** * Serializes the end of a field. */ -TJSONProtocol.prototype.writeFieldEnd = function() { +TJSONProtocol.prototype.writeFieldEnd = function () { var value = this.tstack.pop(); var fieldInfo = this.tstack.pop(); - if (':' + value === ":[object Object]") { - this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' + - fieldInfo.fieldType + ':' + JSON.stringify(value) + '}'; + if (":" + value === ":[object Object]") { + this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = + "{" + fieldInfo.fieldType + ":" + JSON.stringify(value) + "}"; } else { - this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' + - fieldInfo.fieldType + ':' + value + '}'; + this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = + "{" + fieldInfo.fieldType + ":" + value + "}"; } this.tpos.pop(); @@ -193,8 +203,7 @@ TJSONProtocol.prototype.writeFieldEnd = function() { /** * Serializes the end of the set of fields for a struct. */ -TJSONProtocol.prototype.writeFieldStop = function() { -}; +TJSONProtocol.prototype.writeFieldStop = function () {}; /** * Serializes the beginning of a map collection. @@ -202,16 +211,20 @@ TJSONProtocol.prototype.writeFieldStop = function() { * @param {Thrift.Type} valType - The data type of the value. * @param {number} [size] - The number of elements in the map (ignored). */ -TJSONProtocol.prototype.writeMapBegin = function(keyType, valType, size) { +TJSONProtocol.prototype.writeMapBegin = function (keyType, valType, size) { //size is invalid, we'll set it on end. this.tpos.push(this.tstack.length); - this.tstack.push([TJSONProtocol.Type[keyType], TJSONProtocol.Type[valType], 0]); + this.tstack.push([ + TJSONProtocol.Type[keyType], + TJSONProtocol.Type[valType], + 0, + ]); }; /** * Serializes the end of a map. */ -TJSONProtocol.prototype.writeMapEnd = function() { +TJSONProtocol.prototype.writeMapEnd = function () { var p = this.tpos.pop(); if (p == this.tstack.length) { @@ -219,14 +232,14 @@ TJSONProtocol.prototype.writeMapEnd = function() { } if ((this.tstack.length - p - 1) % 2 !== 0) { - this.tstack.push(''); + this.tstack.push(""); } var size = (this.tstack.length - p - 1) / 2; this.tstack[p][this.tstack[p].length - 1] = size; - var map = '}'; + var map = "}"; var first = true; while (this.tstack.length > p + 1) { var v = this.tstack.pop(); @@ -234,16 +247,18 @@ TJSONProtocol.prototype.writeMapEnd = function() { if (first) { first = false; } else { - map = ',' + map; + map = "," + map; } - if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings - map = k + ':' + v + map; + if (!isNaN(k)) { + k = '"' + k + '"'; + } //json "keys" need to be strings + map = k + ":" + v + map; } - map = '{' + map; + map = "{" + map; this.tstack[p].push(map); - this.tstack[p] = '[' + this.tstack[p].join(',') + ']'; + this.tstack[p] = "[" + this.tstack[p].join(",") + "]"; this.writeToTransportIfStackIsFlushable(); }; @@ -253,7 +268,7 @@ TJSONProtocol.prototype.writeMapEnd = function() { * @param {Thrift.Type} elemType - The data type of the elements. * @param {number} size - The number of elements in the list. */ -TJSONProtocol.prototype.writeListBegin = function(elemType, size) { +TJSONProtocol.prototype.writeListBegin = function (elemType, size) { this.tpos.push(this.tstack.length); this.tstack.push([TJSONProtocol.Type[elemType], size]); }; @@ -261,7 +276,7 @@ TJSONProtocol.prototype.writeListBegin = function(elemType, size) { /** * Serializes the end of a list. */ -TJSONProtocol.prototype.writeListEnd = function() { +TJSONProtocol.prototype.writeListEnd = function () { var p = this.tpos.pop(); while (this.tstack.length > p + 1) { @@ -270,7 +285,7 @@ TJSONProtocol.prototype.writeListEnd = function() { this.tstack[p].push(tmpVal); } - this.tstack[p] = '[' + this.tstack[p].join(',') + ']'; + this.tstack[p] = "[" + this.tstack[p].join(",") + "]"; this.writeToTransportIfStackIsFlushable(); }; @@ -280,15 +295,15 @@ TJSONProtocol.prototype.writeListEnd = function() { * @param {Thrift.Type} elemType - The data type of the elements. * @param {number} size - The number of elements in the list. */ -TJSONProtocol.prototype.writeSetBegin = function(elemType, size) { - this.tpos.push(this.tstack.length); - this.tstack.push([TJSONProtocol.Type[elemType], size]); +TJSONProtocol.prototype.writeSetBegin = function (elemType, size) { + this.tpos.push(this.tstack.length); + this.tstack.push([TJSONProtocol.Type[elemType], size]); }; /** * Serializes the end of a set. */ -TJSONProtocol.prototype.writeSetEnd = function() { +TJSONProtocol.prototype.writeSetEnd = function () { var p = this.tpos.pop(); while (this.tstack.length > p + 1) { @@ -297,33 +312,33 @@ TJSONProtocol.prototype.writeSetEnd = function() { this.tstack[p].push(tmpVal); } - this.tstack[p] = '[' + this.tstack[p].join(',') + ']'; + this.tstack[p] = "[" + this.tstack[p].join(",") + "]"; this.writeToTransportIfStackIsFlushable(); }; /** Serializes a boolean */ -TJSONProtocol.prototype.writeBool = function(bool) { +TJSONProtocol.prototype.writeBool = function (bool) { this.tstack.push(bool ? 1 : 0); }; /** Serializes a number */ -TJSONProtocol.prototype.writeByte = function(byte) { +TJSONProtocol.prototype.writeByte = function (byte) { this.tstack.push(byte); }; /** Serializes a number */ -TJSONProtocol.prototype.writeI16 = function(i16) { +TJSONProtocol.prototype.writeI16 = function (i16) { this.tstack.push(i16); }; /** Serializes a number */ -TJSONProtocol.prototype.writeI32 = function(i32) { +TJSONProtocol.prototype.writeI32 = function (i32) { this.tstack.push(i32); }; /** Serializes a number */ -TJSONProtocol.prototype.writeI64 = function(i64) { +TJSONProtocol.prototype.writeI64 = function (i64) { if (i64 instanceof Int64) { this.tstack.push(Int64Util.toDecimalString(i64)); } else { @@ -332,69 +347,81 @@ TJSONProtocol.prototype.writeI64 = function(i64) { }; /** Serializes a number */ -TJSONProtocol.prototype.writeDouble = function(dub) { +TJSONProtocol.prototype.writeDouble = function (dub) { this.tstack.push(dub); }; /** Serializes a string */ -TJSONProtocol.prototype.writeString = function(arg) { +TJSONProtocol.prototype.writeString = function (arg) { // We do not encode uri components for wire transfer: if (arg === null) { - this.tstack.push(null); + this.tstack.push(null); } else { - if (typeof arg === 'string') { - var str = arg; - } else if (arg instanceof Buffer) { - var str = arg.toString('utf8'); - } else { - throw new Error('writeString called without a string/Buffer argument: ' + arg); - } + if (typeof arg === "string") { + var str = arg; + } else if (arg instanceof Buffer) { + var str = arg.toString("utf8"); + } else { + throw new Error( + "writeString called without a string/Buffer argument: " + arg, + ); + } - // concat may be slower than building a byte buffer - var escapedString = ''; - for (var i = 0; i < str.length; i++) { - var ch = str.charAt(i); // a single double quote: " - if (ch === '\"') { - escapedString += '\\\"'; // write out as: \" - } else if (ch === '\\') { // a single backslash: \ - escapedString += '\\\\'; // write out as: \\ - /* Currently escaped forward slashes break TJSONProtocol. - * As it stands, we can simply pass forward slashes into - * our strings across the wire without being escaped. - * I think this is the protocol's bug, not thrift.js - * } else if(ch === '/') { // a single forward slash: / - * escapedString += '\\/'; // write out as \/ - * } - */ - } else if (ch === '\b') { // a single backspace: invisible - escapedString += '\\b'; // write out as: \b" - } else if (ch === '\f') { // a single formfeed: invisible - escapedString += '\\f'; // write out as: \f" - } else if (ch === '\n') { // a single newline: invisible - escapedString += '\\n'; // write out as: \n" - } else if (ch === '\r') { // a single return: invisible - escapedString += '\\r'; // write out as: \r" - } else if (ch === '\t') { // a single tab: invisible - escapedString += '\\t'; // write out as: \t" - } else { - escapedString += ch; // Else it need not be escaped - } + // concat may be slower than building a byte buffer + var escapedString = ""; + for (var i = 0; i < str.length; i++) { + var ch = str.charAt(i); // a single double quote: " + if (ch === '\"') { + escapedString += '\\\"'; // write out as: \" + } else if (ch === "\\") { + // a single backslash: \ + escapedString += "\\\\"; // write out as: \\ + /* Currently escaped forward slashes break TJSONProtocol. + * As it stands, we can simply pass forward slashes into + * our strings across the wire without being escaped. + * I think this is the protocol's bug, not thrift.js + * } else if(ch === '/') { // a single forward slash: / + * escapedString += '\\/'; // write out as \/ + * } + */ + } else if (ch === "\b") { + // a single backspace: invisible + escapedString += "\\b"; // write out as: \b" + } else if (ch === "\f") { + // a single formfeed: invisible + escapedString += "\\f"; // write out as: \f" + } else if (ch === "\n") { + // a single newline: invisible + escapedString += "\\n"; // write out as: \n" + } else if (ch === "\r") { + // a single return: invisible + escapedString += "\\r"; // write out as: \r" + } else if (ch === "\t") { + // a single tab: invisible + escapedString += "\\t"; // write out as: \t" + } else { + escapedString += ch; // Else it need not be escaped } - this.tstack.push('"' + escapedString + '"'); + } + this.tstack.push('"' + escapedString + '"'); } }; /** Serializes a string */ -TJSONProtocol.prototype.writeBinary = function(arg) { - if (typeof arg === 'string') { - var buf = new Buffer(arg, 'binary'); - } else if (arg instanceof Buffer || - Object.prototype.toString.call(arg) == '[object Uint8Array]') { +TJSONProtocol.prototype.writeBinary = function (arg) { + if (typeof arg === "string") { + var buf = new Buffer(arg, "binary"); + } else if ( + arg instanceof Buffer || + Object.prototype.toString.call(arg) == "[object Uint8Array]" + ) { var buf = arg; } else { - throw new Error('writeBinary called without a string/Buffer argument: ' + arg); + throw new Error( + "writeBinary called without a string/Buffer argument: " + arg, + ); } - this.tstack.push('"' + buf.toString('base64') + '"'); + this.tstack.push('"' + buf.toString("base64") + '"'); }; /** @@ -408,7 +435,7 @@ TJSONProtocol.prototype.writeBinary = function(arg) { * Deserializes the beginning of a message. * @returns {AnonReadMessageBeginReturn} */ -TJSONProtocol.prototype.readMessageBegin = function() { +TJSONProtocol.prototype.readMessageBegin = function () { this.rstack = []; this.rpos = []; @@ -419,7 +446,8 @@ TJSONProtocol.prototype.readMessageBegin = function() { } var cursor = transBuf.readIndex; - if (transBuf.buf[cursor] !== 0x5B) { //[ + if (transBuf.buf[cursor] !== 0x5b) { + //[ throw new Error("Malformed JSON input, no opening bracket"); } @@ -432,22 +460,27 @@ TJSONProtocol.prototype.readMessageBegin = function() { var chr = transBuf.buf[cursor]; //we use hexa charcode here because data[i] returns an int and not a char if (inString) { - if (chr === 0x22) { //" + if (chr === 0x22) { + //" inString = false; - } else if (chr === 0x5C) { //\ + } else if (chr === 0x5c) { + //\ //escaped character, skip cursor += 1; } } else { - if (chr === 0x5B) { //[ + if (chr === 0x5b) { + //[ openBracketCount += 1; - } else if (chr === 0x5D) { //] + } else if (chr === 0x5d) { + //] openBracketCount -= 1; if (openBracketCount === 0) { //end of json message detected break; } - } else if (chr === 0x22) { //" + } else if (chr === 0x22) { + //" inString = true; } } @@ -459,13 +492,15 @@ TJSONProtocol.prototype.readMessageBegin = function() { } //Reconstitute the JSON object and conume the necessary bytes - this.robj = json_parse(transBuf.buf.slice(transBuf.readIndex, cursor+1).toString()); + this.robj = json_parse( + transBuf.buf.slice(transBuf.readIndex, cursor + 1).toString(), + ); this.trans.consume(cursor + 1 - transBuf.readIndex); //Verify the protocol version var version = this.robj.shift(); if (version != TJSONProtocol.Version) { - throw new Error('Wrong thrift protocol version: ' + version); + throw new Error("Wrong thrift protocol version: " + version); } //Objectify the thrift message {name/type/sequence-number} for return @@ -479,17 +514,16 @@ TJSONProtocol.prototype.readMessageBegin = function() { }; /** Deserializes the end of a message. */ -TJSONProtocol.prototype.readMessageEnd = function() { -}; +TJSONProtocol.prototype.readMessageEnd = function () {}; /** * Deserializes the beginning of a struct. * @param {string} [name] - The name of the struct (ignored) * @returns {object} - An object with an empty string fname property */ -TJSONProtocol.prototype.readStructBegin = function() { +TJSONProtocol.prototype.readStructBegin = function () { var r = {}; - r.fname = ''; + r.fname = ""; //incase this is an array of structs if (this.rstack[this.rstack.length - 1] instanceof Array) { @@ -500,7 +534,7 @@ TJSONProtocol.prototype.readStructBegin = function() { }; /** Deserializes the end of a struct. */ -TJSONProtocol.prototype.readStructEnd = function() { +TJSONProtocol.prototype.readStructEnd = function () { this.rstack.pop(); }; @@ -515,14 +549,14 @@ TJSONProtocol.prototype.readStructEnd = function() { * Deserializes the beginning of a field. * @returns {AnonReadFieldBeginReturn} */ -TJSONProtocol.prototype.readFieldBegin = function() { +TJSONProtocol.prototype.readFieldBegin = function () { var r = {}; var fid = -1; var ftype = Type.STOP; //get a fieldId - for (var f in (this.rstack[this.rstack.length - 1])) { + for (var f in this.rstack[this.rstack.length - 1]) { if (f === null) { continue; } @@ -543,17 +577,18 @@ TJSONProtocol.prototype.readFieldBegin = function() { if (fid != -1) { //should only be 1 of these but this is the only //way to match a key - for (var i in (this.rstack[this.rstack.length - 1])) { + for (var i in this.rstack[this.rstack.length - 1]) { if (TJSONProtocol.RType[i] === null) { continue; } ftype = TJSONProtocol.RType[i]; - this.rstack[this.rstack.length - 1] = this.rstack[this.rstack.length - 1][i]; + this.rstack[this.rstack.length - 1] = + this.rstack[this.rstack.length - 1][i]; } } - r.fname = ''; + r.fname = ""; r.ftype = ftype; r.fid = fid; @@ -561,7 +596,7 @@ TJSONProtocol.prototype.readFieldBegin = function() { }; /** Deserializes the end of a field. */ -TJSONProtocol.prototype.readFieldEnd = function() { +TJSONProtocol.prototype.readFieldEnd = function () { var pos = this.rpos.pop(); //get back to the right place in the stack @@ -581,7 +616,7 @@ TJSONProtocol.prototype.readFieldEnd = function() { * Deserializes the beginning of a map. * @returns {AnonReadMapBeginReturn} */ -TJSONProtocol.prototype.readMapBegin = function() { +TJSONProtocol.prototype.readMapBegin = function () { var map = this.rstack.pop(); var first = map.shift(); if (first instanceof Array) { @@ -595,7 +630,6 @@ TJSONProtocol.prototype.readMapBegin = function() { r.vtype = TJSONProtocol.RType[map.shift()]; r.size = map.shift(); - this.rpos.push(this.rstack.length); this.rstack.push(map.shift()); @@ -603,7 +637,7 @@ TJSONProtocol.prototype.readMapBegin = function() { }; /** Deserializes the end of a map. */ -TJSONProtocol.prototype.readMapEnd = function() { +TJSONProtocol.prototype.readMapEnd = function () { this.readFieldEnd(); }; @@ -617,7 +651,7 @@ TJSONProtocol.prototype.readMapEnd = function() { * Deserializes the beginning of a list. * @returns {AnonReadColBeginReturn} */ -TJSONProtocol.prototype.readListBegin = function() { +TJSONProtocol.prototype.readListBegin = function () { var list = this.rstack[this.rstack.length - 1]; var r = {}; @@ -631,7 +665,7 @@ TJSONProtocol.prototype.readListBegin = function() { }; /** Deserializes the end of a list. */ -TJSONProtocol.prototype.readListEnd = function() { +TJSONProtocol.prototype.readListEnd = function () { var pos = this.rpos.pop() - 2; var st = this.rstack; st.pop(); @@ -644,33 +678,33 @@ TJSONProtocol.prototype.readListEnd = function() { * Deserializes the beginning of a set. * @returns {AnonReadColBeginReturn} */ -TJSONProtocol.prototype.readSetBegin = function() { +TJSONProtocol.prototype.readSetBegin = function () { return this.readListBegin(); }; /** Deserializes the end of a set. */ -TJSONProtocol.prototype.readSetEnd = function() { +TJSONProtocol.prototype.readSetEnd = function () { return this.readListEnd(); }; -TJSONProtocol.prototype.readBool = function() { - return this.readValue() == '1'; +TJSONProtocol.prototype.readBool = function () { + return this.readValue() == "1"; }; -TJSONProtocol.prototype.readByte = function() { +TJSONProtocol.prototype.readByte = function () { return this.readI32(); }; -TJSONProtocol.prototype.readI16 = function() { +TJSONProtocol.prototype.readI16 = function () { return this.readI32(); }; -TJSONProtocol.prototype.readI32 = function(f) { +TJSONProtocol.prototype.readI32 = function (f) { return +this.readValue(); -} +}; /** Returns the next value found in the protocol buffer */ -TJSONProtocol.prototype.readValue = function(f) { +TJSONProtocol.prototype.readValue = function (f) { if (f === undefined) { f = this.rstack[this.rstack.length - 1]; } @@ -702,9 +736,9 @@ TJSONProtocol.prototype.readValue = function(f) { return r.value; }; -TJSONProtocol.prototype.readI64 = function() { - var n = this.readValue() - if (typeof n === 'string') { +TJSONProtocol.prototype.readI64 = function () { + var n = this.readValue(); + if (typeof n === "string") { // Assuming no one is sending in 1.11111e+33 format return Int64Util.fromDecimalString(n); } else { @@ -712,15 +746,15 @@ TJSONProtocol.prototype.readI64 = function() { } }; -TJSONProtocol.prototype.readDouble = function() { +TJSONProtocol.prototype.readDouble = function () { return this.readI32(); }; -TJSONProtocol.prototype.readBinary = function() { - return new Buffer(this.readValue(), 'base64'); +TJSONProtocol.prototype.readBinary = function () { + return new Buffer(this.readValue(), "base64"); }; -TJSONProtocol.prototype.readString = function() { +TJSONProtocol.prototype.readString = function () { return this.readValue(); }; @@ -729,15 +763,15 @@ TJSONProtocol.prototype.readString = function() { * @readonly * @returns {Thrift.Transport} The underlying transport. */ -TJSONProtocol.prototype.getTransport = function() { +TJSONProtocol.prototype.getTransport = function () { return this.trans; }; /** * Method to arbitrarily skip over data */ -TJSONProtocol.prototype.skip = function(type) { - switch (type) { +TJSONProtocol.prototype.skip = function (type) { + switch (type) { case Type.BOOL: this.readBool(); break; @@ -794,6 +828,6 @@ TJSONProtocol.prototype.skip = function(type) { this.readListEnd(); break; default: - throw new Error("Invalid type: " + type); + throw new Error("Invalid type: " + type); } }; diff --git a/lib/nodejs/lib/thrift/log.js b/lib/nodejs/lib/thrift/log.js index 053e813618e..82d8a222cd7 100644 --- a/lib/nodejs/lib/thrift/log.js +++ b/lib/nodejs/lib/thrift/log.js @@ -17,17 +17,17 @@ * under the License. */ -var util = require('util'); +var util = require("util"); var disabled = function () {}; var logFunc = console.log; -var logLevel = 'error'; // default level +var logLevel = "error"; // default level function factory(level) { return function () { // better use spread syntax, but due to compatibility, // use legacy method here. - var args = ['thrift: [' + level + '] '].concat(Array.from(arguments)); + var args = ["thrift: [" + level + "] "].concat(Array.from(arguments)); return logFunc(util.format.apply(null, args)); }; } @@ -42,22 +42,22 @@ exports.setLogFunc = function (func) { logFunc = func; }; -var setLogLevel = exports.setLogLevel = function (level) { +var setLogLevel = (exports.setLogLevel = function (level) { trace = debug = error = warning = info = disabled; logLevel = level; switch (logLevel) { - case 'trace': - trace = factory('TRACE'); - case 'debug': - debug = factory('DEBUG'); - case 'error': - error = factory('ERROR'); - case 'warning': - warning = factory('WARN'); - case 'info': - info = factory('INFO'); + case "trace": + trace = factory("TRACE"); + case "debug": + debug = factory("DEBUG"); + case "error": + error = factory("ERROR"); + case "warning": + warning = factory("WARN"); + case "info": + info = factory("INFO"); } -}; +}); // set default setLogLevel(logLevel); diff --git a/lib/nodejs/lib/thrift/multiplexed_processor.js b/lib/nodejs/lib/thrift/multiplexed_processor.js index 67b62f7a29d..864d66d3257 100644 --- a/lib/nodejs/lib/thrift/multiplexed_processor.js +++ b/lib/nodejs/lib/thrift/multiplexed_processor.js @@ -16,31 +16,38 @@ * specific language governing permissions and limitations * under the License. */ -var Thrift = require('./thrift'); +var Thrift = require("./thrift"); exports.MultiplexedProcessor = MultiplexedProcessor; function MultiplexedProcessor(stream, options) { this.services = {}; -}; +} -MultiplexedProcessor.prototype.registerProcessor = function(name, handler) { +MultiplexedProcessor.prototype.registerProcessor = function (name, handler) { this.services[name] = handler; }; -MultiplexedProcessor.prototype.process = function(inp, out) { +MultiplexedProcessor.prototype.process = function (inp, out) { var begin = inp.readMessageBegin(); - if (begin.mtype != Thrift.MessageType.CALL && begin.mtype != Thrift.MessageType.ONEWAY) { - throw new Thrift.TException('TMultiplexedProcessor: Unexpected message type'); + if ( + begin.mtype != Thrift.MessageType.CALL && + begin.mtype != Thrift.MessageType.ONEWAY + ) { + throw new Thrift.TException( + "TMultiplexedProcessor: Unexpected message type", + ); } - var p = begin.fname.split(':'); + var p = begin.fname.split(":"); var sname = p[0]; var fname = p[1]; - if (! (sname in this.services)) { - throw new Thrift.TException('TMultiplexedProcessor: Unknown service: ' + sname); + if (!(sname in this.services)) { + throw new Thrift.TException( + "TMultiplexedProcessor: Unknown service: " + sname, + ); } //construct a proxy object which stubs the readMessageBegin @@ -51,11 +58,11 @@ MultiplexedProcessor.prototype.process = function(inp, out) { inpProxy[attr] = inp[attr]; } - inpProxy.readMessageBegin = function() { + inpProxy.readMessageBegin = function () { return { fname: fname, mtype: begin.mtype, - rseqid: begin.rseqid + rseqid: begin.rseqid, }; }; diff --git a/lib/nodejs/lib/thrift/multiplexed_protocol.js b/lib/nodejs/lib/thrift/multiplexed_protocol.js index d078aa2266f..1d2df96341b 100644 --- a/lib/nodejs/lib/thrift/multiplexed_protocol.js +++ b/lib/nodejs/lib/thrift/multiplexed_protocol.js @@ -16,55 +16,69 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); -var Thrift = require('./thrift'); +var util = require("util"); +var Thrift = require("./thrift"); exports.Multiplexer = Multiplexer; function Wrapper(serviceName, protocol, connection) { - function MultiplexProtocol(trans, strictRead, strictWrite) { protocol.call(this, trans, strictRead, strictWrite); - }; + } util.inherits(MultiplexProtocol, protocol); - MultiplexProtocol.prototype.writeMessageBegin = function(name, type, seqid) { + MultiplexProtocol.prototype.writeMessageBegin = function (name, type, seqid) { if (type == Thrift.MessageType.CALL || type == Thrift.MessageType.ONEWAY) { connection.seqId2Service[seqid] = serviceName; - MultiplexProtocol.super_.prototype.writeMessageBegin.call(this, - serviceName + ":" + name, - type, - seqid); + MultiplexProtocol.super_.prototype.writeMessageBegin.call( + this, + serviceName + ":" + name, + type, + seqid, + ); } else { - MultiplexProtocol.super_.prototype.writeMessageBegin.call(this, name, type, seqid); + MultiplexProtocol.super_.prototype.writeMessageBegin.call( + this, + name, + type, + seqid, + ); } }; return MultiplexProtocol; -}; +} function Multiplexer() { this.seqid = 0; -}; +} -Multiplexer.prototype.createClient = function(serviceName, ServiceClient, connection) { +Multiplexer.prototype.createClient = function ( + serviceName, + ServiceClient, + connection, +) { if (ServiceClient.Client) { ServiceClient = ServiceClient.Client; } - var writeCb = function(buf, seqid) { - connection.write(buf,seqid); + var writeCb = function (buf, seqid) { + connection.write(buf, seqid); }; var transport = new connection.transport(undefined, writeCb); - var protocolWrapper = new Wrapper(serviceName, connection.protocol, connection); + var protocolWrapper = new Wrapper( + serviceName, + connection.protocol, + connection, + ); var client = new ServiceClient(transport, protocolWrapper); var self = this; - client.new_seqid = function() { + client.new_seqid = function () { self.seqid += 1; return self.seqid; }; - if (typeof connection.client !== 'object') { + if (typeof connection.client !== "object") { connection.client = {}; } connection.client[serviceName] = client; diff --git a/lib/nodejs/lib/thrift/ohos_connection.js b/lib/nodejs/lib/thrift/ohos_connection.js index 95bf122790a..34afaae1858 100644 --- a/lib/nodejs/lib/thrift/ohos_connection.js +++ b/lib/nodejs/lib/thrift/ohos_connection.js @@ -16,15 +16,15 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); -var EventEmitter = require('events').EventEmitter; -var thrift = require('./thrift'); +var util = require("util"); +var EventEmitter = require("events").EventEmitter; +var thrift = require("./thrift"); -var TBufferedTransport = require('./buffered_transport'); -var TBinaryProtocol = require('./binary_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var TBufferedTransport = require("./buffered_transport"); +var TBinaryProtocol = require("./binary_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); -var createClient = require('./create_client'); +var createClient = require("./create_client"); /** * @class @@ -69,7 +69,7 @@ var createClient = require('./create_client'); * semantics implemented over the OpenHarmonyOS http.request() method. * @see {@link createOhosConnection} */ -var OhosConnection = exports.OhosConnection = function(options) { +var OhosConnection = (exports.OhosConnection = function (options) { //Initialize the emitter base object EventEmitter.call(this); @@ -78,12 +78,12 @@ var OhosConnection = exports.OhosConnection = function(options) { this.options = options || {}; this.host = this.options.host; this.port = this.options.port; - this.path = this.options.path || '/'; + this.path = this.options.path || "/"; //OpenHarmonyOS needs URL for initiating an HTTP request. this.url = this.port === 80 - ? this.host.replace(/\/$/, '') + this.path - : this.host.replace(/\/$/, '') + ':' + this.port + this.path; + ? this.host.replace(/\/$/, "") + this.path + : this.host.replace(/\/$/, "") + ":" + this.port + this.path; this.transport = this.options.transport || TBufferedTransport; this.protocol = this.options.protocol || TBinaryProtocol; //Inherit method from OpenHarmonyOS HTTP module @@ -91,17 +91,17 @@ var OhosConnection = exports.OhosConnection = function(options) { //Prepare HTTP request options this.requestOptions = { - method: 'POST', + method: "POST", header: this.options.header || {}, readTimeout: this.options.readTimeout || 60000, - connectTimeout: this.options.connectTimeout || 60000 + connectTimeout: this.options.connectTimeout || 60000, }; for (var attrname in this.options.requestOptions) { this.requestOptions[attrname] = this.options.requestOptions[attrname]; } /*jshint -W069 */ - if (!this.requestOptions.header['Connection']) { - this.requestOptions.header['Connection'] = 'keep-alive'; + if (!this.requestOptions.header["Connection"]) { + this.requestOptions.header["Connection"] = "keep-alive"; } /*jshint +W069 */ @@ -134,60 +134,61 @@ var OhosConnection = exports.OhosConnection = function(options) { delete self.seqId2Service[header.rseqid]; } /*jshint -W083 */ - client._reqs[dummy_seqid] = function(err, success){ + client._reqs[dummy_seqid] = function (err, success) { transport_with_data.commitPosition(); var clientCallback = client._reqs[header.rseqid]; delete client._reqs[header.rseqid]; if (clientCallback) { - process.nextTick(function() { + process.nextTick(function () { clientCallback(err, success); }); } }; /*jshint +W083 */ - if(client['recv_' + header.fname]) { - client['recv_' + header.fname](proto, header.mtype, dummy_seqid); + if (client["recv_" + header.fname]) { + client["recv_" + header.fname](proto, header.mtype, dummy_seqid); } else { delete client._reqs[dummy_seqid]; - self.emit("error", - new thrift.TApplicationException( - thrift.TApplicationExceptionType.WRONG_METHOD_NAME, - "Received a response to an unknown RPC function")); + self.emit( + "error", + new thrift.TApplicationException( + thrift.TApplicationExceptionType.WRONG_METHOD_NAME, + "Received a response to an unknown RPC function", + ), + ); } } - } - catch (e) { + } catch (e) { if (e instanceof InputBufferUnderrunError) { transport_with_data.rollbackPosition(); } else { - self.emit('error', e); + self.emit("error", e); } } } - //Response handler ////////////////////////////////////////////////// - this.responseCallback = function(error, response) { + this.responseCallback = function (error, response) { //Response will be a struct like: // https://developer.harmonyos.com/en/docs/documentation/doc-references/js-apis-net-http-0000001168304341#section15920192914312 var data = []; var dataLen = 0; if (error) { - self.emit('error', error); + self.emit("error", error); return; } if (!response || response.responseCode !== 200) { - self.emit('error', new THTTPException(response)); + self.emit("error", new THTTPException(response)); } // With OpenHarmonyOS running in a Browser (e.g. Browserify), chunk // will be a string or an ArrayBuffer. if ( - typeof response.result == 'string' || - Object.prototype.toString.call(response.result) == '[object Uint8Array]' + typeof response.result == "string" || + Object.prototype.toString.call(response.result) == "[object Uint8Array]" ) { // Wrap ArrayBuffer/string in a Buffer so data[i].copy will work data.push(Buffer.from(response.result)); @@ -211,7 +212,7 @@ var OhosConnection = exports.OhosConnection = function(options) { * @event {error} the "error" event is raised upon request failure passing the * Node.js error object to the listener. */ - this.write = function(data) { + this.write = function (data) { //To initiate multiple HTTP requests, we must create an HttpRequest object // for each HTTP request var http = self.createHttp(); @@ -223,7 +224,7 @@ var OhosConnection = exports.OhosConnection = function(options) { opts.extraData = data.toString(); http.request(self.url, opts, self.responseCallback); }; -}; +}); util.inherits(OhosConnection, EventEmitter); /** @@ -236,7 +237,7 @@ util.inherits(OhosConnection, EventEmitter); * @returns {OhosConnection} The connection object. * @see {@link ConnectOptions} */ -exports.createOhosConnection = function(createHttp, host, port, options) { +exports.createOhosConnection = function (createHttp, host, port, options) { options.createHttp = createHttp; options.host = host; options.port = port || 80; @@ -256,6 +257,6 @@ function THTTPException(response) { this.response = response; this.type = thrift.TApplicationExceptionType.PROTOCOL_ERROR; this.message = - 'Received a response with a bad HTTP status code: ' + response.responseCode; + "Received a response with a bad HTTP status code: " + response.responseCode; } util.inherits(THTTPException, thrift.TApplicationException); diff --git a/lib/nodejs/lib/thrift/protocol.js b/lib/nodejs/lib/thrift/protocol.js index a70ebe2872d..6eb88da061b 100644 --- a/lib/nodejs/lib/thrift/protocol.js +++ b/lib/nodejs/lib/thrift/protocol.js @@ -17,6 +17,6 @@ * under the License. */ -module.exports.TBinaryProtocol = require('./binary_protocol'); -module.exports.TCompactProtocol = require('./compact_protocol'); -module.exports.TJSONProtocol = require('./json_protocol'); +module.exports.TBinaryProtocol = require("./binary_protocol"); +module.exports.TCompactProtocol = require("./compact_protocol"); +module.exports.TJSONProtocol = require("./json_protocol"); diff --git a/lib/nodejs/lib/thrift/server.js b/lib/nodejs/lib/thrift/server.js index 16b74eaafc4..80a369fd194 100644 --- a/lib/nodejs/lib/thrift/server.js +++ b/lib/nodejs/lib/thrift/server.js @@ -17,14 +17,14 @@ * under the License. */ -var constants = require('constants'); -var net = require('net'); -var tls = require('tls'); +var constants = require("constants"); +var net = require("net"); +var tls = require("tls"); -var TBufferedTransport = require('./buffered_transport'); -var TBinaryProtocol = require('./binary_protocol'); -var THeaderProtocol = require('./header_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var TBufferedTransport = require("./buffered_transport"); +var TBinaryProtocol = require("./binary_protocol"); +var THeaderProtocol = require("./header_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); /** * Create a Thrift server which can serve one or multiple services. @@ -33,75 +33,82 @@ var InputBufferUnderrunError = require('./input_buffer_underrun_error'); * @param {ServerOptions} options - Optional additional server configuration. * @returns {object} - The Apache Thrift Multiplex Server. */ -exports.createMultiplexServer = function(processor, options) { - var transport = (options && options.transport) ? options.transport : TBufferedTransport; - var protocol = (options && options.protocol) ? options.protocol : TBinaryProtocol; +exports.createMultiplexServer = function (processor, options) { + var transport = + options && options.transport ? options.transport : TBufferedTransport; + var protocol = + options && options.protocol ? options.protocol : TBinaryProtocol; function serverImpl(stream) { var self = this; - stream.on('error', function(err) { - self.emit('error', err); + stream.on("error", function (err) { + self.emit("error", err); }); - stream.on('data', transport.receiver(function(transportWithData) { - var input = new protocol(transportWithData); - var outputCb = function(buf) { - try { + stream.on( + "data", + transport.receiver(function (transportWithData) { + var input = new protocol(transportWithData); + var outputCb = function (buf) { + try { stream.write(buf); - } catch (err) { - self.emit('error', err); + } catch (err) { + self.emit("error", err); stream.end(); - } - }; + } + }; - var output = new protocol(new transport(undefined, outputCb)); - // Read and write need to be performed on the same transport - // for THeaderProtocol because we should only respond with - // headers if the request contains headers - if (protocol === THeaderProtocol) { - output = input; - output.trans.onFlush = outputCb; - } - - try { - do { - processor.process(input, output); - transportWithData.commitPosition(); - } while (true); - } catch (err) { - if (err instanceof InputBufferUnderrunError) { - //The last data in the buffer was not a complete message, wait for the rest - transportWithData.rollbackPosition(); - } - else if (err.message === "Invalid type: undefined") { - //No more data in the buffer - //This trap is a bit hackish - //The next step to improve the node behavior here is to have - // the compiler generated process method throw a more explicit - // error when the network buffer is empty (regardles of the - // protocol/transport stack in use) and replace this heuristic. - // Also transports should probably not force upper layers to - // manage their buffer positions (i.e. rollbackPosition() and - // commitPosition() should be eliminated in lieu of a transport - // encapsulated buffer management strategy.) - transportWithData.rollbackPosition(); + var output = new protocol(new transport(undefined, outputCb)); + // Read and write need to be performed on the same transport + // for THeaderProtocol because we should only respond with + // headers if the request contains headers + if (protocol === THeaderProtocol) { + output = input; + output.trans.onFlush = outputCb; } - else { - //Unexpected error - self.emit('error', err); - stream.end(); + + try { + do { + processor.process(input, output); + transportWithData.commitPosition(); + } while (true); + } catch (err) { + if (err instanceof InputBufferUnderrunError) { + //The last data in the buffer was not a complete message, wait for the rest + transportWithData.rollbackPosition(); + } else if (err.message === "Invalid type: undefined") { + //No more data in the buffer + //This trap is a bit hackish + //The next step to improve the node behavior here is to have + // the compiler generated process method throw a more explicit + // error when the network buffer is empty (regardles of the + // protocol/transport stack in use) and replace this heuristic. + // Also transports should probably not force upper layers to + // manage their buffer positions (i.e. rollbackPosition() and + // commitPosition() should be eliminated in lieu of a transport + // encapsulated buffer management strategy.) + transportWithData.rollbackPosition(); + } else { + //Unexpected error + self.emit("error", err); + stream.end(); + } } - } - })); + }), + ); - stream.on('end', function() { + stream.on("end", function () { stream.end(); }); } if (options && options.tls) { - if (!('secureProtocol' in options.tls) && !('secureOptions' in options.tls)) { + if ( + !("secureProtocol" in options.tls) && + !("secureOptions" in options.tls) + ) { options.tls.secureProtocol = "SSLv23_method"; - options.tls.secureOptions = constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3; + options.tls.secureOptions = + constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3; } return tls.createServer(options.tls, serverImpl); } else { @@ -115,7 +122,7 @@ exports.createMultiplexServer = function(processor, options) { * @param {ServerOptions} options - Optional additional server configuration. * @returns {object} - The Apache Thrift Multiplex Server. */ -exports.createServer = function(processor, handler, options) { +exports.createServer = function (processor, handler, options) { if (processor.Processor) { processor = processor.Processor; } diff --git a/lib/nodejs/lib/thrift/thrift.js b/lib/nodejs/lib/thrift/thrift.js index 3a693f6da58..741a493835d 100644 --- a/lib/nodejs/lib/thrift/thrift.js +++ b/lib/nodejs/lib/thrift/thrift.js @@ -16,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); +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,10 +55,10 @@ function TException(message) { this.name = this.constructor.name; this.message = message; -}; +} util.inherits(TException, Error); -var TApplicationExceptionType = exports.TApplicationExceptionType = { +var TApplicationExceptionType = (exports.TApplicationExceptionType = { UNKNOWN: 0, UNKNOWN_METHOD: 1, INVALID_MESSAGE_TYPE: 2, @@ -69,8 +69,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; @@ -83,73 +83,73 @@ function TApplicationException(type, message) { this.type = type || TApplicationExceptionType.UNKNOWN; this.name = this.constructor.name; this.message = message; -}; +} util.inherits(TApplicationException, TException); -TApplicationException.prototype[Symbol.for("read")] = TApplicationException.prototype.read = function(input) { - var ftype; - var ret = input.readStructBegin('TApplicationException'); +TApplicationException.prototype[Symbol.for("read")] = + TApplicationException.prototype.read = function (input) { + var ftype; + var ret = input.readStructBegin("TApplicationException"); - while(1){ + while (1) { ret = input.readFieldBegin(); - if(ret.ftype == Type.STOP) + if (ret.ftype == Type.STOP) break; + + switch (ret.fid) { + case 1: + if (ret.ftype == Type.STRING) { + ret = input.readString(); + this.message = ret; + } else { + ret = input.skip(ret.ftype); + } + break; + case 2: + if (ret.ftype == Type.I32) { + ret = input.readI32(); + this.type = ret; + } else { + ret = input.skip(ret.ftype); + } + break; + default: + ret = input.skip(ret.ftype); break; - - switch(ret.fid){ - case 1: - if( ret.ftype == Type.STRING ){ - ret = input.readString(); - this.message = ret; - } else { - ret = input.skip(ret.ftype); - } - break; - case 2: - if( ret.ftype == Type.I32 ){ - ret = input.readI32(); - this.type = ret; - } else { - ret = input.skip(ret.ftype); - } - break; - default: - ret = input.skip(ret.ftype); - break; } input.readFieldEnd(); - } - input.readStructEnd(); -}; + } + input.readStructEnd(); + }; -TApplicationException.prototype[Symbol.for("write")] = TApplicationException.prototype.write = function(output){ - output.writeStructBegin('TApplicationException'); +TApplicationException.prototype[Symbol.for("write")] = + TApplicationException.prototype.write = function (output) { + output.writeStructBegin("TApplicationException"); - if (this.message) { - output.writeFieldBegin('message', Type.STRING, 1); + if (this.message) { + output.writeFieldBegin("message", Type.STRING, 1); output.writeString(this.message); output.writeFieldEnd(); - } + } - if (this.code) { - output.writeFieldBegin('type', Type.I32, 2); + if (this.code) { + output.writeFieldBegin("type", Type.I32, 2); output.writeI32(this.code); output.writeFieldEnd(); - } + } - output.writeFieldStop(); - output.writeStructEnd(); -}; + output.writeFieldStop(); + output.writeStructEnd(); + }; -var TProtocolExceptionType = exports.TProtocolExceptionType = { +var TProtocolExceptionType = (exports.TProtocolExceptionType = { UNKNOWN: 0, INVALID_DATA: 1, NEGATIVE_SIZE: 2, SIZE_LIMIT: 3, BAD_VERSION: 4, NOT_IMPLEMENTED: 5, - DEPTH_LIMIT: 6 -}; - + DEPTH_LIMIT: 6, +}); exports.TProtocolException = TProtocolException; @@ -162,74 +162,74 @@ function TProtocolException(type, message) { this.name = this.constructor.name; this.type = type; this.message = message; -}; +} util.inherits(TProtocolException, Error); -exports.objectLength = function(obj) { +exports.objectLength = function (obj) { return Object.keys(obj).length; }; -exports.inherits = function(constructor, superConstructor) { +exports.inherits = function (constructor, superConstructor) { util.inherits(constructor, superConstructor); }; var copyList, copyMap; -copyList = function(lst, types) { - - if (!lst) {return lst; } +copyList = function (lst, types) { + if (!lst) { + return lst; + } var type; 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)); } } return result; }; -copyMap = function(obj, types){ - - if (!obj) {return obj; } +copyMap = function (obj, types) { + if (!obj) { + return obj; + } var type; if (types.shift === undefined) { type = types; - } - else { + } else { type = types[0]; } var Type = type; - var result = {}, val; - for(var prop in obj) { - if(obj.hasOwnProperty(prop)) { + var result = {}, + val; + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { val = obj[prop]; if (type === null) { result[prop] = val; - } - else if (type === copyMap || type === copyList) { + } else if (type === copyMap || type === copyList) { result[prop] = type(val, types.slice(1)); - } - else { + } else { result[prop] = new Type(val); } } diff --git a/lib/nodejs/lib/thrift/transport.js b/lib/nodejs/lib/thrift/transport.js index 59daa987d54..b3ba39495b7 100644 --- a/lib/nodejs/lib/thrift/transport.js +++ b/lib/nodejs/lib/thrift/transport.js @@ -17,6 +17,6 @@ * under the License. */ -module.exports.TBufferedTransport = require('./buffered_transport'); -module.exports.TFramedTransport = require('./framed_transport'); -module.exports.InputBufferUnderrunError = require('./input_buffer_underrun_error'); +module.exports.TBufferedTransport = require("./buffered_transport"); +module.exports.TFramedTransport = require("./framed_transport"); +module.exports.InputBufferUnderrunError = require("./input_buffer_underrun_error"); diff --git a/lib/nodejs/lib/thrift/web_server.js b/lib/nodejs/lib/thrift/web_server.js index a33f47aedb7..f49f654b116 100644 --- a/lib/nodejs/lib/thrift/web_server.js +++ b/lib/nodejs/lib/thrift/web_server.js @@ -16,19 +16,20 @@ * specific language governing permissions and limitations * under the License. */ -var http = require('http'); -var https = require('https'); +var http = require("http"); +var https = require("https"); var url = require("url"); var path = require("path"); var fs = require("fs"); var crypto = require("crypto"); -var log = require('./log'); +var log = require("./log"); -var MultiplexedProcessor = require('./multiplexed_processor').MultiplexedProcessor; +var MultiplexedProcessor = + require("./multiplexed_processor").MultiplexedProcessor; -var TBufferedTransport = require('./buffered_transport'); -var TBinaryProtocol = require('./binary_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var TBufferedTransport = require("./buffered_transport"); +var TBinaryProtocol = require("./binary_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); // WSFrame constructor and prototype ///////////////////////////////////////////////////////////////////// @@ -82,36 +83,43 @@ var wsFrame = { * @param {Boolean} binEncoding - True for binary encoding, false for text encoding * @returns {Buffer} - The WebSocket frame, ready to send */ - encode: function(data, mask, binEncoding) { - var frame = new Buffer(wsFrame.frameSizeFromData(data, mask)); - //Byte 0 - FIN & OPCODE - frame[0] = wsFrame.fin.FIN + - (binEncoding ? wsFrame.frameOpCodes.BIN : wsFrame.frameOpCodes.TEXT); - //Byte 1 or 1-3 or 1-9 - MASK FLAG & SIZE - var payloadOffset = 2; - if (data.length < 0x7E) { - frame[1] = data.length + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT); - } else if (data.length < 0xFFFF) { - frame[1] = 0x7E + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT); - frame.writeUInt16BE(data.length, 2, true); - payloadOffset = 4; - } else { - frame[1] = 0x7F + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT); - frame.writeUInt32BE(0, 2, true); - frame.writeUInt32BE(data.length, 6, true); - payloadOffset = 10; - } - //MASK - if (mask) { - mask.copy(frame, payloadOffset, 0, 4); - payloadOffset += 4; - } - //Payload - data.copy(frame, payloadOffset); - if (mask) { - wsFrame.applyMask(frame.slice(payloadOffset), frame.slice(payloadOffset-4,payloadOffset)); - } - return frame; + encode: function (data, mask, binEncoding) { + var frame = new Buffer(wsFrame.frameSizeFromData(data, mask)); + //Byte 0 - FIN & OPCODE + frame[0] = + wsFrame.fin.FIN + + (binEncoding ? wsFrame.frameOpCodes.BIN : wsFrame.frameOpCodes.TEXT); + //Byte 1 or 1-3 or 1-9 - MASK FLAG & SIZE + var payloadOffset = 2; + if (data.length < 0x7e) { + frame[1] = + data.length + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT); + } else if (data.length < 0xffff) { + frame[1] = + 0x7e + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT); + frame.writeUInt16BE(data.length, 2, true); + payloadOffset = 4; + } else { + frame[1] = + 0x7f + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT); + frame.writeUInt32BE(0, 2, true); + frame.writeUInt32BE(data.length, 6, true); + payloadOffset = 10; + } + //MASK + if (mask) { + mask.copy(frame, payloadOffset, 0, 4); + payloadOffset += 4; + } + //Payload + data.copy(frame, payloadOffset); + if (mask) { + wsFrame.applyMask( + frame.slice(payloadOffset), + frame.slice(payloadOffset - 4, payloadOffset), + ); + } + return frame; }, /** @@ -127,7 +135,7 @@ var wsFrame = { * @property {Boolean} FIN - True is the message is complete */ - /** Decodes a WebSocket frame + /** Decodes a WebSocket frame * * @param {Buffer} frame - The raw inbound frame, if this is a continuation * frame it must have a mask property with the mask. @@ -135,54 +143,55 @@ var wsFrame = { * * @see {@link WSDecodeResult} */ - decode: function(frame) { - var result = { - data: null, - mask: null, - binEncoding: false, - nextFrame: null, - FIN: true - }; - - //Byte 0 - FIN & OPCODE - if (wsFrame.fin.FIN != (frame[0] & wsFrame.fin.FIN)) { - result.FIN = false; - } - result.binEncoding = (wsFrame.frameOpCodes.BIN == (frame[0] & wsFrame.frameOpCodes.BIN)); - //Byte 1 or 1-3 or 1-9 - SIZE - var lenByte = (frame[1] & 0x0000007F); - var len = lenByte; - var dataOffset = 2; - if (lenByte == 0x7E) { - len = frame.readUInt16BE(2); - dataOffset = 4; - } else if (lenByte == 0x7F) { - len = frame.readUInt32BE(6); - dataOffset = 10; - } - //MASK - if (wsFrame.mask.TO_SERVER == (frame[1] & wsFrame.mask.TO_SERVER)) { - result.mask = new Buffer(4); - frame.copy(result.mask, 0, dataOffset, dataOffset + 4); - dataOffset += 4; - } - //Payload - result.data = new Buffer(len); - frame.copy(result.data, 0, dataOffset, dataOffset+len); - if (result.mask) { - wsFrame.applyMask(result.data, result.mask); - } - //Next Frame - if (frame.length > dataOffset+len) { - result.nextFrame = new Buffer(frame.length - (dataOffset+len)); - frame.copy(result.nextFrame, 0, dataOffset+len, frame.length); - } - //Don't forward control frames - if (frame[0] & wsFrame.frameOpCodes.FINCTRL) { - result.data = null; - } + decode: function (frame) { + var result = { + data: null, + mask: null, + binEncoding: false, + nextFrame: null, + FIN: true, + }; + + //Byte 0 - FIN & OPCODE + if (wsFrame.fin.FIN != (frame[0] & wsFrame.fin.FIN)) { + result.FIN = false; + } + result.binEncoding = + wsFrame.frameOpCodes.BIN == (frame[0] & wsFrame.frameOpCodes.BIN); + //Byte 1 or 1-3 or 1-9 - SIZE + var lenByte = frame[1] & 0x0000007f; + var len = lenByte; + var dataOffset = 2; + if (lenByte == 0x7e) { + len = frame.readUInt16BE(2); + dataOffset = 4; + } else if (lenByte == 0x7f) { + len = frame.readUInt32BE(6); + dataOffset = 10; + } + //MASK + if (wsFrame.mask.TO_SERVER == (frame[1] & wsFrame.mask.TO_SERVER)) { + result.mask = new Buffer(4); + frame.copy(result.mask, 0, dataOffset, dataOffset + 4); + dataOffset += 4; + } + //Payload + result.data = new Buffer(len); + frame.copy(result.data, 0, dataOffset, dataOffset + len); + if (result.mask) { + wsFrame.applyMask(result.data, result.mask); + } + //Next Frame + if (frame.length > dataOffset + len) { + result.nextFrame = new Buffer(frame.length - (dataOffset + len)); + frame.copy(result.nextFrame, 0, dataOffset + len, frame.length); + } + //Don't forward control frames + if (frame[0] & wsFrame.frameOpCodes.FINCTRL) { + result.data = null; + } - return result; + return result; }, /** Masks/Unmasks data @@ -190,12 +199,12 @@ var wsFrame = { * @param {Buffer} data - data to mask/unmask in place * @param {Buffer} mask - the mask */ - applyMask: function(data, mask){ + applyMask: function (data, mask) { //TODO: look into xoring words at a time var dataLen = data.length; var maskLen = mask.length; for (var i = 0; i < dataLen; i++) { - data[i] = data[i] ^ mask[i%maskLen]; + data[i] = data[i] ^ mask[i % maskLen]; } }, @@ -204,35 +213,34 @@ var wsFrame = { * @param {Buffer} data - data.length is the assumed payload size * @param {Boolean} mask - true if a mask will be sent (TO_SERVER) */ - frameSizeFromData: function(data, mask) { + frameSizeFromData: function (data, mask) { var headerSize = 10; - if (data.length < 0x7E) { + if (data.length < 0x7e) { headerSize = 2; - } else if (data.length < 0xFFFF) { + } else if (data.length < 0xffff) { headerSize = 4; } return headerSize + data.length + (mask ? 4 : 0); }, frameOpCodes: { - CONT: 0x00, - TEXT: 0x01, - BIN: 0x02, - CTRL: 0x80 + CONT: 0x00, + TEXT: 0x01, + BIN: 0x02, + CTRL: 0x80, }, mask: { TO_SERVER: 0x80, - TO_CLIENT: 0x00 + TO_CLIENT: 0x00, }, fin: { CONT: 0x00, - FIN: 0x80 - } + FIN: 0x80, + }, }; - // createWebServer constructor and options ///////////////////////////////////////////////////////////////////// @@ -272,20 +280,20 @@ var wsFrame = { * @param {ServerOptions} options - The server configuration. * @returns {object} - The Apache Thrift Web Server. */ -exports.createWebServer = function(options) { +exports.createWebServer = function (options) { var baseDir = options.files; var contentTypesByExtension = { - '.txt': 'text/plain', - '.html': 'text/html', - '.css': 'text/css', - '.xml': 'application/xml', - '.json': 'application/json', - '.js': 'application/javascript', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - '.gif': 'image/gif', - '.png': 'image/png', - '.svg': 'image/svg+xml' + ".txt": "text/plain", + ".html": "text/html", + ".css": "text/css", + ".xml": "application/xml", + ".json": "application/json", + ".js": "application/javascript", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".png": "image/png", + ".svg": "image/svg+xml", }; //Setup all of the services @@ -302,8 +310,9 @@ exports.createWebServer = function(options) { // IDL Compiler generated class housing the processor. Also, the options property // for a Processor has been called both cls and processor at different times. We // support any of the four possibilities here. - var processor = (svcObj.processor) ? (svcObj.processor.Processor || svcObj.processor) : - (svcObj.cls.Processor || svcObj.cls); + var processor = svcObj.processor + ? svcObj.processor.Processor || svcObj.processor + : svcObj.cls.Processor || svcObj.cls; //Processors can be supplied as constructed objects with handlers already embedded, // if a handler is provided we construct a new processor, if not we use the processor // object directly @@ -322,9 +331,18 @@ exports.createWebServer = function(options) { if (request.headers.origin && options.cors) { if (options.cors["*"] || options.cors[request.headers.origin]) { //Allow, origin allowed - response.setHeader("access-control-allow-origin", request.headers.origin); - response.setHeader("access-control-allow-methods", "GET, POST, OPTIONS"); - response.setHeader("access-control-allow-headers", "content-type, accept"); + response.setHeader( + "access-control-allow-origin", + request.headers.origin, + ); + response.setHeader( + "access-control-allow-methods", + "GET, POST, OPTIONS", + ); + response.setHeader( + "access-control-allow-headers", + "content-type, accept", + ); response.setHeader("access-control-max-age", "60"); return true; } else { @@ -336,19 +354,21 @@ exports.createWebServer = function(options) { return true; } - //Handle OPTIONS method (CORS) /////////////////////////////////////////////////// function processOptions(request, response) { if (VerifyCORSAndSetHeaders(request, response)) { - response.writeHead("204", "No Content", {"content-length": 0}); + response.writeHead("204", "No Content", { "content-length": 0 }); } else { - response.writeHead("403", "Origin " + request.headers.origin + " not allowed", {}); + response.writeHead( + "403", + "Origin " + request.headers.origin + " not allowed", + {}, + ); } response.end(); } - //Handle POST methods (TXHRTransport) /////////////////////////////////////////////////// function processPost(request, response) { @@ -363,39 +383,47 @@ exports.createWebServer = function(options) { //Verify CORS requirements if (!VerifyCORSAndSetHeaders(request, response)) { - response.writeHead("403", "Origin " + request.headers.origin + " not allowed", {}); + response.writeHead( + "403", + "Origin " + request.headers.origin + " not allowed", + {}, + ); response.end(); return; } //Process XHR payload - request.on('data', svc.transport.receiver(function(transportWithData) { - var input = new svc.protocol(transportWithData); - var output = new svc.protocol(new svc.transport(undefined, function(buf) { + request.on( + "data", + svc.transport.receiver(function (transportWithData) { + var input = new svc.protocol(transportWithData); + var output = new svc.protocol( + new svc.transport(undefined, function (buf) { + try { + response.writeHead(200); + response.end(buf); + } catch (err) { + response.writeHead(500); + response.end(); + } + }), + ); + try { - response.writeHead(200); - response.end(buf); + svc.processor.process(input, output); + transportWithData.commitPosition(); } catch (err) { - response.writeHead(500); - response.end(); - } - })); - - try { - svc.processor.process(input, output); - transportWithData.commitPosition(); - } catch (err) { - if (err instanceof InputBufferUnderrunError) { - transportWithData.rollbackPosition(); - } else { - response.writeHead(500); - response.end(); + if (err instanceof InputBufferUnderrunError) { + transportWithData.rollbackPosition(); + } else { + response.writeHead(500); + response.end(); + } } - } - })); + }), + ); } - //Handle GET methods (Static Page Server) /////////////////////////////////////////////////// function processGet(request, response) { @@ -408,7 +436,11 @@ exports.createWebServer = function(options) { //Verify CORS requirements if (!VerifyCORSAndSetHeaders(request, response)) { - response.writeHead("403", "Origin " + request.headers.origin + " not allowed", {}); + response.writeHead( + "403", + "Origin " + request.headers.origin + " not allowed", + {}, + ); response.end(); return; } @@ -424,18 +456,18 @@ exports.createWebServer = function(options) { return; } - fs.exists(filename, function(exists) { - if(!exists) { + fs.exists(filename, function (exists) { + if (!exists) { response.writeHead(404); response.end(); return; } if (fs.statSync(filename).isDirectory()) { - filename += '/index.html'; + filename += "/index.html"; } - fs.readFile(filename, "binary", function(err, file) { + fs.readFile(filename, "binary", function (err, file) { if (err) { response.writeHead(500); response.end(err + "\n"); @@ -456,30 +488,29 @@ exports.createWebServer = function(options) { }); } - //Handle WebSocket calls (TWebSocketTransport) /////////////////////////////////////////////////// function processWS(data, socket, svc, binEncoding) { - svc.transport.receiver(function(transportWithData) { + svc.transport.receiver(function (transportWithData) { var input = new svc.protocol(transportWithData); - var output = new svc.protocol(new svc.transport(undefined, function(buf) { - try { - var frame = wsFrame.encode(buf, null, binEncoding); - socket.write(frame); - } catch (err) { - //TODO: Add better error processing - } - })); + var output = new svc.protocol( + new svc.transport(undefined, function (buf) { + try { + var frame = wsFrame.encode(buf, null, binEncoding); + socket.write(frame); + } catch (err) { + //TODO: Add better error processing + } + }), + ); try { svc.processor.process(input, output); transportWithData.commitPosition(); - } - catch (err) { + } catch (err) { if (err instanceof InputBufferUnderrunError) { transportWithData.rollbackPosition(); - } - else { + } else { //TODO: Add better error processing } } @@ -498,69 +529,83 @@ exports.createWebServer = function(options) { // - GET static files, // - POST XHR Thrift services // - OPTIONS CORS requests - server.on('request', function(request, response) { - if (request.method === 'POST') { - processPost(request, response); - } else if (request.method === 'GET') { - processGet(request, response); - } else if (request.method === 'OPTIONS') { - processOptions(request, response); - } else { - response.writeHead(500); - response.end(); - } - }).on('upgrade', function(request, socket, head) { - //Lookup service - var svc; - try { - svc = services[Object.keys(services)[0]]; - } catch(e) { - socket.write("HTTP/1.1 403 No Apache Thrift Service available\r\n\r\n"); - return; - } - //Perform upgrade - var hash = crypto.createHash("sha1"); - hash.update(request.headers['sec-websocket-key'] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); - socket.write("HTTP/1.1 101 Switching Protocols\r\n" + - "Upgrade: websocket\r\n" + - "Connection: Upgrade\r\n" + - "Sec-WebSocket-Accept: " + hash.digest("base64") + "\r\n" + - "Sec-WebSocket-Origin: " + request.headers.origin + "\r\n" + - "Sec-WebSocket-Location: ws://" + request.headers.host + request.url + "\r\n" + - "\r\n"); - //Handle WebSocket traffic - var data = null; - socket.on('data', function(frame) { + server + .on("request", function (request, response) { + if (request.method === "POST") { + processPost(request, response); + } else if (request.method === "GET") { + processGet(request, response); + } else if (request.method === "OPTIONS") { + processOptions(request, response); + } else { + response.writeHead(500); + response.end(); + } + }) + .on("upgrade", function (request, socket, head) { + //Lookup service + var svc; try { - while (frame) { - var result = wsFrame.decode(frame); - //Prepend any existing decoded data - if (data) { - if (result.data) { - var newData = new Buffer(data.length + result.data.length); - data.copy(newData); - result.data.copy(newData, data.length); - result.data = newData; + svc = services[Object.keys(services)[0]]; + } catch (e) { + socket.write("HTTP/1.1 403 No Apache Thrift Service available\r\n\r\n"); + return; + } + //Perform upgrade + var hash = crypto.createHash("sha1"); + hash.update( + request.headers["sec-websocket-key"] + + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + ); + socket.write( + "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + + hash.digest("base64") + + "\r\n" + + "Sec-WebSocket-Origin: " + + request.headers.origin + + "\r\n" + + "Sec-WebSocket-Location: ws://" + + request.headers.host + + request.url + + "\r\n" + + "\r\n", + ); + //Handle WebSocket traffic + var data = null; + socket.on("data", function (frame) { + try { + while (frame) { + var result = wsFrame.decode(frame); + //Prepend any existing decoded data + if (data) { + if (result.data) { + var newData = new Buffer(data.length + result.data.length); + data.copy(newData); + result.data.copy(newData, data.length); + result.data = newData; + } else { + result.data = data; + } + data = null; + } + //If this completes a message process it + if (result.FIN) { + processWS(result.data, socket, svc, result.binEncoding); } else { - result.data = data; + data = result.data; } - data = null; + //Prepare next frame for decoding (if any) + frame = result.nextFrame; } - //If this completes a message process it - if (result.FIN) { - processWS(result.data, socket, svc, result.binEncoding); - } else { - data = result.data; - } - //Prepare next frame for decoding (if any) - frame = result.nextFrame; + } catch (e) { + log.error("TWebSocketTransport Exception: " + e); + socket.destroy(); } - } catch(e) { - log.error('TWebSocketTransport Exception: ' + e); - socket.destroy(); - } + }); }); - }); //Return the server return server; diff --git a/lib/nodejs/lib/thrift/ws_connection.js b/lib/nodejs/lib/thrift/ws_connection.js index 8ee8f6eca18..878a5724ff3 100644 --- a/lib/nodejs/lib/thrift/ws_connection.js +++ b/lib/nodejs/lib/thrift/ws_connection.js @@ -16,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); -var WebSocket = require('isomorphic-ws'); +var util = require("util"); +var WebSocket = require("isomorphic-ws"); var EventEmitter = require("events").EventEmitter; -var thrift = require('./thrift'); +var thrift = require("./thrift"); -var TBufferedTransport = require('./buffered_transport'); -var TJSONProtocol = require('./json_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var TBufferedTransport = require("./buffered_transport"); +var TJSONProtocol = require("./json_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); -var createClient = require('./create_client'); -var jsEnv = require('browser-or-node'); +var createClient = require("./create_client"); +var jsEnv = require("browser-or-node"); exports.WSConnection = WSConnection; /** @@ -95,38 +95,38 @@ function WSConnection(host, port, options) { this.wsOptions = { host: this.host, port: this.port || 80, - path: this.options.path || '/', - headers: this.options.headers || {} + path: this.options.path || "/", + headers: this.options.headers || {}, }; for (var attrname in this.options.wsOptions) { this.wsOptions[attrname] = this.options.wsOptions[attrname]; } -}; +} util.inherits(WSConnection, EventEmitter); -WSConnection.prototype.__reset = function() { +WSConnection.prototype.__reset = function () { this.socket = null; //The web socket this.send_pending = []; //Buffers/Callback pairs waiting to be sent }; -WSConnection.prototype.__onOpen = function() { +WSConnection.prototype.__onOpen = function () { this.emit("open"); if (this.send_pending.length > 0) { //If the user made calls before the connection was fully //open, send them now - this.send_pending.forEach(function(data) { + this.send_pending.forEach(function (data) { this.socket.send(data); }, this); this.send_pending = []; } }; -WSConnection.prototype.__onClose = function(evt) { +WSConnection.prototype.__onClose = function (evt) { this.emit("close"); this.__reset(); }; -WSConnection.prototype.__decodeCallback = function(transport_with_data) { +WSConnection.prototype.__decodeCallback = function (transport_with_data) { var proto = new this.protocol(transport_with_data); try { while (true) { @@ -151,7 +151,7 @@ WSConnection.prototype.__decodeCallback = function(transport_with_data) { delete this.seqId2Service[header.rseqid]; } /*jshint -W083 */ - client._reqs[dummy_seqid] = function(err, success) { + client._reqs[dummy_seqid] = function (err, success) { transport_with_data.commitPosition(); var clientCallback = client._reqs[header.rseqid]; delete client._reqs[header.rseqid]; @@ -160,14 +160,17 @@ WSConnection.prototype.__decodeCallback = function(transport_with_data) { } }; /*jshint +W083 */ - if (client['recv_' + header.fname]) { - client['recv_' + header.fname](proto, header.mtype, dummy_seqid); + if (client["recv_" + header.fname]) { + client["recv_" + header.fname](proto, header.mtype, dummy_seqid); } else { delete client._reqs[dummy_seqid]; - this.emit("error", + this.emit( + "error", new thrift.TApplicationException( thrift.TApplicationExceptionType.WRONG_METHOD_NAME, - "Received a response to an unknown RPC function")); + "Received a response to an unknown RPC function", + ), + ); } } } catch (e) { @@ -179,20 +182,19 @@ WSConnection.prototype.__decodeCallback = function(transport_with_data) { } }; -WSConnection.prototype.__onData = function(data) { +WSConnection.prototype.__onData = function (data) { if (Object.prototype.toString.call(data) === "[object ArrayBuffer]") { data = new Uint8Array(data); } var buf = new Buffer(data); this.transport.receiver(this.__decodeCallback.bind(this))(buf); - }; -WSConnection.prototype.__onMessage = function(evt) { +WSConnection.prototype.__onMessage = function (evt) { this.__onData(evt.data); }; -WSConnection.prototype.__onError = function(evt) { +WSConnection.prototype.__onError = function (evt) { this.emit("error", evt); this.socket.close(); }; @@ -202,14 +204,14 @@ WSConnection.prototype.__onError = function(evt) { * @readonly * @returns {boolean} */ -WSConnection.prototype.isOpen = function() { +WSConnection.prototype.isOpen = function () { return this.socket && this.socket.readyState === this.socket.OPEN; }; /** * Opens the transport connection */ -WSConnection.prototype.open = function() { +WSConnection.prototype.open = function () { //If OPEN/CONNECTING/CLOSING ignore additional opens if (this.socket && this.socket.readyState !== this.socket.CLOSED) { return; @@ -220,7 +222,7 @@ WSConnection.prototype.open = function() { } else { this.socket = new WebSocket(this.uri(), "", this.wsOptions); } - this.socket.binaryType = 'arraybuffer'; + this.socket.binaryType = "arraybuffer"; this.socket.onopen = this.__onOpen.bind(this); this.socket.onmessage = this.__onMessage.bind(this); this.socket.onerror = this.__onError.bind(this); @@ -230,7 +232,7 @@ WSConnection.prototype.open = function() { /** * Closes the transport connection */ -WSConnection.prototype.close = function() { +WSConnection.prototype.close = function () { this.socket.close(); }; @@ -238,19 +240,22 @@ WSConnection.prototype.close = function() { * Return URI for the connection * @returns {string} URI */ -WSConnection.prototype.uri = function() { - var schema = this.secure ? 'wss' : 'ws'; - var port = ''; - var path = this.path || '/'; +WSConnection.prototype.uri = function () { + var schema = this.secure ? "wss" : "ws"; + var port = ""; + var path = this.path || "/"; var host = this.host; // avoid port if default for schema - if (this.port && (('wss' === schema && this.port !== 443) || - ('ws' === schema && this.port !== 80))) { - port = ':' + this.port; + if ( + this.port && + (("wss" === schema && this.port !== 443) || + ("ws" === schema && this.port !== 80)) + ) { + port = ":" + this.port; } - return schema + '://' + host + port + path; + return schema + "://" + host + port + path; }; /** @@ -260,7 +265,7 @@ WSConnection.prototype.uri = function() { * @event {error} the "error" event is raised upon request failure passing the * Node.js error object to the listener. */ -WSConnection.prototype.write = function(data) { +WSConnection.prototype.write = function (data) { if (this.isOpen()) { //Send data and register a callback to invoke the client callback this.socket.send(data); @@ -279,7 +284,7 @@ WSConnection.prototype.write = function(data) { * @returns {WSConnection} The connection object. * @see {@link WSConnectOptions} */ -exports.createWSConnection = function(host, port, options) { +exports.createWSConnection = function (host, port, options) { return new WSConnection(host, port, options); }; diff --git a/lib/nodejs/lib/thrift/ws_transport.js b/lib/nodejs/lib/thrift/ws_transport.js index 4cf62b9f9bf..94b6d90221b 100644 --- a/lib/nodejs/lib/thrift/ws_transport.js +++ b/lib/nodejs/lib/thrift/ws_transport.js @@ -17,7 +17,7 @@ * under the License. */ -var log = require('./log'); +var log = require("./log"); module.exports = TWebSocketTransport; @@ -33,19 +33,18 @@ module.exports = TWebSocketTransport; * var transport = new Thrift.TWebSocketTransport("http://localhost:8585"); */ function TWebSocketTransport(url) { - this.__reset(url); -}; - - -TWebSocketTransport.prototype.__reset = function(url) { - this.url = url; //Where to connect - this.socket = null; //The web socket - this.callbacks = []; //Pending callbacks - this.send_pending = []; //Buffers/Callback pairs waiting to be sent - this.send_buf = ''; //Outbound data, immutable until sent - this.recv_buf = ''; //Inbound data - this.rb_wpos = 0; //Network write position in receive buffer - this.rb_rpos = 0; //Client read position in receive buffer + this.__reset(url); +} + +TWebSocketTransport.prototype.__reset = function (url) { + this.url = url; //Where to connect + this.socket = null; //The web socket + this.callbacks = []; //Pending callbacks + this.send_pending = []; //Buffers/Callback pairs waiting to be sent + this.send_buf = ""; //Outbound data, immutable until sent + this.recv_buf = ""; //Inbound data + this.rb_wpos = 0; //Network write position in receive buffer + this.rb_rpos = 0; //Client read position in receive buffer }; /** @@ -56,58 +55,62 @@ TWebSocketTransport.prototype.__reset = function(url) { * @param {object} callback - The client completion callback. * @returns {undefined|string} Nothing (undefined) */ -TWebSocketTransport.prototype.flush = function(async, callback) { +TWebSocketTransport.prototype.flush = function (async, callback) { var self = this; if (this.isOpen()) { //Send data and register a callback to invoke the client callback this.socket.send(this.send_buf); - this.callbacks.push((function() { - var clientCallback = callback; - return function(msg) { - self.setRecvBuffer(msg); - clientCallback(); - }; - }())); + this.callbacks.push( + (function () { + var clientCallback = callback; + return function (msg) { + self.setRecvBuffer(msg); + clientCallback(); + }; + })(), + ); } else { //Queue the send to go out __onOpen this.send_pending.push({ buf: this.send_buf, - cb: callback + cb: callback, }); } }; -TWebSocketTransport.prototype.__onOpen = function() { - var self = this; - if (this.send_pending.length > 0) { - //If the user made calls before the connection was fully - //open, send them now - this.send_pending.forEach(function(elem) { - self.socket.send(elem.buf); - self.callbacks.push((function() { - var clientCallback = elem.cb; - return function(msg) { - self.setRecvBuffer(msg); - clientCallback(); - }; - }())); - }); - this.send_pending = []; - } +TWebSocketTransport.prototype.__onOpen = function () { + var self = this; + if (this.send_pending.length > 0) { + //If the user made calls before the connection was fully + //open, send them now + this.send_pending.forEach(function (elem) { + self.socket.send(elem.buf); + self.callbacks.push( + (function () { + var clientCallback = elem.cb; + return function (msg) { + self.setRecvBuffer(msg); + clientCallback(); + }; + })(), + ); + }); + this.send_pending = []; + } }; -TWebSocketTransport.prototype.__onClose = function(evt) { +TWebSocketTransport.prototype.__onClose = function (evt) { this.__reset(this.url); }; -TWebSocketTransport.prototype.__onMessage = function(evt) { +TWebSocketTransport.prototype.__onMessage = function (evt) { if (this.callbacks.length) { this.callbacks.shift()(evt.data); } }; -TWebSocketTransport.prototype.__onError = function(evt) { - log.error('websocket: ' + evt.toString()); +TWebSocketTransport.prototype.__onError = function (evt) { + log.error("websocket: " + evt.toString()); this.socket.close(); }; @@ -115,7 +118,7 @@ TWebSocketTransport.prototype.__onError = function(evt) { * Sets the buffer to use when receiving server responses. * @param {string} buf - The buffer to receive server responses. */ -TWebSocketTransport.prototype.setRecvBuffer = function(buf) { +TWebSocketTransport.prototype.setRecvBuffer = function (buf) { this.recv_buf = buf; this.recv_buf_sz = this.recv_buf.length; this.wpos = this.recv_buf.length; @@ -127,14 +130,14 @@ TWebSocketTransport.prototype.setRecvBuffer = function(buf) { * @readonly * @returns {boolean} */ -TWebSocketTransport.prototype.isOpen = function() { +TWebSocketTransport.prototype.isOpen = function () { return this.socket && this.socket.readyState == this.socket.OPEN; }; /** * Opens the transport connection */ -TWebSocketTransport.prototype.open = function() { +TWebSocketTransport.prototype.open = function () { //If OPEN/CONNECTING/CLOSING ignore additional opens if (this.socket && this.socket.readyState != this.socket.CLOSED) { return; @@ -150,7 +153,7 @@ TWebSocketTransport.prototype.open = function() { /** * Closes the transport connection */ -TWebSocketTransport.prototype.close = function() { +TWebSocketTransport.prototype.close = function () { this.socket.close(); }; @@ -160,11 +163,11 @@ TWebSocketTransport.prototype.close = function() { * @param {number} len - The number of characters to return. * @returns {string} Characters sent by the server. */ -TWebSocketTransport.prototype.read = function(len) { +TWebSocketTransport.prototype.read = function (len) { var avail = this.wpos - this.rpos; if (avail === 0) { - return ''; + return ""; } var give = len; @@ -184,7 +187,7 @@ TWebSocketTransport.prototype.read = function(len) { * Returns the entire response buffer. * @returns {string} Characters sent by the server. */ -TWebSocketTransport.prototype.readAll = function() { +TWebSocketTransport.prototype.readAll = function () { return this.recv_buf; }; @@ -192,7 +195,7 @@ TWebSocketTransport.prototype.readAll = function() { * Sets the send buffer to buf. * @param {string} buf - The buffer to send. */ -TWebSocketTransport.prototype.write = function(buf) { +TWebSocketTransport.prototype.write = function (buf) { this.send_buf = buf; }; @@ -201,6 +204,6 @@ TWebSocketTransport.prototype.write = function(buf) { * @readonly * @returns {string} The send buffer. */ -TWebSocketTransport.prototype.getSendBuffer = function() { +TWebSocketTransport.prototype.getSendBuffer = function () { return this.send_buf; }; diff --git a/lib/nodejs/lib/thrift/xhr_connection.js b/lib/nodejs/lib/thrift/xhr_connection.js index 6459c900c2a..ea542d1fe58 100644 --- a/lib/nodejs/lib/thrift/xhr_connection.js +++ b/lib/nodejs/lib/thrift/xhr_connection.js @@ -16,15 +16,15 @@ * specific language governing permissions and limitations * under the License. */ -var util = require('util'); +var util = require("util"); var EventEmitter = require("events").EventEmitter; -var thrift = require('./thrift'); +var thrift = require("./thrift"); -var TBufferedTransport = require('./buffered_transport'); -var TJSONProtocol = require('./json_protocol'); -var InputBufferUnderrunError = require('./input_buffer_underrun_error'); +var TBufferedTransport = require("./buffered_transport"); +var TJSONProtocol = require("./json_protocol"); +var InputBufferUnderrunError = require("./input_buffer_underrun_error"); -var createClient = require('./create_client'); +var createClient = require("./create_client"); exports.XHRConnection = XHRConnection; @@ -43,43 +43,49 @@ function XHRConnection(host, port, options) { this.options = options || {}; this.wpos = 0; this.rpos = 0; - this.useCORS = (options && options.useCORS); - this.send_buf = ''; - this.recv_buf = ''; + this.useCORS = options && options.useCORS; + this.send_buf = ""; + this.recv_buf = ""; this.transport = options.transport || TBufferedTransport; this.protocol = options.protocol || TJSONProtocol; this.headers = options.headers || {}; host = host || window.location.host; port = port || window.location.port; - var prefix = options.https ? 'https://' : 'http://'; - var path = options.path || '/'; + var prefix = options.https ? "https://" : "http://"; + var path = options.path || "/"; - if (port === '') { + if (port === "") { port = undefined; } - if (!port || port === 80 || port === '80') { + if (!port || port === 80 || port === "80") { this.url = prefix + host + path; } else { - this.url = prefix + host + ':' + port + path; + this.url = prefix + host + ":" + port + path; } //The sequence map is used to map seqIDs back to the // calling client in multiplexed scenarios this.seqId2Service = {}; -}; +} util.inherits(XHRConnection, EventEmitter); /** -* Gets the browser specific XmlHttpRequest Object. -* @returns {object} the browser XHR interface object -*/ -XHRConnection.prototype.getXmlHttpRequestObject = function() { - try { return new XMLHttpRequest(); } catch (e1) { } - try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e2) { } - try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e3) { } + * Gets the browser specific XmlHttpRequest Object. + * @returns {object} the browser XHR interface object + */ +XHRConnection.prototype.getXmlHttpRequestObject = function () { + try { + return new XMLHttpRequest(); + } catch (e1) {} + try { + return new ActiveXObject("Msxml2.XMLHTTP"); + } catch (e2) {} + try { + return new ActiveXObject("Microsoft.XMLHTTP"); + } catch (e3) {} throw "Your browser doesn't support XHR."; }; @@ -94,27 +100,27 @@ XHRConnection.prototype.getXmlHttpRequestObject = function() { * @returns {undefined|string} Nothing or the current send buffer. * @throws {string} If XHR fails. */ -XHRConnection.prototype.flush = function() { +XHRConnection.prototype.flush = function () { var self = this; - if (this.url === undefined || this.url === '') { + if (this.url === undefined || this.url === "") { return this.send_buf; } var xreq = this.getXmlHttpRequestObject(); if (xreq.overrideMimeType) { - xreq.overrideMimeType('application/json'); + xreq.overrideMimeType("application/json"); } - xreq.onreadystatechange = function() { + xreq.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { self.setRecvBuffer(this.responseText); } }; - xreq.open('POST', this.url, true); + xreq.open("POST", this.url, true); - Object.keys(this.headers).forEach(function(headerKey) { + Object.keys(this.headers).forEach(function (headerKey) { xreq.setRequestHeader(headerKey, self.headers[headerKey]); }); @@ -125,7 +131,7 @@ XHRConnection.prototype.flush = function() { * Sets the buffer to provide the protocol when deserializing. * @param {string} buf - The buffer to supply the protocol. */ -XHRConnection.prototype.setRecvBuffer = function(buf) { +XHRConnection.prototype.setRecvBuffer = function (buf) { this.recv_buf = buf; this.recv_buf_sz = this.recv_buf.length; this.wpos = this.recv_buf.length; @@ -137,10 +143,9 @@ XHRConnection.prototype.setRecvBuffer = function(buf) { var thing = new Buffer(data || buf); this.transport.receiver(this.__decodeCallback.bind(this))(thing); - }; -XHRConnection.prototype.__decodeCallback = function(transport_with_data) { +XHRConnection.prototype.__decodeCallback = function (transport_with_data) { var proto = new this.protocol(transport_with_data); try { while (true) { @@ -165,7 +170,7 @@ XHRConnection.prototype.__decodeCallback = function(transport_with_data) { delete this.seqId2Service[header.rseqid]; } /*jshint -W083 */ - client._reqs[dummy_seqid] = function(err, success) { + client._reqs[dummy_seqid] = function (err, success) { transport_with_data.commitPosition(); var clientCallback = client._reqs[header.rseqid]; delete client._reqs[header.rseqid]; @@ -174,14 +179,17 @@ XHRConnection.prototype.__decodeCallback = function(transport_with_data) { } }; /*jshint +W083 */ - if (client['recv_' + header.fname]) { - client['recv_' + header.fname](proto, header.mtype, dummy_seqid); + if (client["recv_" + header.fname]) { + client["recv_" + header.fname](proto, header.mtype, dummy_seqid); } else { delete client._reqs[dummy_seqid]; - this.emit("error", + this.emit( + "error", new thrift.TApplicationException( thrift.TApplicationExceptionType.WRONG_METHOD_NAME, - "Received a response to an unknown RPC function")); + "Received a response to an unknown RPC function", + ), + ); } } } catch (e) { @@ -198,19 +206,19 @@ XHRConnection.prototype.__decodeCallback = function(transport_with_data) { * @readonly * @returns {boolean} Always True. */ -XHRConnection.prototype.isOpen = function() { +XHRConnection.prototype.isOpen = function () { return true; }; /** * Opens the transport connection, with XHR this is a nop. */ -XHRConnection.prototype.open = function() {}; +XHRConnection.prototype.open = function () {}; /** * Closes the transport connection, with XHR this is a nop. */ -XHRConnection.prototype.close = function() {}; +XHRConnection.prototype.close = function () {}; /** * Returns the specified number of characters from the response @@ -218,11 +226,11 @@ XHRConnection.prototype.close = function() {}; * @param {number} len - The number of characters to return. * @returns {string} Characters sent by the server. */ -XHRConnection.prototype.read = function(len) { +XHRConnection.prototype.read = function (len) { var avail = this.wpos - this.rpos; if (avail === 0) { - return ''; + return ""; } var give = len; @@ -242,7 +250,7 @@ XHRConnection.prototype.read = function(len) { * Returns the entire response buffer. * @returns {string} Characters sent by the server. */ -XHRConnection.prototype.readAll = function() { +XHRConnection.prototype.readAll = function () { return this.recv_buf; }; @@ -250,7 +258,7 @@ XHRConnection.prototype.readAll = function() { * Sets the send buffer to buf. * @param {string} buf - The buffer to send. */ -XHRConnection.prototype.write = function(buf) { +XHRConnection.prototype.write = function (buf) { this.send_buf = buf; this.flush(); }; @@ -260,7 +268,7 @@ XHRConnection.prototype.write = function(buf) { * @readonly * @returns {string} The send buffer. */ -XHRConnection.prototype.getSendBuffer = function() { +XHRConnection.prototype.getSendBuffer = function () { return this.send_buf; }; @@ -273,7 +281,7 @@ XHRConnection.prototype.getSendBuffer = function() { * @returns {XHRConnection} The connection object. * @see {@link XHRConnectOptions} */ -exports.createXHRConnection = function(host, port, options) { +exports.createXHRConnection = function (host, port, options) { return new XHRConnection(host, port, options); }; diff --git a/lib/nodejs/test/binary.test.js b/lib/nodejs/test/binary.test.js index 187cd187434..343d39a9923 100644 --- a/lib/nodejs/test/binary.test.js +++ b/lib/nodejs/test/binary.test.js @@ -21,7 +21,7 @@ const test = require("tape"); const binary = require("thrift/binary"); const cases = { - "Should read signed byte": function(assert) { + "Should read signed byte": function (assert) { assert.equal(1, binary.readByte(0x01)); assert.equal(-1, binary.readByte(0xff)); @@ -29,12 +29,12 @@ const cases = { assert.equal(-128, binary.readByte(0x80)); assert.end(); }, - "Should write byte": function(assert) { + "Should write byte": function (assert) { //Protocol simply writes to the buffer. Nothing to test.. yet. assert.ok(true); assert.end(); }, - "Should read I16": function(assert) { + "Should read I16": function (assert) { assert.equal(0, binary.readI16([0x00, 0x00])); assert.equal(1, binary.readI16([0x00, 0x01])); assert.equal(-1, binary.readI16([0xff, 0xff])); @@ -46,7 +46,7 @@ const cases = { assert.end(); }, - "Should write I16": function(assert) { + "Should write I16": function (assert) { assert.deepEqual([0x00, 0x00], binary.writeI16([], 0)); assert.deepEqual([0x00, 0x01], binary.writeI16([], 1)); assert.deepEqual([0xff, 0xff], binary.writeI16([], -1)); @@ -58,7 +58,7 @@ const cases = { assert.end(); }, - "Should read I32": function(assert) { + "Should read I32": function (assert) { assert.equal(0, binary.readI32([0x00, 0x00, 0x00, 0x00])); assert.equal(1, binary.readI32([0x00, 0x00, 0x00, 0x01])); assert.equal(-1, binary.readI32([0xff, 0xff, 0xff, 0xff])); @@ -70,7 +70,7 @@ const cases = { assert.end(); }, - "Should write I32": function(assert) { + "Should write I32": function (assert) { assert.deepEqual([0x00, 0x00, 0x00, 0x00], binary.writeI32([], 0)); assert.deepEqual([0x00, 0x00, 0x00, 0x01], binary.writeI32([], 1)); assert.deepEqual([0xff, 0xff, 0xff, 0xff], binary.writeI32([], -1)); @@ -78,137 +78,139 @@ const cases = { // Min I32 assert.deepEqual( [0x80, 0x00, 0x00, 0x00], - binary.writeI32([], -2147483648) + binary.writeI32([], -2147483648), ); // Max I32 assert.deepEqual([0x7f, 0xff, 0xff, 0xff], binary.writeI32([], 2147483647)); assert.end(); }, - "Should read doubles": function(assert) { + "Should read doubles": function (assert) { assert.equal( 0, - binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); assert.equal( 0, - binary.readDouble([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); assert.equal( 1, - binary.readDouble([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); assert.equal( 2, - binary.readDouble([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); assert.equal( -2, - binary.readDouble([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); assert.equal( Math.PI, - binary.readDouble([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18]) + binary.readDouble([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18]), ); assert.equal( Infinity, - binary.readDouble([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); assert.equal( -Infinity, - binary.readDouble([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); assert.ok( - isNaN(binary.readDouble([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) + isNaN( + binary.readDouble([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + ), ); assert.equal( 1 / 3, - binary.readDouble([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]) + binary.readDouble([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]), ); // Min subnormal positive double assert.equal( 4.9406564584124654e-324, - binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]) + binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]), ); // Min normal positive double assert.equal( 2.2250738585072014e-308, - binary.readDouble([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + binary.readDouble([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), ); // Max positive double assert.equal( 1.7976931348623157e308, - binary.readDouble([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) + binary.readDouble([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), ); assert.end(); }, - "Should write doubles": function(assert) { + "Should write doubles": function (assert) { assert.deepEqual( [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], 0) + binary.writeDouble([], 0), ); assert.deepEqual( [0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], 1) + binary.writeDouble([], 1), ); assert.deepEqual( [0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], 2) + binary.writeDouble([], 2), ); assert.deepEqual( [0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], -2) + binary.writeDouble([], -2), ); assert.deepEqual( [0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18], - binary.writeDouble([], Math.PI) + binary.writeDouble([], Math.PI), ); assert.deepEqual( [0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], Infinity) + binary.writeDouble([], Infinity), ); assert.deepEqual( [0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], -Infinity) + binary.writeDouble([], -Infinity), ); assert.deepEqual( [0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], NaN) + binary.writeDouble([], NaN), ); assert.deepEqual( [0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55], - binary.writeDouble([], 1 / 3) + binary.writeDouble([], 1 / 3), ); // Min subnormal positive double assert.deepEqual( [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], - binary.writeDouble([], 4.9406564584124654e-324) + binary.writeDouble([], 4.9406564584124654e-324), ); // Min normal positive double assert.deepEqual( [0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - binary.writeDouble([], 2.2250738585072014e-308) + binary.writeDouble([], 2.2250738585072014e-308), ); // Max positive double assert.deepEqual( [0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], - binary.writeDouble([], 1.7976931348623157e308) + binary.writeDouble([], 1.7976931348623157e308), ); assert.end(); - } + }, }; -Object.keys(cases).forEach(function(caseName) { +Object.keys(cases).forEach(function (caseName) { test(caseName, cases[caseName]); }); diff --git a/lib/nodejs/test/client.js b/lib/nodejs/test/client.js index 31ea06e2f0d..1d137fff51a 100644 --- a/lib/nodejs/test/client.js +++ b/lib/nodejs/test/client.js @@ -25,8 +25,8 @@ const helpers = require("./helpers"); const ThriftTest = require(`./${helpers.genPath}/ThriftTest`); const ThriftTestDriver = require("./test_driver").ThriftTestDriver; -const ThriftTestDriverPromise = require("./test_driver") - .ThriftTestDriverPromise; +const ThriftTestDriverPromise = + require("./test_driver").ThriftTestDriverPromise; const SecondService = require(`./${helpers.genPath}/SecondService`); const program = require("commander"); @@ -34,24 +34,24 @@ const program = require("commander"); program .option( "-p, --protocol ", - "Set thrift protocol (binary|compact|json) [protocol]" + "Set thrift protocol (binary|compact|json) [protocol]", ) .option( "-t, --transport ", - "Set thrift transport (buffered|framed|http) [transport]" + "Set thrift transport (buffered|framed|http) [transport]", ) .option("--port ", "Set thrift server port number to connect", 9090) .option("--host ", "Set thrift server host to connect", "localhost") .option( "--domain-socket ", - "Set thrift server unix domain socket to connect" + "Set thrift server unix domain socket to connect", ) .option("--ssl", "use SSL transport") .option("--callback", "test with callback style functions") .option( "-t, --type ", "Select server type (http|multiplex|tcp|websocket)", - "tcp" + "tcp", ) .option("--es6", "Use es6 code") .option("--es5", "Use es5 code") @@ -76,7 +76,7 @@ if (program.transport === "websocket") { const options = { transport: helpers.transports[program.transport], - protocol: helpers.protocols[program.protocol] + protocol: helpers.protocols[program.protocol], }; if (type === "http" || type === "websocket") { @@ -128,7 +128,7 @@ if (type === "tcp" || type === "multiplex") { connection.open(); } -connection.on("error", function(err) { +connection.on("error", function (err) { assert(false, err); }); @@ -141,11 +141,11 @@ if (type === "tcp") { const secondclient = mp.createClient( "SecondService", SecondService, - connection + connection, ); - connection.on("connect", function() { - secondclient.secondtestString("Test", function(err, response) { + connection.on("connect", function () { + secondclient.secondtestString("Test", function (err, response) { assert(!err); assert.equal('testString("Test")', response); }); @@ -161,7 +161,7 @@ if (type === "tcp") { } function runTests() { - testDriver(client, function(status) { + testDriver(client, function (status) { console.log(status); if (type !== "http" && type !== "websocket") { connection.end(); @@ -172,4 +172,4 @@ function runTests() { }); } -exports.expressoTest = function() {}; +exports.expressoTest = function () {}; diff --git a/lib/nodejs/test/deep-constructor.test.js b/lib/nodejs/test/deep-constructor.test.js index a91ddb1784c..e5ac3f888e2 100644 --- a/lib/nodejs/test/deep-constructor.test.js +++ b/lib/nodejs/test/deep-constructor.test.js @@ -24,7 +24,7 @@ const bufferEquals = require("buffer-equals"); function serializeBinary(data) { let buff; - const transport = new thrift.TBufferedTransport(null, function(msg) { + const transport = new thrift.TBufferedTransport(null, function (msg) { buff = msg; }); const prot = new thrift.TBinaryProtocol(transport); @@ -43,7 +43,7 @@ function deserializeBinary(serialized, type) { function serializeJSON(data) { let buff; - const transport = new thrift.TBufferedTransport(null, function(msg) { + const transport = new thrift.TBufferedTransport(null, function (msg) { buff = msg; }); const protocol = new thrift.TJSONProtocol(transport); @@ -70,17 +70,17 @@ function createThriftObj() { struct_list_field: [ new ttypes.Simple({ value: "b" }), - new ttypes.Simple({ value: "c" }) + new ttypes.Simple({ value: "c" }), ], struct_set_field: [ new ttypes.Simple({ value: "d" }), - new ttypes.Simple({ value: "e" }) + new ttypes.Simple({ value: "e" }), ], struct_map_field: { A: new ttypes.Simple({ value: "f" }), - B: new ttypes.Simple({ value: "g" }) + B: new ttypes.Simple({ value: "g" }), }, struct_nested_containers_field: [ @@ -88,46 +88,46 @@ function createThriftObj() { { C: [ new ttypes.Simple({ value: "h" }), - new ttypes.Simple({ value: "i" }) - ] - } - ] + new ttypes.Simple({ value: "i" }), + ], + }, + ], ], struct_nested_containers_field2: { D: [ { - DA: new ttypes.Simple({ value: "j" }) + DA: new ttypes.Simple({ value: "j" }), }, { - DB: new ttypes.Simple({ value: "k" }) - } - ] + DB: new ttypes.Simple({ value: "k" }), + }, + ], }, list_of_list_field: [ ["l00", "l01", "l02"], ["l10", "l11", "l12"], - ["l20", "l21", "l22"] + ["l20", "l21", "l22"], ], list_of_list_of_list_field: [ [ ["m000", "m001", "m002"], ["m010", "m011", "m012"], - ["m020", "m021", "m022"] + ["m020", "m021", "m022"], ], [ ["m100", "m101", "m102"], ["m110", "m111", "m112"], - ["m120", "m121", "m122"] + ["m120", "m121", "m122"], ], [ ["m200", "m201", "m202"], ["m210", "m211", "m212"], - ["m220", "m221", "m222"] - ] - ] + ["m220", "m221", "m222"], + ], + ], }); } @@ -141,51 +141,51 @@ function createJsObj() { struct_map_field: { A: { value: "f" }, - B: { value: "g" } + B: { value: "g" }, }, struct_nested_containers_field: [ [ { - C: [{ value: "h" }, { value: "i" }] - } - ] + C: [{ value: "h" }, { value: "i" }], + }, + ], ], struct_nested_containers_field2: { D: [ { - DA: { value: "j" } + DA: { value: "j" }, }, { - DB: { value: "k" } - } - ] + DB: { value: "k" }, + }, + ], }, list_of_list_field: [ ["l00", "l01", "l02"], ["l10", "l11", "l12"], - ["l20", "l21", "l22"] + ["l20", "l21", "l22"], ], list_of_list_of_list_field: [ [ ["m000", "m001", "m002"], ["m010", "m011", "m012"], - ["m020", "m021", "m022"] + ["m020", "m021", "m022"], ], [ ["m100", "m101", "m102"], ["m110", "m111", "m112"], - ["m120", "m121", "m122"] + ["m120", "m121", "m122"], ], [ ["m200", "m201", "m202"], ["m210", "m211", "m212"], - ["m220", "m221", "m222"] - ] - ] + ["m220", "m221", "m222"], + ], + ], }; } @@ -244,7 +244,7 @@ function assertValues(obj, assert) { function createTestCases(serialize, deserialize) { const cases = { - "Serialize/deserialize should return equal object": function(assert) { + "Serialize/deserialize should return equal object": function (assert) { const tObj = createThriftObj(); const received = deserialize(serialize(tObj), ttypes.Complex); assert.ok(tObj !== received, "not the same object"); @@ -252,51 +252,49 @@ function createTestCases(serialize, deserialize) { assert.end(); }, - "Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects": function( - assert - ) { - const tObj1 = createThriftObj(); - const tObj2 = new ttypes.Complex(createJsObj()); - assertValues(tObj2, assert); - const s1 = serialize(tObj1); - const s2 = serialize(tObj2); - assert.ok(bufferEquals(s1, s2)); - assert.end(); - }, - - "Modifications to args object should not affect constructed Thrift object": function( - assert - ) { - const args = createJsObj(); - assertValues(args, assert); - - const tObj = new ttypes.Complex(args); - assertValues(tObj, assert); - - args.struct_field.value = "ZZZ"; - args.struct_list_field[0].value = "ZZZ"; - args.struct_list_field[1].value = "ZZZ"; - args.struct_set_field[0].value = "ZZZ"; - args.struct_set_field[1].value = "ZZZ"; - args.struct_map_field.A.value = "ZZZ"; - args.struct_map_field.B.value = "ZZZ"; - args.struct_nested_containers_field[0][0].C[0] = "ZZZ"; - args.struct_nested_containers_field[0][0].C[1] = "ZZZ"; - args.struct_nested_containers_field2.D[0].DA = "ZZZ"; - args.struct_nested_containers_field2.D[0].DB = "ZZZ"; - - assertValues(tObj, assert); - assert.end(); - }, - - "nulls are ok": function(assert) { + "Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects": + function (assert) { + const tObj1 = createThriftObj(); + const tObj2 = new ttypes.Complex(createJsObj()); + assertValues(tObj2, assert); + const s1 = serialize(tObj1); + const s2 = serialize(tObj2); + assert.ok(bufferEquals(s1, s2)); + assert.end(); + }, + + "Modifications to args object should not affect constructed Thrift object": + function (assert) { + const args = createJsObj(); + assertValues(args, assert); + + const tObj = new ttypes.Complex(args); + assertValues(tObj, assert); + + args.struct_field.value = "ZZZ"; + args.struct_list_field[0].value = "ZZZ"; + args.struct_list_field[1].value = "ZZZ"; + args.struct_set_field[0].value = "ZZZ"; + args.struct_set_field[1].value = "ZZZ"; + args.struct_map_field.A.value = "ZZZ"; + args.struct_map_field.B.value = "ZZZ"; + args.struct_nested_containers_field[0][0].C[0] = "ZZZ"; + args.struct_nested_containers_field[0][0].C[1] = "ZZZ"; + args.struct_nested_containers_field2.D[0].DA = "ZZZ"; + args.struct_nested_containers_field2.D[0].DB = "ZZZ"; + + assertValues(tObj, assert); + assert.end(); + }, + + "nulls are ok": function (assert) { const tObj = new ttypes.Complex({ struct_field: null, struct_list_field: null, struct_set_field: null, struct_map_field: null, struct_nested_containers_field: null, - struct_nested_containers_field2: null + struct_nested_containers_field2: null, }); const received = deserialize(serialize(tObj), ttypes.Complex); assert.strictEqual(tObj.struct_field, null); @@ -305,9 +303,9 @@ function createTestCases(serialize, deserialize) { assert.end(); }, - "Can make list with objects": function(assert) { + "Can make list with objects": function (assert) { const tObj = new ttypes.ComplexList({ - struct_list_field: [new ttypes.Complex({})] + struct_list_field: [new ttypes.Complex({})], }); const innerObj = tObj.struct_list_field[0]; assert.ok(innerObj instanceof ttypes.Complex); @@ -318,13 +316,13 @@ function createTestCases(serialize, deserialize) { assert.strictEqual(innerObj.struct_nested_containers_field, null); assert.strictEqual(innerObj.struct_nested_containers_field2, null); assert.end(); - } + }, }; return cases; } function run(name, cases) { - Object.keys(cases).forEach(function(caseName) { + Object.keys(cases).forEach(function (caseName) { test(name + ": " + caseName, cases[caseName]); }); } diff --git a/lib/nodejs/test/episodic-code-generation-test/client.js b/lib/nodejs/test/episodic-code-generation-test/client.js index 55dc70269ca..631bfe73a7e 100644 --- a/lib/nodejs/test/episodic-code-generation-test/client.js +++ b/lib/nodejs/test/episodic-code-generation-test/client.js @@ -37,21 +37,21 @@ const port = program.port; const options = { transport: thrift.TBufferedTransport, - protocol: thrift.TJSONProtocol + protocol: thrift.TJSONProtocol, }; const connection = thrift.createConnection(host, port, options); -const testDriver = function(client, callback) { - test("NodeJS episodic compilation client-server test", function(assert) { +const testDriver = function (client, callback) { + test("NodeJS episodic compilation client-server test", function (assert) { const type1Object = new Types.Type1(); type1Object.number = 42; type1Object.message = "The answer"; - client.testEpisode(type1Object, function(err, response) { + client.testEpisode(type1Object, function (err, response) { assert.error(err, "no callback error"); assert.equal(response.number, type1Object.number + 1); assert.equal( response.message, - type1Object.message + " [Hello from the server]" + type1Object.message + " [Hello from the server]", ); assert.end(); callback("Server successfully tested"); @@ -59,7 +59,7 @@ const testDriver = function(client, callback) { }); }; -connection.on("error", function(err) { +connection.on("error", function (err) { assert(false, err); }); @@ -68,10 +68,10 @@ const client = thrift.createClient(Service, connection); runTests(); function runTests() { - testDriver(client, function(status) { + testDriver(client, function (status) { console.log(status); connection.destroy(); }); } -exports.expressoTest = function() {}; +exports.expressoTest = function () {}; diff --git a/lib/nodejs/test/episodic-code-generation-test/server.js b/lib/nodejs/test/episodic-code-generation-test/server.js index 2917b681c84..feca38045d9 100644 --- a/lib/nodejs/test/episodic-code-generation-test/server.js +++ b/lib/nodejs/test/episodic-code-generation-test/server.js @@ -33,17 +33,17 @@ const port = program.port; const options = { transport: thrift.TBufferedTransport, - protocol: thrift.TJSONProtocol + protocol: thrift.TJSONProtocol, }; const ServiceHandler = { - testEpisode: function(receivedType1Object) { + testEpisode: function (receivedType1Object) { const type1Object = new Types.Type1(); type1Object.number = receivedType1Object.number + 1; type1Object.message = receivedType1Object.message + " [Hello from the server]"; return type1Object; - } + }, }; const server = thrift.createServer(Service, ServiceHandler, options); diff --git a/lib/nodejs/test/exceptions.js b/lib/nodejs/test/exceptions.js index ab2798a26a1..4119e76b052 100644 --- a/lib/nodejs/test/exceptions.js +++ b/lib/nodejs/test/exceptions.js @@ -20,29 +20,29 @@ "use strict"; const test = require("tape"); const thrift = require("../lib/thrift/thrift.js"); -const InputBufferUnderrunError = require("../lib/thrift/input_buffer_underrun_error"); +const { InputBufferUnderrunError } = require("../lib/thrift"); test("TApplicationException", function t(assert) { const e = new thrift.TApplicationException(1, "foo"); assert.ok( e instanceof thrift.TApplicationException, - "is instanceof TApplicationException" + "is instanceof TApplicationException", ); assert.ok(e instanceof thrift.TException, "is instanceof TException"); assert.ok(e instanceof Error, "is instanceof Error"); assert.equal(typeof e.stack, "string", "has stack trace"); assert.ok( /^TApplicationException: foo/.test(e.stack), - "Stack trace has correct error name and message" + "Stack trace has correct error name and message", ); assert.ok( e.stack.indexOf("test/exceptions.js:7:11") !== -1, - "stack trace starts on correct line and column" + "stack trace starts on correct line and column", ); assert.equal( e.name, "TApplicationException", - "has function name TApplicationException" + "has function name TApplicationException", ); assert.equal(e.message, "foo", 'has error message "foo"'); assert.equal(e.type, 1, "has type 1"); @@ -53,23 +53,23 @@ test("unexpected TApplicationException ", function t(assert) { const e = new thrift.TApplicationException(1, 100); assert.ok( e instanceof thrift.TApplicationException, - "is instanceof TApplicationException" + "is instanceof TApplicationException", ); assert.ok(e instanceof thrift.TException, "is instanceof TException"); assert.ok(e instanceof Error, "is instanceof Error"); assert.equal(typeof e.stack, "string", "has stack trace"); assert.ok( /^TApplicationException: 100/.test(e.stack), - "Stack trace has correct error name and message" + "Stack trace has correct error name and message", ); assert.ok( e.stack.indexOf("test/exceptions.js:7:11") !== -1, - "stack trace starts on correct line and column" + "stack trace starts on correct line and column", ); assert.equal( e.name, "TApplicationException", - "has function name TApplicationException" + "has function name TApplicationException", ); assert.equal(e.message, 100, "has error message 100"); assert.equal(e.type, 1, "has type 1"); @@ -83,11 +83,11 @@ test("TException", function t(assert) { assert.equal(typeof e.stack, "string", "has stack trace"); assert.ok( /^TException: foo/.test(e.stack), - "Stack trace has correct error name and message" + "Stack trace has correct error name and message", ); assert.ok( e.stack.indexOf("test/exceptions.js:21:11") !== -1, - "stack trace starts on correct line and column" + "stack trace starts on correct line and column", ); assert.equal(e.name, "TException", "has function name TException"); assert.equal(e.message, "foo", 'has error message "foo"'); @@ -98,22 +98,22 @@ test("TProtocolException", function t(assert) { const e = new thrift.TProtocolException(1, "foo"); assert.ok( e instanceof thrift.TProtocolException, - "is instanceof TProtocolException" + "is instanceof TProtocolException", ); assert.ok(e instanceof Error, "is instanceof Error"); assert.equal(typeof e.stack, "string", "has stack trace"); assert.ok( /^TProtocolException: foo/.test(e.stack), - "Stack trace has correct error name and message" + "Stack trace has correct error name and message", ); assert.ok( e.stack.indexOf("test/exceptions.js:33:11") !== -1, - "stack trace starts on correct line and column" + "stack trace starts on correct line and column", ); assert.equal( e.name, "TProtocolException", - "has function name TProtocolException" + "has function name TProtocolException", ); assert.equal(e.message, "foo", 'has error message "foo"'); assert.equal(e.type, 1, "has type 1"); @@ -124,22 +124,22 @@ test("InputBufferUnderrunError", function t(assert) { const e = new InputBufferUnderrunError("foo"); assert.ok( e instanceof InputBufferUnderrunError, - "is instanceof InputBufferUnderrunError" + "is instanceof InputBufferUnderrunError", ); assert.ok(e instanceof Error, "is instanceof Error"); assert.equal(typeof e.stack, "string", "has stack trace"); assert.ok( /^InputBufferUnderrunError: foo/.test(e.stack), - "Stack trace has correct error name and message" + "Stack trace has correct error name and message", ); assert.ok( e.stack.indexOf("test/exceptions.js:46:11") !== -1, - "stack trace starts on correct line and column" + "stack trace starts on correct line and column", ); assert.equal( e.name, "InputBufferUnderrunError", - "has function name InputBufferUnderrunError" + "has function name InputBufferUnderrunError", ); assert.equal(e.message, "foo", 'has error message "foo"'); assert.end(); diff --git a/lib/nodejs/test/header.test.js b/lib/nodejs/test/header.test.js index 12f1557a477..24f49beff27 100644 --- a/lib/nodejs/test/header.test.js +++ b/lib/nodejs/test/header.test.js @@ -26,11 +26,11 @@ const test = require("tape"); const path = require("path"); const headerPayload = fs.readFileSync( - path.join(__dirname, "test_header_payload") + path.join(__dirname, "test_header_payload"), ); const cases = { - "Should read headers from payload": function(assert) { + "Should read headers from payload": function (assert) { const transport = new TFramedTransport(); transport.inBuf = Buffer.from(headerPayload); @@ -39,7 +39,7 @@ const cases = { assert.equals(headers.Trace, "abcde"); assert.end(); }, - "Should read different headers from different payload": function(assert) { + "Should read different headers from different payload": function (assert) { const transport = new TFramedTransport(); const buf = Buffer.from(headerPayload); buf[24] = 115; // Change Parent to Parens @@ -52,7 +52,7 @@ const cases = { assert.equals(headers.Trace, "abcde"); assert.end(); }, - "Should read headers when reading message begin": function(assert) { + "Should read headers when reading message begin": function (assert) { const transport = new TFramedTransport(); transport.inBuf = Buffer.from(headerPayload); const protocol = new THeaderProtocol(transport); @@ -65,7 +65,7 @@ const cases = { assert.equals(result.mtype, thrift.Thrift.MessageType.CALL); assert.end(); }, - "Should be able to write headers": function(assert) { + "Should be able to write headers": function (assert) { const writeTransport = new TFramedTransport(); writeTransport.setProtocolId(THeaderTransport.SubprotocolId.BINARY); writeTransport.setWriteHeader("Hihihihi", "hohohoho"); @@ -84,7 +84,7 @@ const cases = { assert.equals(headers.a, "z"); assert.end(); }, - "Separate transports should have separate headers": function(assert) { + "Separate transports should have separate headers": function (assert) { const writeTransport = new TFramedTransport(); writeTransport.setProtocolId(THeaderTransport.SubprotocolId.BINARY); writeTransport.setWriteHeader("foo", "bar"); @@ -101,8 +101,8 @@ const cases = { assert.equals(otherHeaders.otherfoo, "baz"); assert.end(); }, - "Should handle large messages without crashing": function(assert) { - const callback = function() {}; + "Should handle large messages without crashing": function (assert) { + const callback = function () {}; const onData = TFramedTransport.receiver(callback); const largeChunkSize = 2 * 100 * 1024 * 1024; @@ -112,9 +112,9 @@ const cases = { onData(Buffer.concat([sizeBuffer, largeChunk])); assert.end(); - } + }, }; -Object.keys(cases).forEach(function(caseName) { +Object.keys(cases).forEach(function (caseName) { test(caseName, cases[caseName]); }); diff --git a/lib/nodejs/test/helpers.js b/lib/nodejs/test/helpers.js index f3c27b3d1f1..51a0523139e 100644 --- a/lib/nodejs/test/helpers.js +++ b/lib/nodejs/test/helpers.js @@ -22,14 +22,14 @@ const thrift = require("../lib/thrift"); module.exports.transports = { buffered: thrift.TBufferedTransport, - framed: thrift.TFramedTransport + framed: thrift.TFramedTransport, }; module.exports.protocols = { json: thrift.TJSONProtocol, binary: thrift.TBinaryProtocol, compact: thrift.TCompactProtocol, - header: thrift.THeaderProtocol + header: thrift.THeaderProtocol, }; module.exports.ecmaMode = process.argv.includes("--es6") ? "es6" : "es5"; diff --git a/lib/nodejs/test/int64.test.js b/lib/nodejs/test/int64.test.js index 27ad28c003f..21d4d58a6a8 100644 --- a/lib/nodejs/test/int64.test.js +++ b/lib/nodejs/test/int64.test.js @@ -23,7 +23,7 @@ const i64types = require("./gen-nodejs-es6/Int64Test_types.js"); const test = require("tape"); const cases = { - "should correctly generate Int64 constants": function(assert) { + "should correctly generate Int64 constants": function (assert) { const EXPECTED_SMALL_INT64_AS_NUMBER = 42; const EXPECTED_SMALL_INT64 = new Int64(42); const EXPECTED_MAX_JS_SAFE_INT64 = new Int64(Number.MAX_SAFE_INTEGER); @@ -39,7 +39,7 @@ const cases = { EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64, EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64, EXPECTED_MAX_SIGNED_INT64, - EXPECTED_MIN_SIGNED_INT64 + EXPECTED_MIN_SIGNED_INT64, ]; assert.ok(EXPECTED_SMALL_INT64.equals(i64types.SMALL_INT64)); @@ -47,27 +47,27 @@ const cases = { assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(i64types.MIN_JS_SAFE_INT64)); assert.ok( EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals( - i64types.MAX_JS_SAFE_PLUS_ONE_INT64 - ) + i64types.MAX_JS_SAFE_PLUS_ONE_INT64, + ), ); assert.ok( EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals( - i64types.MIN_JS_SAFE_MINUS_ONE_INT64 - ) + i64types.MIN_JS_SAFE_MINUS_ONE_INT64, + ), ); assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(i64types.MAX_SIGNED_INT64)); assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(i64types.MIN_SIGNED_INT64)); assert.equal( EXPECTED_SMALL_INT64_AS_NUMBER, - i64types.SMALL_INT64.toNumber() + i64types.SMALL_INT64.toNumber(), ); assert.equal( Number.MAX_SAFE_INTEGER, - i64types.MAX_JS_SAFE_INT64.toNumber() + i64types.MAX_JS_SAFE_INT64.toNumber(), ); assert.equal( Number.MIN_SAFE_INTEGER, - i64types.MIN_JS_SAFE_INT64.toNumber() + i64types.MIN_JS_SAFE_INT64.toNumber(), ); for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) { @@ -79,14 +79,14 @@ const cases = { assert.ok( i64types.INT64_2_INT64_MAP[ JSONInt64.toDecimalString(int64Object) - ].equals(int64Object) + ].equals(int64Object), ); } assert.end(); - } + }, }; -Object.keys(cases).forEach(function(caseName) { +Object.keys(cases).forEach(function (caseName) { test(caseName, cases[caseName]); }); diff --git a/lib/nodejs/test/server.js b/lib/nodejs/test/server.js index 677839aea2b..c8e7808202a 100644 --- a/lib/nodejs/test/server.js +++ b/lib/nodejs/test/server.js @@ -29,12 +29,12 @@ program .option( "-p, --protocol ", "Set thrift protocol (binary|compact|json)", - "binary" + "binary", ) .option( "-t, --transport ", "Set thrift transport (buffered|framed|http)", - "buffered" + "buffered", ) .option("--ssl", "use ssl transport") .option("--port ", "Set thrift server port", 9090) @@ -42,7 +42,7 @@ program .option( "-t, --type ", "Select server type (http|multiplex|tcp|websocket)", - "tcp" + "tcp", ) .option("--callback", "test with callback style functions") .option("--es6", "Use es6 code") @@ -68,7 +68,7 @@ if (program.transport === "http") { let options = { transport: helpers.transports[program.transport], - protocol: helpers.protocols[program.protocol] + protocol: helpers.protocols[program.protocol], }; if (type === "http" || type === "websocket") { @@ -78,30 +78,30 @@ if (type === "http" || type === "websocket") { options = { services: { "/test": options }, cors: { - "*": true - } + "*": true, + }, }; } let processor; if (type === "multiplex") { const SecondServiceHandler = { - secondtestString: function(thing, result) { + secondtestString: function (thing, result) { console.log('testString("' + thing + '")'); result(null, 'testString("' + thing + '")'); - } + }, }; processor = new thrift.MultiplexedProcessor(); processor.registerProcessor( "ThriftTest", - new ThriftTest.Processor(ThriftTestHandler) + new ThriftTest.Processor(ThriftTestHandler), ); processor.registerProcessor( "SecondService", - new SecondService.Processor(SecondServiceHandler) + new SecondService.Processor(SecondServiceHandler), ); } @@ -114,7 +114,7 @@ if (ssl) { ) { options.tls = { key: fs.readFileSync(path.resolve(__dirname, "server.key")), - cert: fs.readFileSync(path.resolve(__dirname, "server.crt")) + cert: fs.readFileSync(path.resolve(__dirname, "server.crt")), }; } } diff --git a/lib/nodejs/test/test-cases.js b/lib/nodejs/test/test-cases.js index 02c566fbf53..98077f70321 100644 --- a/lib/nodejs/test/test-cases.js +++ b/lib/nodejs/test/test-cases.js @@ -65,9 +65,9 @@ const mapTestInput = (module.exports.mapTestInput = { a: "123", "a b": "with spaces ", same: "same", - "0": "numeric key", + 0: "numeric key", longValue: stringTest, - stringTest: "long key" + stringTest: "long key", }); const simple = [ @@ -93,9 +93,9 @@ const simple = [ ["testI64", new Int64(new Buffer([0, 0x20, 0, 0, 0, 0, 0, 1]))], // 2^53+1 [ "testI64", - new Int64(new Buffer([0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])) + new Int64(new Buffer([0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])), ], // -2^53-1 - ["testTypedef", 69] + ["testTypedef", 69], ]; const mapout = {}; @@ -106,21 +106,21 @@ for (let i = 0; i < 5; ++i) { const deep = [ [ "testList", - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] - ] + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], + ], ]; const deepUnordered = [ ["testMap", mapout], ["testSet", [1, 2, 3]], - ["testStringMap", mapTestInput] + ["testStringMap", mapTestInput], ]; const out = new ttypes.Xtruct({ string_thing: "Zero", byte_thing: 1, i32_thing: -3, - i64_thing: 1000000 + i64_thing: 1000000, }); const out2 = new ttypes.Xtruct2(); @@ -129,44 +129,44 @@ out2.struct_thing = out; out2.i32_thing = 5; const crazy = new ttypes.Insanity({ - userMap: { "5": 5, "8": 8 }, + userMap: { 5: 5, 8: 8 }, xtructs: [ new ttypes.Xtruct({ string_thing: "Goodbye4", byte_thing: 4, i32_thing: 4, - i64_thing: 4 + i64_thing: 4, }), new ttypes.Xtruct({ string_thing: "Hello2", byte_thing: 2, i32_thing: 2, - i64_thing: 2 - }) - ] + i64_thing: 2, + }), + ], }); const crazy2 = new ttypes.Insanity({ - userMap: { "5": 5, "8": 8 }, + userMap: { 5: 5, 8: 8 }, xtructs: [ { string_thing: "Goodbye4", byte_thing: 4, i32_thing: 4, - i64_thing: 4 + i64_thing: 4, }, { string_thing: "Hello2", byte_thing: 2, i32_thing: 2, - i64_thing: 2 - } - ] + i64_thing: 2, + }, + ], }); const insanity = { - "1": { "2": crazy, "3": crazy }, - "2": { "6": { userMap: {}, xtructs: [] } } + 1: { 2: crazy, 3: crazy }, + 2: { 6: { userMap: {}, xtructs: [] } }, }; module.exports.simple = simple; diff --git a/lib/nodejs/test/test_driver.js b/lib/nodejs/test/test_driver.js index 7c9a91914bf..0593aeab671 100644 --- a/lib/nodejs/test/test_driver.js +++ b/lib/nodejs/test/test_driver.js @@ -34,18 +34,18 @@ const TException = require("thrift").Thrift.TException; const Int64 = require("node-int64"); const testCases = require("./test-cases"); -exports.ThriftTestDriver = function(client, callback) { +exports.ThriftTestDriver = function (client, callback) { test( "NodeJS Style Callback Client Tests", { skip: helpers.ecmaMode === "es6" }, - function(assert) { + function (assert) { const checkRecursively = makeRecursiveCheck(assert); function makeAsserter(assertionFn) { - return function(c) { + return function (c) { const fnName = c[0]; const expected = c[1]; - client[fnName](expected, function(err, actual) { + client[fnName](expected, function (err, actual) { assert.error(err, fnName + ": no callback error"); assertionFn(actual, expected, fnName); }); @@ -53,18 +53,18 @@ exports.ThriftTestDriver = function(client, callback) { } testCases.simple.forEach( - makeAsserter(function(a, e, m) { + makeAsserter(function (a, e, m) { if (a instanceof Int64) { const e64 = e instanceof Int64 ? e : new Int64(e); assert.deepEqual(a.buffer, e64.buffer, m); } else { assert.equal(a, e, m); } - }) + }), ); testCases.deep.forEach(makeAsserter(assert.deepEqual)); testCases.deepUnordered.forEach( - makeAsserter(makeUnorderedDeepEqual(assert)) + makeAsserter(makeUnorderedDeepEqual(assert)), ); const arr = []; @@ -72,106 +72,106 @@ exports.ThriftTestDriver = function(client, callback) { arr[i] = 255 - i; } let buf = new Buffer(arr); - client.testBinary(buf, function(err, response) { + client.testBinary(buf, function (err, response) { assert.error(err, "testBinary: no callback error"); assert.equal(response.length, 256, "testBinary"); assert.deepEqual(response, buf, "testBinary(Buffer)"); }); buf = new Buffer(arr); - client.testBinary(buf.toString("binary"), function(err, response) { + client.testBinary(buf.toString("binary"), function (err, response) { assert.error(err, "testBinary: no callback error"); assert.equal(response.length, 256, "testBinary"); assert.deepEqual(response, buf, "testBinary(string)"); }); - client.testMapMap(42, function(err, response) { + client.testMapMap(42, function (err, response) { const expected = { - "4": { "1": 1, "2": 2, "3": 3, "4": 4 }, - "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 } + 4: { 1: 1, 2: 2, 3: 3, 4: 4 }, + "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 }, }; assert.error(err, "testMapMap: no callback error"); assert.deepEqual(expected, response, "testMapMap"); }); - client.testStruct(testCases.out, function(err, response) { + client.testStruct(testCases.out, function (err, response) { assert.error(err, "testStruct: no callback error"); checkRecursively(testCases.out, response, "testStruct"); }); - client.testNest(testCases.out2, function(err, response) { + client.testNest(testCases.out2, function (err, response) { assert.error(err, "testNest: no callback error"); checkRecursively(testCases.out2, response, "testNest"); }); - client.testInsanity(testCases.crazy, function(err, response) { + client.testInsanity(testCases.crazy, function (err, response) { assert.error(err, "testInsanity: no callback error"); checkRecursively(testCases.insanity, response, "testInsanity"); }); - client.testInsanity(testCases.crazy2, function(err, response) { + client.testInsanity(testCases.crazy2, function (err, response) { assert.error(err, "testInsanity2: no callback error"); checkRecursively(testCases.insanity, response, "testInsanity2"); }); - client.testException("TException", function(err, response) { + client.testException("TException", function (err, response) { assert.ok( err instanceof TException, - "testException: correct error type" + "testException: correct error type", ); assert.ok(!response, "testException: no response"); }); - client.testException("Xception", function(err, response) { + client.testException("Xception", function (err, response) { assert.ok( err instanceof ttypes.Xception, - "testException: correct error type" + "testException: correct error type", ); assert.ok(!response, "testException: no response"); assert.equal(err.errorCode, 1001, "testException: correct error code"); assert.equal( "Xception", err.message, - "testException: correct error message" + "testException: correct error message", ); }); - client.testException("no Exception", function(err, response) { + client.testException("no Exception", function (err, response) { assert.error(err, "testException: no callback error"); assert.ok(!response, "testException: no response"); }); - client.testOneway(0, function(err, response) { + client.testOneway(0, function (err, response) { assert.error(err, "testOneway: no callback error"); assert.strictEqual(response, undefined, "testOneway: void response"); }); - checkOffByOne(function(done) { - client.testI32(-1, function(err, response) { + checkOffByOne(function (done) { + client.testI32(-1, function (err, response) { assert.error(err, "checkOffByOne: no callback error"); assert.equal(-1, response); assert.end(); done(); }); }, callback); - } + }, ); // ES6 does not support callback style if (helpers.ecmaMode === "es6") { - checkOffByOne(done => done(), callback); + checkOffByOne((done) => done(), callback); } }; -exports.ThriftTestDriverPromise = function(client, callback) { - test("Promise Client Tests", function(assert) { +exports.ThriftTestDriverPromise = function (client, callback) { + test("Promise Client Tests", function (assert) { const checkRecursively = makeRecursiveCheck(assert); function makeAsserter(assertionFn) { - return function(c) { + return function (c) { const fnName = c[0]; const expected = c[1]; client[fnName](expected) - .then(function(actual) { + .then(function (actual) { assertionFn(actual, expected, fnName); }) .catch(() => assert.fail("fnName")); @@ -179,63 +179,63 @@ exports.ThriftTestDriverPromise = function(client, callback) { } testCases.simple.forEach( - makeAsserter(function(a, e, m) { + makeAsserter(function (a, e, m) { if (a instanceof Int64) { const e64 = e instanceof Int64 ? e : new Int64(e); assert.deepEqual(a.buffer, e64.buffer, m); } else { assert.equal(a, e, m); } - }) + }), ); testCases.deep.forEach(makeAsserter(assert.deepEqual)); testCases.deepUnordered.forEach( - makeAsserter(makeUnorderedDeepEqual(assert)) + makeAsserter(makeUnorderedDeepEqual(assert)), ); client .testStruct(testCases.out) - .then(function(response) { + .then(function (response) { checkRecursively(testCases.out, response, "testStruct"); }) .catch(() => assert.fail("testStruct")); client .testNest(testCases.out2) - .then(function(response) { + .then(function (response) { checkRecursively(testCases.out2, response, "testNest"); }) .catch(() => assert.fail("testNest")); client .testInsanity(testCases.crazy) - .then(function(response) { + .then(function (response) { checkRecursively(testCases.insanity, response, "testInsanity"); }) .catch(() => assert.fail("testInsanity")); client .testInsanity(testCases.crazy2) - .then(function(response) { + .then(function (response) { checkRecursively(testCases.insanity, response, "testInsanity2"); }) .catch(() => assert.fail("testInsanity2")); client .testException("TException") - .then(function() { + .then(function () { assert.fail("testException: TException"); }) - .catch(function(err) { + .catch(function (err) { assert.ok(err instanceof TException); }); client .testException("Xception") - .then(function() { + .then(function () { assert.fail("testException: Xception"); }) - .catch(function(err) { + .catch(function (err) { assert.ok(err instanceof ttypes.Xception); assert.equal(err.errorCode, 1001); assert.equal("Xception", err.message); @@ -243,22 +243,22 @@ exports.ThriftTestDriverPromise = function(client, callback) { client .testException("no Exception") - .then(function(response) { + .then(function (response) { assert.equal(undefined, response); //void }) .catch(() => assert.fail("testException")); client .testOneway(0) - .then(function(response) { + .then(function (response) { assert.strictEqual(response, undefined, "testOneway: void response"); }) .catch(() => assert.fail("testOneway: should not reject")); - checkOffByOne(function(done) { + checkOffByOne(function (done) { client .testI32(-1) - .then(function(response) { + .then(function (response) { assert.equal(-1, response); assert.end(); done(); @@ -272,7 +272,7 @@ exports.ThriftTestDriverPromise = function(client, callback) { // ========================================================= function makeRecursiveCheck(assert) { - return function(map1, map2, msg) { + return function (map1, map2, msg) { const equal = checkRecursively(map1, map2); assert.ok(equal, msg); @@ -295,7 +295,7 @@ function makeRecursiveCheck(assert) { return map1 == map2; } } else { - return Object.keys(map1).every(function(key) { + return Object.keys(map1).every(function (key) { return checkRecursively(map1[key], map2[key]); }); } @@ -319,7 +319,7 @@ function checkOffByOne(done, callback) { * Because this is the last test against the server, when it completes * the entire suite is complete by definition (the tests run serially). */ - done(function() { + done(function () { test_complete = true; }); @@ -334,7 +334,7 @@ function checkOffByOne(done, callback) { callback( "Server test failed to complete after " + (retry_limit * retry_interval) / 1000 + - " seconds" + " seconds", ); } } @@ -344,7 +344,7 @@ function checkOffByOne(done, callback) { } function makeUnorderedDeepEqual(assert) { - return function(actual, expected, name) { + return function (actual, expected, name) { assert.equal(actual.length, expected.length, name); for (const k in actual) { let found = false; diff --git a/lib/nodejs/test/test_handler.js b/lib/nodejs/test/test_handler.js index 317a7c81016..a6a6fc2e327 100644 --- a/lib/nodejs/test/test_handler.js +++ b/lib/nodejs/test/test_handler.js @@ -24,7 +24,7 @@ const ttypes = require(`./${helpers.genPath}/ThriftTest_types`); const TException = require("thrift").Thrift.TException; function makeSyncHandler() { - return function(thing) { + return function (thing) { return thing; }; } @@ -36,11 +36,11 @@ const syncHandlers = { testMulti: testMulti, testException: testException, testMultiException: testMultiException, - testOneway: testOneway + testOneway: testOneway, }; function makeAsyncHandler(label) { - return function(thing, result) { + return function (thing, result) { thing = syncHandlers[label](thing); result(null, thing); }; @@ -51,7 +51,7 @@ const asyncHandlers = { testMulti: testMultiAsync, testException: testExceptionAsync, testMultiException: testMultiExceptionAsync, - testOneway: testOnewayAsync + testOneway: testOnewayAsync, }; const identityHandlers = [ @@ -69,7 +69,7 @@ const identityHandlers = [ "testSet", "testList", "testEnum", - "testTypedef" + "testTypedef", ]; function testVoid() { @@ -208,12 +208,12 @@ function testOnewayAsync(sleepFor) { testOneway(sleepFor); } -identityHandlers.forEach(function(label) { +identityHandlers.forEach(function (label) { syncHandlers[label] = makeSyncHandler(label); asyncHandlers[label] = makeAsyncHandler(label); }); -["testMapMap", "testInsanity"].forEach(function(label) { +["testMapMap", "testInsanity"].forEach(function (label) { asyncHandlers[label] = makeAsyncHandler(label); }); diff --git a/lib/nodets/test/client.ts b/lib/nodets/test/client.ts index 4fa3c2868dd..a95567f8dc3 100644 --- a/lib/nodets/test/client.ts +++ b/lib/nodets/test/client.ts @@ -39,15 +39,15 @@ var promise = program.promise; var options = { transport: Thrift.TBufferedTransport, - protocol: Thrift.TBinaryProtocol + protocol: Thrift.TBinaryProtocol, }; var testDriver = promise ? ThriftTestDriverPromise : ThriftTestDriver; var connection = thrift.createConnection("localhost", port, options); -connection.on("error", function(err: string) { - assert(false, err); +connection.on("error", function (err: string) { + assert(false, err); }); var client = thrift.createClient(ThriftTest.Client, connection); @@ -60,4 +60,4 @@ function runTests() { }); } -exports.expressoTest = function() {}; +exports.expressoTest = function () {}; diff --git a/lib/nodets/test/int64.test.ts b/lib/nodets/test/int64.test.ts index d209234b50c..bb0345851e1 100644 --- a/lib/nodets/test/int64.test.ts +++ b/lib/nodets/test/int64.test.ts @@ -18,18 +18,26 @@ */ import Int64 = require("node-int64"); -import JSONInt64 = require('json-int64'); +import JSONInt64 = require("json-int64"); import i64types = require("./gen-nodejs/Int64Test_types"); import test = require("tape"); const cases = { - "should correctly generate Int64 constants": function(assert) { + "should correctly generate Int64 constants": function (assert) { const EXPECTED_SMALL_INT64_AS_NUMBER: number = 42; const EXPECTED_SMALL_INT64: Int64 = new Int64(42); - const EXPECTED_MAX_JS_SAFE_INT64: Int64 = new Int64(Number.MAX_SAFE_INTEGER); - const EXPECTED_MIN_JS_SAFE_INT64: Int64 = new Int64(Number.MIN_SAFE_INTEGER); - const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: Int64 = new Int64("0020000000000000"); // hex-encoded - const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: Int64 = new Int64("ffe0000000000000"); // hex-encoded 2's complement + const EXPECTED_MAX_JS_SAFE_INT64: Int64 = new Int64( + Number.MAX_SAFE_INTEGER, + ); + const EXPECTED_MIN_JS_SAFE_INT64: Int64 = new Int64( + Number.MIN_SAFE_INTEGER, + ); + const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: Int64 = new Int64( + "0020000000000000", + ); // hex-encoded + const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: Int64 = new Int64( + "ffe0000000000000", + ); // hex-encoded 2's complement const EXPECTED_MAX_SIGNED_INT64: Int64 = new Int64("7fffffffffffffff"); // hex-encoded const EXPECTED_MIN_SIGNED_INT64: Int64 = new Int64("8000000000000000"); // hex-encoded 2's complement const EXPECTED_INT64_LIST: Int64[] = [ @@ -39,7 +47,7 @@ const cases = { EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64, EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64, EXPECTED_MAX_SIGNED_INT64, - EXPECTED_MIN_SIGNED_INT64 + EXPECTED_MIN_SIGNED_INT64, ]; assert.ok(EXPECTED_SMALL_INT64.equals(i64types.SMALL_INT64)); @@ -47,42 +55,46 @@ const cases = { assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(i64types.MIN_JS_SAFE_INT64)); assert.ok( EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals( - i64types.MAX_JS_SAFE_PLUS_ONE_INT64 - ) + i64types.MAX_JS_SAFE_PLUS_ONE_INT64, + ), ); assert.ok( EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals( - i64types.MIN_JS_SAFE_MINUS_ONE_INT64 - ) + i64types.MIN_JS_SAFE_MINUS_ONE_INT64, + ), ); assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(i64types.MAX_SIGNED_INT64)); assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(i64types.MIN_SIGNED_INT64)); assert.equal( EXPECTED_SMALL_INT64_AS_NUMBER, - i64types.SMALL_INT64.toNumber() + i64types.SMALL_INT64.toNumber(), ); assert.equal( Number.MAX_SAFE_INTEGER, - i64types.MAX_JS_SAFE_INT64.toNumber() + i64types.MAX_JS_SAFE_INT64.toNumber(), ); assert.equal( Number.MIN_SAFE_INTEGER, - i64types.MIN_JS_SAFE_INT64.toNumber() + i64types.MIN_JS_SAFE_INT64.toNumber(), ); for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) { assert.ok(EXPECTED_INT64_LIST[i].equals(i64types.INT64_LIST[i])); } - for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i){ + for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) { let int64Object = EXPECTED_INT64_LIST[i]; - assert.ok(i64types.INT64_2_INT64_MAP[JSONInt64.toDecimalString(int64Object)].equals(int64Object)); + assert.ok( + i64types.INT64_2_INT64_MAP[ + JSONInt64.toDecimalString(int64Object) + ].equals(int64Object), + ); } assert.end(); - } + }, }; -Object.keys(cases).forEach(function(caseName) { +Object.keys(cases).forEach(function (caseName) { test(caseName, cases[caseName]); }); diff --git a/lib/nodets/test/server.ts b/lib/nodets/test/server.ts index 2da53aee29b..79457ce99aa 100644 --- a/lib/nodets/test/server.ts +++ b/lib/nodets/test/server.ts @@ -1,26 +1,33 @@ import thrift = require("thrift"); -var program = require('commander'); -import ThriftTest = require('./gen-nodejs/ThriftTest'); -import test_handler = require('./test_handler'); - +var program = require("commander"); +import ThriftTest = require("./gen-nodejs/ThriftTest"); +import test_handler = require("./test_handler"); program - .option('--port ', 'Set thrift server port', 9090) - .option('--promise', 'test with promise style functions') - .option('--protocol', '"Set thrift protocol (binary) [protocol]"') + .option("--port ", "Set thrift server port", 9090) + .option("--promise", "test with promise style functions") + .option("--protocol", '"Set thrift protocol (binary) [protocol]"') .parse(process.argv); var port: number = program.port; var options: thrift.ServerOptions = { transport: thrift.TBufferedTransport, - protocol: thrift.TBinaryProtocol + protocol: thrift.TBinaryProtocol, }; var server: thrift.Server; if (program.promise) { - server = thrift.createServer(ThriftTest.Processor, new test_handler.AsyncThriftTestHandler(), options); + server = thrift.createServer( + ThriftTest.Processor, + new test_handler.AsyncThriftTestHandler(), + options, + ); } else { - server = thrift.createServer(ThriftTest.Processor, new test_handler.SyncThriftTestHandler(), options); + server = thrift.createServer( + ThriftTest.Processor, + new test_handler.SyncThriftTestHandler(), + options, + ); } server.listen(port); diff --git a/lib/nodets/test/test-cases.ts b/lib/nodets/test/test-cases.ts index 44f254e9200..98f54af5ca5 100644 --- a/lib/nodets/test/test-cases.ts +++ b/lib/nodets/test/test-cases.ts @@ -1,91 +1,100 @@ -'use strict'; +"use strict"; -import ttypes = require('./gen-nodejs/ThriftTest_types'); -import Int64 = require('node-int64'); +import ttypes = require("./gen-nodejs/ThriftTest_types"); +import Int64 = require("node-int64"); //all Languages in UTF-8 /*jshint -W100 */ -export var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " + - "Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, " + - "Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, " + - "বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, " + - "Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, " + - "Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, " + - "Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, " + - "Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, " + - "Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, " + - "Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, " + - "Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, " + - "ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, " + - "Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, " + - "Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa " + - "Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, مازِرونی, Bahasa " + - "Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪" + - "Norsk (nynorsk)‬, ‪Norsk (bokmål)‬, Nouormand, Diné bizaad, " + - "Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, " + - "Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, " + - "Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple " + - "English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, " + - "Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, " + - "Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, " + - "Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " + - "Bân-lâm-gú, 粵語"; +export var stringTest = + "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " + + "Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, " + + "Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, " + + "বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, " + + "Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, " + + "Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, " + + "Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, " + + "Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, " + + "Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, " + + "Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, " + + "Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, " + + "ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, " + + "Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, " + + "Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa " + + "Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, مازِرونی, Bahasa " + + "Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪" + + "Norsk (nynorsk)‬, ‪Norsk (bokmål)‬, Nouormand, Diné bizaad, " + + "Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, " + + "Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, " + + "Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple " + + "English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, " + + "Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, " + + "Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, " + + "Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " + + "Bân-lâm-gú, 粵語"; /*jshint +W100 */ -export var specialCharacters = 'quote: \" backslash:' + - ' forwardslash-escaped: \/ ' + - ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + - ' now-all-of-them-together: "\\\/\b\n\r\t' + - ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><' + - ' char-to-test-json-parsing: ]] \"]] \\" }}}{ [[[ '; +export var specialCharacters = + 'quote: \" backslash:' + + " forwardslash-escaped: \/ " + + " backspace: \b formfeed: \f newline: \n return: \r tab: " + + ' now-all-of-them-together: "\\\/\b\n\r\t' + + " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><" + + ' char-to-test-json-parsing: ]] \"]] \\" }}}{ [[[ '; export var mapTestInput = { - "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key", - "longValue":stringTest, stringTest:"long key" + a: "123", + "a b": "with spaces ", + same: "same", + "0": "numeric key", + longValue: stringTest, + stringTest: "long key", }; export var simple = [ - ['testVoid', undefined], - ['testString', 'Test'], - ['testString', ''], - ['testString', stringTest], - ['testString', specialCharacters], - ['testByte', 1], - ['testByte', 0], - ['testByte', -1], - ['testByte', -127], - ['testI32', -1], - ['testDouble', -5.2098523], - ['testDouble', 7.012052175215044], - ['testEnum', ttypes.Numberz.ONE] + ["testVoid", undefined], + ["testString", "Test"], + ["testString", ""], + ["testString", stringTest], + ["testString", specialCharacters], + ["testByte", 1], + ["testByte", 0], + ["testByte", -1], + ["testByte", -127], + ["testI32", -1], + ["testDouble", -5.2098523], + ["testDouble", 7.012052175215044], + ["testEnum", ttypes.Numberz.ONE], ]; export var simpleLoose = [ - ['testI64', 5], - ['testI64', -5], - ['testI64', 734359738368], - ['testI64', -34359738368], - ['testI64', -734359738368], - ['testTypedef', 69] -] + ["testI64", 5], + ["testI64", -5], + ["testI64", 734359738368], + ["testI64", -34359738368], + ["testI64", -734359738368], + ["testTypedef", 69], +]; -var mapout: {[key: number]: number; } = {}; +var mapout: { [key: number]: number } = {}; for (var i = 0; i < 5; ++i) { - mapout[i] = i-10; + mapout[i] = i - 10; } export var deep = [ - ['testMap', mapout], - ['testSet', [1,2,3]], - ['testList', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]], - ['testStringMap', mapTestInput] + ["testMap", mapout], + ["testSet", [1, 2, 3]], + [ + "testList", + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], + ], + ["testStringMap", mapTestInput], ]; export var out = new ttypes.Xtruct({ - string_thing: 'Zero', + string_thing: "Zero", byte_thing: 1, i32_thing: -3, - i64_thing: new Int64(1000000) + i64_thing: new Int64(1000000), }); export var out2 = new ttypes.Xtruct2(); @@ -94,21 +103,24 @@ out2.struct_thing = out; out2.i32_thing = 5; export var crazy = new ttypes.Insanity({ - "userMap":{ "5":new Int64(5), "8":new Int64(8) }, - "xtructs":[new ttypes.Xtruct({ - "string_thing":"Goodbye4", - "byte_thing":4, - "i32_thing":4, - "i64_thing":new Int64(4) - }), new ttypes.Xtruct({ - "string_thing":"Hello2", - "byte_thing":2, - "i32_thing":2, - "i64_thing":new Int64(2) - })] + userMap: { "5": new Int64(5), "8": new Int64(8) }, + xtructs: [ + new ttypes.Xtruct({ + string_thing: "Goodbye4", + byte_thing: 4, + i32_thing: 4, + i64_thing: new Int64(4), + }), + new ttypes.Xtruct({ + string_thing: "Hello2", + byte_thing: 2, + i32_thing: 2, + i64_thing: new Int64(2), + }), + ], }); export var insanity: any = { - "1":{ "2": crazy, "3": crazy }, - "2":{ "6":{ "userMap":{}, "xtructs":[] } } + "1": { "2": crazy, "3": crazy }, + "2": { "6": { userMap: {}, xtructs: [] } }, }; diff --git a/lib/nodets/test/test_driver.ts b/lib/nodets/test/test_driver.ts index 2c4152616ee..604d5e5836d 100644 --- a/lib/nodets/test/test_driver.ts +++ b/lib/nodets/test/test_driver.ts @@ -17,14 +17,14 @@ * under the License. */ - // This is the Node.js test driver for the standard Apache Thrift - // test service. The driver invokes every function defined in the - // Thrift Test service with a representative range of parameters. - // - // The ThriftTestDriver function requires a client object - // connected to a server hosting the Thrift Test service and - // supports an optional callback function which is called with - // a status message when the test is complete. +// This is the Node.js test driver for the standard Apache Thrift +// test service. The driver invokes every function defined in the +// Thrift Test service with a representative range of parameters. +// +// The ThriftTestDriver function requires a client object +// connected to a server hosting the Thrift Test service and +// supports an optional callback function which is called with +// a status message when the test is complete. import test = require("tape"); import ttypes = require("./gen-nodejs/ThriftTest_types"); @@ -35,107 +35,118 @@ import TException = thrift.Thrift.TException; var Int64 = require("node-int64"); import testCases = require("./test-cases"); -export function ThriftTestDriver(client: ThriftTest.Client, callback: (status: string) => void) { - - test("NodeJS Style Callback Client Tests", function(assert) { - +export function ThriftTestDriver( + client: ThriftTest.Client, + callback: (status: string) => void, +) { + test("NodeJS Style Callback Client Tests", function (assert) { var checkRecursively = makeRecursiveCheck(assert); function makeAsserter(assertionFn: (a: any, b: any, msg?: string) => void) { - return function(c: (string | any)[]) { + return function (c: (string | any)[]) { var fnName = c[0]; var expected = c[1]; - (client)[fnName](expected, function(err: any, actual: any) { + (client)[fnName](expected, function (err: any, actual: any) { assert.error(err, fnName + ": no callback error"); assertionFn(actual, expected, fnName); - }) + }); }; } testCases.simple.forEach(makeAsserter(assert.equal)); - testCases.simpleLoose.forEach(makeAsserter(function(a, e, m){ - assert.ok(a == e, m); - })); + testCases.simpleLoose.forEach( + makeAsserter(function (a, e, m) { + assert.ok(a == e, m); + }), + ); testCases.deep.forEach(makeAsserter(assert.deepEqual)); - client.testMapMap(42, function(err, response) { + client.testMapMap(42, function (err, response) { var expected: typeof response = { - "4": {"1":1, "2":2, "3":3, "4":4}, - "-4": {"-4":-4, "-3":-3, "-2":-2, "-1":-1} + "4": { "1": 1, "2": 2, "3": 3, "4": 4 }, + "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 }, }; - assert.error(err, 'testMapMap: no callback error'); + assert.error(err, "testMapMap: no callback error"); assert.deepEqual(expected, response, "testMapMap"); }); - client.testStruct(testCases.out, function(err, response) { + client.testStruct(testCases.out, function (err, response) { assert.error(err, "testStruct: no callback error"); checkRecursively(testCases.out, response, "testStruct"); }); - client.testNest(testCases.out2, function(err, response) { + client.testNest(testCases.out2, function (err, response) { assert.error(err, "testNest: no callback error"); checkRecursively(testCases.out2, response, "testNest"); }); - client.testInsanity(testCases.crazy, function(err, response) { + client.testInsanity(testCases.crazy, function (err, response) { assert.error(err, "testInsanity: no callback error"); checkRecursively(testCases.insanity, response, "testInsanity"); }); - client.testException("TException", function(err, response) { - assert.ok(err instanceof TException, 'testException: correct error type'); - assert.ok(!Boolean(response), 'testException: no response'); + client.testException("TException", function (err, response) { + assert.ok(err instanceof TException, "testException: correct error type"); + assert.ok(!Boolean(response), "testException: no response"); }); - client.testException("Xception", function(err, response) { - assert.ok(err instanceof ttypes.Xception, 'testException: correct error type'); - assert.ok(!Boolean(response), 'testException: no response'); - assert.equal(err.errorCode, 1001, 'testException: correct error code'); - assert.equal('Xception', err.message, 'testException: correct error message'); + client.testException("Xception", function (err, response) { + assert.ok( + err instanceof ttypes.Xception, + "testException: correct error type", + ); + assert.ok(!Boolean(response), "testException: no response"); + assert.equal(err.errorCode, 1001, "testException: correct error code"); + assert.equal( + "Xception", + err.message, + "testException: correct error message", + ); }); - client.testException("no Exception", function(err, response) { - assert.error(err, 'testException: no callback error'); - assert.ok(!Boolean(response), 'testException: no response'); + client.testException("no Exception", function (err, response) { + assert.error(err, "testException: no callback error"); + assert.ok(!Boolean(response), "testException: no response"); }); - client.testOneway(0, function(err, response) { - assert.error(err, 'testOneway: no callback error'); - assert.strictEqual(response, undefined, 'testOneway: void response'); + client.testOneway(0, function (err, response) { + assert.error(err, "testOneway: no callback error"); + assert.strictEqual(response, undefined, "testOneway: void response"); }); - checkOffByOne(function(done) { - client.testI32(-1, function(err, response) { + checkOffByOne(function (done) { + client.testI32(-1, function (err, response) { assert.error(err, "checkOffByOne: no callback error"); assert.equal(-1, response); assert.end(); done(); }); }, callback); - }); -}; - -export function ThriftTestDriverPromise(client: ThriftTest.Client, callback: (status: string) => void) { - - test("Q Promise Client Tests", function(assert) { +} +export function ThriftTestDriverPromise( + client: ThriftTest.Client, + callback: (status: string) => void, +) { + test("Q Promise Client Tests", function (assert) { var checkRecursively = makeRecursiveCheck(assert); function fail(msg: string) { - return function(error, response) { + return function (error, response) { if (error !== null) { assert.fail(msg); } - } + }; } function makeAsserter(assertionFn: (a: any, b: any, msg?: string) => void) { - return function(c: (string | any)[]) { + return function (c: (string | any)[]) { var fnName = c[0]; var expected = c[1]; - (client)[fnName](expected) - .then(function(actual: any) { + (client) + [fnName](expected) + .then(function (actual: any) { assertionFn(actual, expected, fnName); }) .fail(fail("fnName")); @@ -143,73 +154,73 @@ export function ThriftTestDriverPromise(client: ThriftTest.Client, callback: (st } testCases.simple.forEach(makeAsserter(assert.equal)); - testCases.simpleLoose.forEach(makeAsserter(function(a, e, m){ - assert.ok(a == e, m); - })); + testCases.simpleLoose.forEach( + makeAsserter(function (a, e, m) { + assert.ok(a == e, m); + }), + ); testCases.deep.forEach(makeAsserter(assert.deepEqual)); Q.resolve(client.testStruct(testCases.out)) - .then(function(response) { + .then(function (response) { checkRecursively(testCases.out, response, "testStruct"); }) .fail(fail("testStruct")); Q.resolve(client.testNest(testCases.out2)) - .then(function(response) { + .then(function (response) { checkRecursively(testCases.out2, response, "testNest"); }) .fail(fail("testNest")); Q.resolve(client.testInsanity(testCases.crazy)) - .then(function(response) { + .then(function (response) { checkRecursively(testCases.insanity, response, "testInsanity"); }) .fail(fail("testInsanity")); Q.resolve(client.testException("TException")) - .then(function(response) { + .then(function (response) { fail("testException: TException"); }) - .fail(function(err) { + .fail(function (err) { assert.ok(err instanceof TException); }); Q.resolve(client.testException("Xception")) - .then(function(response) { + .then(function (response) { fail("testException: Xception"); }) - .fail(function(err) { + .fail(function (err) { assert.ok(err instanceof ttypes.Xception); assert.equal(err.errorCode, 1001); assert.equal("Xception", err.message); }); Q.resolve(client.testException("no Exception")) - .then(function(response) { + .then(function (response) { assert.equal(undefined, response); //void }) .fail(fail("testException")); client.testOneway(0, fail("testOneway: should not answer")); - checkOffByOne(function(done) { + checkOffByOne(function (done) { Q.resolve(client.testI32(-1)) - .then(function(response) { - assert.equal(-1, response); - assert.end(); - done(); + .then(function (response) { + assert.equal(-1, response); + assert.end(); + done(); }) .fail(fail("checkOffByOne")); }, callback); }); -}; - +} // Helper Functions // ========================================================= function makeRecursiveCheck(assert: test.Test) { - return function (map1: any, map2: any, msg: string) { var equal = true; @@ -218,30 +229,37 @@ function makeRecursiveCheck(assert: test.Test) { assert.ok(equal, msg); // deepEqual doesn't work with fields using node-int64 - function checkRecursively(map1: any, map2: any) : boolean { + function checkRecursively(map1: any, map2: any): boolean { if (!(typeof map1 !== "function" && typeof map2 !== "function")) { return false; } if (!map1 || typeof map1 !== "object") { //Handle int64 types (which use node-int64 in Node.js JavaScript) - if ((typeof map1 === "number") && (typeof map2 === "object") && - (map2.buffer) && (map2.buffer instanceof Buffer) && (map2.buffer.length === 8)) { + if ( + typeof map1 === "number" && + typeof map2 === "object" && + map2.buffer && + map2.buffer instanceof Buffer && + map2.buffer.length === 8 + ) { var n = new Int64(map2.buffer); return map1 === n.toNumber(); } else { return map1 == map2; } } else { - return Object.keys(map1).every(function(key) { + return Object.keys(map1).every(function (key) { return checkRecursively(map1[key], map2[key]); }); } } - } + }; } -function checkOffByOne(done: (callback: () => void) => void, callback: (message: string) => void) { - +function checkOffByOne( + done: (callback: () => void) => void, + callback: (message: string) => void, +) { var retry_limit = 30; var retry_interval = 100; var test_complete = false; @@ -256,20 +274,23 @@ function checkOffByOne(done: (callback: () => void) => void, callback: (message: * Because this is the last test against the server, when it completes * the entire suite is complete by definition (the tests run serially). */ - done(function() { + done(function () { test_complete = true; }); //We wait up to retry_limit * retry_interval for the test suite to complete function TestForCompletion() { - if(test_complete && callback) { + if (test_complete && callback) { callback("Server successfully tested!"); } else { if (++retrys < retry_limit) { setTimeout(TestForCompletion, retry_interval); } else if (callback) { - callback("Server test failed to complete after " + - (retry_limit * retry_interval / 1000) + " seconds"); + callback( + "Server test failed to complete after " + + (retry_limit * retry_interval) / 1000 + + " seconds", + ); } } } diff --git a/lib/nodets/test/test_handler.ts b/lib/nodets/test/test_handler.ts index 996c32a5a32..823b4e7ee03 100644 --- a/lib/nodets/test/test_handler.ts +++ b/lib/nodets/test/test_handler.ts @@ -26,7 +26,6 @@ import Thrift = thrift.Thrift; import Q = require("q"); import Int64 = require("node-int64"); - export class SyncThriftTestHandler { testVoid(): Q.IPromise { //console.log('testVoid()'); @@ -35,9 +34,9 @@ export class SyncThriftTestHandler { testMapMap(hello: number) { //console.log('testMapMap(' + hello + ')'); - var mapmap: {[key: number]: {[key: number]: number; }} = []; - var pos: {[key: number]: number; } = []; - var neg: {[key: number]: number; } = []; + var mapmap: { [key: number]: { [key: number]: number } } = []; + var pos: { [key: number]: number } = []; + var neg: { [key: number]: number } = []; for (var i = 1; i < 5; i++) { pos[i] = i; neg[-i] = -i; @@ -47,53 +46,60 @@ export class SyncThriftTestHandler { return Q.resolve(mapmap); } - testInsanity(argument: ttypes.Insanity): Q.IPromise<{ [k: number]: any; }> { - const first_map: { [k: number]: any; } = []; - const second_map: { [k: number]: any; } = []; - + testInsanity(argument: ttypes.Insanity): Q.IPromise<{ [k: number]: any }> { + const first_map: { [k: number]: any } = []; + const second_map: { [k: number]: any } = []; + first_map[ttypes.Numberz.TWO] = argument; first_map[ttypes.Numberz.THREE] = argument; - + const looney = new ttypes.Insanity(); second_map[ttypes.Numberz.SIX] = looney; - - const insane: { [k: number]: any; } = []; + + const insane: { [k: number]: any } = []; insane[1] = first_map; insane[2] = second_map; return Q.resolve(insane); } - testMulti(arg0: any, arg1: number, arg2: Int64, arg3: { [k: number]: string; }, arg4: ttypes.Numberz, arg5: number) { + testMulti( + arg0: any, + arg1: number, + arg2: Int64, + arg3: { [k: number]: string }, + arg4: ttypes.Numberz, + arg5: number, + ) { var hello = new ttypes.Xtruct(); - hello.string_thing = 'Hello2'; + hello.string_thing = "Hello2"; hello.byte_thing = arg0; hello.i32_thing = arg1; hello.i64_thing = arg2; return Q.resolve(hello); } testException(arg: string): Q.IPromise { - if (arg === 'Xception') { + if (arg === "Xception") { var x = new ttypes.Xception(); x.errorCode = 1001; x.message = arg; throw x; - } else if (arg === 'TException') { + } else if (arg === "TException") { throw new Thrift.TException(arg); } else { return Q.resolve(); } } testMultiException(arg0: string, arg1: string) { - if (arg0 === ('Xception')) { + if (arg0 === "Xception") { var x = new ttypes.Xception(); x.errorCode = 1001; - x.message = 'This is an Xception'; + x.message = "This is an Xception"; throw x; - } else if (arg0 === ('Xception2')) { + } else if (arg0 === "Xception2") { var x2 = new ttypes.Xception2(); x2.errorCode = 2002; x2.struct_thing = new ttypes.Xtruct(); - x2.struct_thing.string_thing = 'This is an Xception2'; + x2.struct_thing.string_thing = "This is an Xception2"; throw x2; } @@ -101,8 +107,7 @@ export class SyncThriftTestHandler { res.string_thing = arg1; return Q.resolve(res); } - testOneway(sleepFor: number) { - } + testOneway(sleepFor: number) {} testString(thing: string) { return Q.resolve(thing); @@ -131,10 +136,10 @@ export class SyncThriftTestHandler { testNest(thing: ttypes.Xtruct2) { return Q.resolve(thing); } - testMap(thing: { [k: number]: number; }) { + testMap(thing: { [k: number]: number }) { return Q.resolve(thing); } - testStringMap(thing: { [k: string]: string; }) { + testStringMap(thing: { [k: string]: string }) { return Q.resolve(thing); } testSet(thing: number[]) { @@ -161,13 +166,16 @@ export class AsyncThriftTestHandler { callback(undefined); return Q.resolve(); } - testMapMap(hello: number, - callback: (err: any, result: { [k: number]: { [k: number]: number; }; }) => void): - Q.IPromise<{ [k: number]: { [k: number]: number; }; }> { - - var mapmap: {[key: number]: {[key: number]: number; }} = []; - var pos: {[key: number]: number; } = []; - var neg: {[key: number]: number; } = []; + testMapMap( + hello: number, + callback: ( + err: any, + result: { [k: number]: { [k: number]: number } }, + ) => void, + ): Q.IPromise<{ [k: number]: { [k: number]: number } }> { + var mapmap: { [key: number]: { [key: number]: number } } = []; + var pos: { [key: number]: number } = []; + var neg: { [key: number]: number } = []; for (var i = 1; i < 5; i++) { pos[i] = i; neg[-i] = -i; @@ -178,54 +186,69 @@ export class AsyncThriftTestHandler { callback(null, mapmap); return Q.resolve(); } - testInsanity(argument: ttypes.Insanity, callback?: (err: any, result: { [k: number]: any; }) => void): Q.IPromise<{ [k: number]: any; }> { - const first_map: { [k: number]: any; } = []; - const second_map: { [k: number]: any; } = []; - + testInsanity( + argument: ttypes.Insanity, + callback?: (err: any, result: { [k: number]: any }) => void, + ): Q.IPromise<{ [k: number]: any }> { + const first_map: { [k: number]: any } = []; + const second_map: { [k: number]: any } = []; + first_map[ttypes.Numberz.TWO] = argument; first_map[ttypes.Numberz.THREE] = argument; - + const looney = new ttypes.Insanity(); second_map[ttypes.Numberz.SIX] = looney; - - const insane: { [k: number]: any; } = []; + + const insane: { [k: number]: any } = []; insane[1] = first_map; insane[2] = second_map; - if (callback !== undefined){ + if (callback !== undefined) { callback(null, insane); } return Q.resolve(); } - testMulti(arg0: any, arg1: number, arg2: Int64, arg3: { [k: number]: string; }, arg4: ttypes.Numberz, arg5: number, result: Function): Q.IPromise { + testMulti( + arg0: any, + arg1: number, + arg2: Int64, + arg3: { [k: number]: string }, + arg4: ttypes.Numberz, + arg5: number, + result: Function, + ): Q.IPromise { var hello = this.syncHandler.testMulti(arg0, arg1, arg2, arg3, arg4, arg5); - hello.then(hello => result(null, hello)); + hello.then((hello) => result(null, hello)); return Q.resolve(); } testException(arg: string, result: (err: any) => void): Q.IPromise { - if (arg === 'Xception') { + if (arg === "Xception") { var x = new ttypes.Xception(); x.errorCode = 1001; x.message = arg; result(x); - } else if (arg === 'TException') { + } else if (arg === "TException") { result(new Thrift.TException(arg)); } else { result(null); } return Q.resolve(); } - testMultiException(arg0: string, arg1: string, result: (err: any, res?: ttypes.Xtruct) => void): Q.IPromise { - if (arg0 === ('Xception')) { + testMultiException( + arg0: string, + arg1: string, + result: (err: any, res?: ttypes.Xtruct) => void, + ): Q.IPromise { + if (arg0 === "Xception") { var x = new ttypes.Xception(); x.errorCode = 1001; - x.message = 'This is an Xception'; + x.message = "This is an Xception"; result(x); - } else if (arg0 === ('Xception2')) { + } else if (arg0 === "Xception2") { var x2 = new ttypes.Xception2(); x2.errorCode = 2002; x2.struct_thing = new ttypes.Xtruct(); - x2.struct_thing.string_thing = 'This is an Xception2'; + x2.struct_thing.string_thing = "This is an Xception2"; result(x2); } else { var res = new ttypes.Xtruct(); @@ -237,63 +260,108 @@ export class AsyncThriftTestHandler { testOneway(sleepFor: number, result: Function) { this.syncHandler.testOneway(sleepFor); } - testString(thing: string, callback: (err: any, result: string) => void): Q.IPromise { + testString( + thing: string, + callback: (err: any, result: string) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testByte(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + testByte( + thing: number, + callback: (err: any, result: number) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testBool(thing: boolean, callback: (err: any, result: boolean) => void ): Q.IPromise { + testBool( + thing: boolean, + callback: (err: any, result: boolean) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testI32(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + testI32( + thing: number, + callback: (err: any, result: number) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testI64(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + testI64( + thing: number, + callback: (err: any, result: number) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testDouble(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + testDouble( + thing: number, + callback: (err: any, result: number) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testBinary(thing: Buffer, callback: (err: any, result: Buffer) => void): Q.IPromise { + testBinary( + thing: Buffer, + callback: (err: any, result: Buffer) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testStruct(thing: ttypes.Xtruct, callback: (err: any, result: ttypes.Xtruct) => void): Q.IPromise { + testStruct( + thing: ttypes.Xtruct, + callback: (err: any, result: ttypes.Xtruct) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testNest(thing: ttypes.Xtruct2, callback: (err: any, result: ttypes.Xtruct2) => void): Q.IPromise { + testNest( + thing: ttypes.Xtruct2, + callback: (err: any, result: ttypes.Xtruct2) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testMap(thing: { [k: number]: number; }, callback: (err: any, result: { [k: number]: number; }) => void): Q.IPromise<{ [k: number]: number; }> { + testMap( + thing: { [k: number]: number }, + callback: (err: any, result: { [k: number]: number }) => void, + ): Q.IPromise<{ [k: number]: number }> { callback(null, thing); return Q.resolve(); } - testStringMap(thing: { [k: string]: string; }, callback: (err: any, result: { [k: string]: string; }) => void): Q.IPromise<{ [k: string]: string; }> { + testStringMap( + thing: { [k: string]: string }, + callback: (err: any, result: { [k: string]: string }) => void, + ): Q.IPromise<{ [k: string]: string }> { callback(null, thing); return Q.resolve(); } - testSet(thing: number[], callback: (err: any, result: number[]) => void): Q.IPromise { + testSet( + thing: number[], + callback: (err: any, result: number[]) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testList(thing: number[], callback: (err: any, result: number[]) => void): Q.IPromise { + testList( + thing: number[], + callback: (err: any, result: number[]) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testEnum(thing: ttypes.Numberz, callback: (err: any, result: ttypes.Numberz) => void): Q.IPromise { + testEnum( + thing: ttypes.Numberz, + callback: (err: any, result: ttypes.Numberz) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } - testTypedef(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + testTypedef( + thing: number, + callback: (err: any, result: number) => void, + ): Q.IPromise { callback(null, thing); return Q.resolve(); } diff --git a/lib/py/setup.py b/lib/py/setup.py index 066483e19de..2a170a411cc 100644 --- a/lib/py/setup.py +++ b/lib/py/setup.py @@ -97,8 +97,6 @@ def run_setup(with_binary): extensions = dict() ssl_deps = [] - if sys.version_info[0] == 2: - ssl_deps.append('ipaddress') if sys.hexversion < 0x03050000: ssl_deps.append('backports.ssl_match_hostname>=3.5') tornado_deps = ['tornado>=4.0'] diff --git a/lib/py/src/TRecursive.py b/lib/py/src/TRecursive.py index abf202cb1eb..aed696ad993 100644 --- a/lib/py/src/TRecursive.py +++ b/lib/py/src/TRecursive.py @@ -10,11 +10,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function -from __future__ import unicode_literals - from thrift.Thrift import TType TYPE_IDX = 1 diff --git a/lib/py/src/TTornado.py b/lib/py/src/TTornado.py index 5eff11d2d85..c409e09eb4c 100644 --- a/lib/py/src/TTornado.py +++ b/lib/py/src/TTornado.py @@ -17,7 +17,6 @@ # under the License. # -from __future__ import absolute_import import logging import socket import struct @@ -34,7 +33,7 @@ logger = logging.getLogger(__name__) -class _Lock(object): +class _Lock: def __init__(self): self._waiters = deque() diff --git a/lib/py/src/compat.py b/lib/py/src/compat.py index 0e8271dc193..3b3d57f56e5 100644 --- a/lib/py/src/compat.py +++ b/lib/py/src/compat.py @@ -17,30 +17,13 @@ # under the License. # -import sys +from io import BytesIO as BufferIO # noqa -if sys.version_info[0] == 2: +def binary_to_str(bin_val): + return bin_val.decode('utf8') - from cStringIO import StringIO as BufferIO +def str_to_binary(str_val): + return bytes(str_val, 'utf8') - def binary_to_str(bin_val): - return bin_val - - def str_to_binary(str_val): - return str_val - - def byte_index(bytes_val, i): - return ord(bytes_val[i]) - -else: - - from io import BytesIO as BufferIO # noqa - - def binary_to_str(bin_val): - return bin_val.decode('utf8') - - def str_to_binary(str_val): - return bytes(str_val, 'utf8') - - def byte_index(bytes_val, i): - return bytes_val[i] +def byte_index(bytes_val, i): + return bytes_val[i] diff --git a/lib/py/src/protocol/TJSONProtocol.py b/lib/py/src/protocol/TJSONProtocol.py index 17417027a0a..fef0cc9422b 100644 --- a/lib/py/src/protocol/TJSONProtocol.py +++ b/lib/py/src/protocol/TJSONProtocol.py @@ -263,19 +263,11 @@ def _isLowSurrogate(self, codeunit): def _toChar(self, high, low=None): if not low: - if sys.version_info[0] == 2: - return ("\\u%04x" % high).decode('unicode-escape') \ - .encode('utf-8') - else: - return chr(high) + return chr(high) else: codepoint = (1 << 16) + ((high & 0x3ff) << 10) codepoint += low & 0x3ff - if sys.version_info[0] == 2: - s = "\\U%08x" % codepoint - return s.decode('unicode-escape').encode('utf-8') - else: - return chr(codepoint) + return chr(codepoint) def readJSONString(self, skipContext): highSurrogate = None @@ -317,7 +309,7 @@ def readJSONString(self, skipContext): elif character in ESCAPE_CHAR_VALS: raise TProtocolException(TProtocolException.INVALID_DATA, "Unescaped control char") - elif sys.version_info[0] > 2: + else: utf8_bytes = bytearray([ord(character)]) while ord(self.reader.peek()) >= 0x80: utf8_bytes.append(ord(self.reader.read())) diff --git a/lib/py/src/protocol/TProtocol.py b/lib/py/src/protocol/TProtocol.py index bac54aece9d..ec71ab3aa72 100644 --- a/lib/py/src/protocol/TProtocol.py +++ b/lib/py/src/protocol/TProtocol.py @@ -261,11 +261,6 @@ def _ttype_handlers(self, ttype, spec): raise TProtocolException(type=TProtocolException.INVALID_DATA, message='Invalid binary field type %d' % ttype) return ('readBinary', 'writeBinary', False) - if sys.version_info[0] == 2 and spec == 'UTF8': - if ttype != TType.STRING: - raise TProtocolException(type=TProtocolException.INVALID_DATA, - message='Invalid string field type %d' % ttype) - return ('readUtf8', 'writeUtf8', False) return self._TTYPE_HANDLERS[ttype] if ttype < len(self._TTYPE_HANDLERS) else (None, None, False) def _read_by_ttype(self, ttype, spec, espec): diff --git a/lib/py/src/transport/TTransport.py b/lib/py/src/transport/TTransport.py index ff20d7ec99b..a686b1231c6 100644 --- a/lib/py/src/transport/TTransport.py +++ b/lib/py/src/transport/TTransport.py @@ -17,9 +17,10 @@ # under the License. # +from io import BytesIO as BufferIO + from struct import pack, unpack from thrift.Thrift import TException -from ..compat import BufferIO class TTransportException(TException): diff --git a/lib/py/src/transport/TZlibTransport.py b/lib/py/src/transport/TZlibTransport.py index e8485792464..8b08297645d 100644 --- a/lib/py/src/transport/TZlibTransport.py +++ b/lib/py/src/transport/TZlibTransport.py @@ -22,13 +22,12 @@ data compression. """ -from __future__ import division import zlib from .TTransport import TTransportBase, CReadableTransport from ..compat import BufferIO -class TZlibTransportFactory(object): +class TZlibTransportFactory: """Factory transport that builds zlib compressed transports. This factory caches the last single client/transport that it was passed diff --git a/lib/py/test/thrift_json.py b/lib/py/test/thrift_json.py index 125ea59f6c7..5a491e2c495 100644 --- a/lib/py/test/thrift_json.py +++ b/lib/py/test/thrift_json.py @@ -42,8 +42,6 @@ def test_escaped_unicode_string(self): transport = TTransport.TBufferedTransportFactory().getTransport(buf) protocol = TJSONProtocol(transport) - if sys.version_info[0] == 2: - unicode_text = unicode_text.encode('utf8') self.assertEqual(protocol.readString(), unicode_text) def test_TJSONProtocol_write(self): diff --git a/lib/rs/src/protocol/compact.rs b/lib/rs/src/protocol/compact.rs index 8ed4e0635e4..4dc45cac2fd 100644 --- a/lib/rs/src/protocol/compact.rs +++ b/lib/rs/src/protocol/compact.rs @@ -210,6 +210,10 @@ where None => { let b = self.read_byte()?; match b { + // Previous versions of the thrift compact protocol specification said to use 0 + // and 1 inside collections, but that differed from existing implementations. + // The specification was updated in https://github.com/apache/thrift/commit/2c29c5665bc442e703480bb0ee60fe925ffe02e8. + 0x00 => Ok(false), 0x01 => Ok(true), 0x02 => Ok(false), unkn => Err(crate::Error::Protocol(crate::ProtocolError { @@ -652,7 +656,11 @@ fn type_to_u8(field_type: TType) -> u8 { fn collection_u8_to_type(b: u8) -> crate::Result { match b { - 0x01 => Ok(TType::Bool), + // For historical and compatibility reasons, a reader should be capable to deal with both cases. + // The only valid value in the original spec was 2, but due to a widespread implementation bug + // the defacto standard across large parts of the library became 1 instead. + // As a result, both values are now allowed. + 0x01 | 0x02 => Ok(TType::Bool), o => u8_to_type(o), } } @@ -2839,4 +2847,40 @@ mod tests { assert!(write_fn(&mut o_prot).is_ok()); assert_eq!(o_prot.transport.write_bytes().len(), 0); } + + #[test] + fn must_read_boolean_list() { + let (mut i_prot, _) = test_objects(); + + let source_bytes: [u8; 3] = [0x21, 2, 1]; + + i_prot.transport.set_readable_bytes(&source_bytes); + + let (ttype, element_count) = assert_success!(i_prot.read_list_set_begin()); + + assert_eq!(ttype, TType::Bool); + assert_eq!(element_count, 2); + assert_eq!(i_prot.read_bool().unwrap(), false); + assert_eq!(i_prot.read_bool().unwrap(), true); + + assert_success!(i_prot.read_list_end()); + } + + #[test] + fn must_read_boolean_list_alternative_encoding() { + let (mut i_prot, _) = test_objects(); + + let source_bytes: [u8; 3] = [0x22, 0, 1]; + + i_prot.transport.set_readable_bytes(&source_bytes); + + let (ttype, element_count) = assert_success!(i_prot.read_list_set_begin()); + + assert_eq!(ttype, TType::Bool); + assert_eq!(element_count, 2); + assert_eq!(i_prot.read_bool().unwrap(), false); + assert_eq!(i_prot.read_bool().unwrap(), true); + + assert_success!(i_prot.read_list_end()); + } } diff --git a/lib/ts/Gruntfile.js b/lib/ts/Gruntfile.js index 61ab582741d..3e4b1c49227 100644 --- a/lib/ts/Gruntfile.js +++ b/lib/ts/Gruntfile.js @@ -5,55 +5,57 @@ // Grunt Setup - npm install //reads the ./package.json and installs project dependencies // Run grunt - npx grunt // uses project-local installed version of grunt (from package.json) -module.exports = function(grunt) { - 'use strict'; +module.exports = function (grunt) { + "use strict"; grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), + pkg: grunt.file.readJSON("package.json"), concat: { options: { - separator: ';' + separator: ";", }, dist: { - src: ['src/**/*.js'], - dest: 'dist/<%= pkg.name %>.js' - } + src: ["src/**/*.js"], + dest: "dist/<%= pkg.name %>.js", + }, }, shell: { InstallThriftJS: { - command: 'mkdir -p test/build/ts/lib; cp ../js/src/thrift.js test/build/ts/thrift.js' + command: + "mkdir -p test/build/ts/lib; cp ../js/src/thrift.js test/build/ts/thrift.js", }, InstallThriftNodeJSDep: { - command: 'cd ../..; npm install' + command: "cd ../..; npm install", }, InstallTestLibs: { - command: 'cd test; ant download_jslibs' + command: "cd test; ant download_jslibs", }, ThriftGen: { command: [ - 'mkdir -p test/gen-js', - '../../compiler/cpp/thrift -gen js:ts --out test/gen-js ../../test/v0.16/ThriftTest.thrift', - 'mkdir -p test/gen-nodejs', - '../../compiler/cpp/thrift -gen js:node,ts --out test/gen-nodejs ../../test/v0.16/ThriftTest.thrift', - ].join(' && ') + "mkdir -p test/gen-js", + "../../compiler/cpp/thrift -gen js:ts --out test/gen-js ../../test/v0.16/ThriftTest.thrift", + "mkdir -p test/gen-nodejs", + "../../compiler/cpp/thrift -gen js:node,ts --out test/gen-nodejs ../../test/v0.16/ThriftTest.thrift", + ].join(" && "), }, ThriftBrowserifyNodeInt64: { command: [ - './node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js', - './node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js', - './node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js' - ].join(' && ') + "./node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js", + "./node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js", + "./node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js", + ].join(" && "), }, ThriftGenInt64: { - command: '../../compiler/cpp/thrift -gen js:ts -o test ../../test/Int64Test.thrift' + command: + "../../compiler/cpp/thrift -gen js:ts -o test ../../test/Int64Test.thrift", }, ThriftTestServer: { options: { async: true, execOptions: { cwd: "./test", - env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} - } + env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" }, + }, }, command: "node server_http.js", }, @@ -61,103 +63,104 @@ module.exports = function(grunt) { options: { execOptions: { cwd: "./test", - } + }, }, - command : "../node_modules/typescript/bin/tsc --listFiles --outDir build/ts" + command: + "../node_modules/typescript/bin/tsc --listFiles --outDir build/ts", }, BrowserifyCompiledTS: { command: [ "./node_modules/browserify/bin/cmd.js test/build/ts/test.js -o test/build/ts/lib/test.js --standalone test", "./node_modules/browserify/bin/cmd.js test/build/ts/test-int64.js -o test/build/ts/lib/test-int64.js --standalone testInt64", - ].join(" && ") + ].join(" && "), }, InstallGeneratedCode: { command: [ "mkdir -p test/build/ts", - "cp -r test/gen-js test/build/ts" - ].join(" && ") + "cp -r test/gen-js test/build/ts", + ].join(" && "), }, }, qunit: { ThriftJS: { options: { - urls: [ - 'http://localhost:8089/test.html' - ], + urls: ["http://localhost:8089/test.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], }, - } + }, }, ThriftJS_Int64: { options: { - urls: [ - 'http://localhost:8089/test-int64.html' - ], + urls: ["http://localhost:8089/test-int64.html"], puppeteer: { headless: true, - args: ['--no-sandbox'], + args: ["--no-sandbox"], ignoreHTTPSErrors: true, }, - } + }, }, }, jshint: { // The main Thrift library file. not es6 yet :( lib: { - src: ['../js/src/**/*.js'], + src: ["../js/src/**/*.js"], }, // The test files use es6 test: { - src: ['Gruntfile.js', 'test/*.js'], + src: ["Gruntfile.js", "test/*.js"], options: { esversion: 6, - } + }, }, gen_js_code: { - src: ['test/gen-js/*.js'], + src: ["test/gen-js/*.js"], }, gen_node_code: { - src: ['test/gen-nodejs/*.js'], + src: ["test/gen-nodejs/*.js"], options: { node: true, - } + }, }, }, }); - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-contrib-qunit'); - grunt.loadNpmTasks('grunt-shell-spawn'); + grunt.loadNpmTasks("grunt-contrib-jshint"); + grunt.loadNpmTasks("grunt-contrib-qunit"); + grunt.loadNpmTasks("grunt-shell-spawn"); - grunt.registerTask('wait', 'Wait just one second for the server to start', function () { - var done = this.async(); - setTimeout(function() { - done(true); - }, 1000); - }); + grunt.registerTask( + "wait", + "Wait just one second for the server to start", + function () { + var done = this.async(); + setTimeout(function () { + done(true); + }, 1000); + }, + ); - grunt.registerTask('installAndGenerate', [ - 'shell:InstallThriftJS', - 'shell:InstallThriftNodeJSDep', - 'shell:ThriftGen', - 'shell:ThriftBrowserifyNodeInt64', - 'shell:ThriftGenInt64', - 'shell:InstallTestLibs', - 'shell:BuildTS', - 'shell:InstallGeneratedCode', - 'shell:BrowserifyCompiledTS', + grunt.registerTask("installAndGenerate", [ + "shell:InstallThriftJS", + "shell:InstallThriftNodeJSDep", + "shell:ThriftGen", + "shell:ThriftBrowserifyNodeInt64", + "shell:ThriftGenInt64", + "shell:InstallTestLibs", + "shell:BuildTS", + "shell:InstallGeneratedCode", + "shell:BrowserifyCompiledTS", ]); - grunt.registerTask('test', [ - 'installAndGenerate', - 'jshint', - 'shell:ThriftTestServer', - 'wait', - 'qunit:ThriftJS', - 'qunit:ThriftJS_Int64', - 'shell:ThriftTestServer:kill', + grunt.registerTask("test", [ + "installAndGenerate", + "jshint", + "shell:ThriftTestServer", + "wait", + "qunit:ThriftJS", + "qunit:ThriftJS_Int64", + "shell:ThriftTestServer:kill", ]); - grunt.registerTask('default', ['test']); + grunt.registerTask("default", ["test"]); }; diff --git a/lib/ts/test/phantom-client.ts b/lib/ts/test/phantom-client.ts index 55189372536..90a532d6ff8 100644 --- a/lib/ts/test/phantom-client.ts +++ b/lib/ts/test/phantom-client.ts @@ -16,337 +16,360 @@ * specific language governing permissions and limitations * under the License. */ - /* jshint -W100 */ +/* jshint -W100 */ import { ThriftTest } from "./gen-js/ThriftTest_types"; import "./gen-js/ThriftTest"; var Int64 = require("node-int64"); var phantom = require("phantom"); -const int64_2_pow_60: typeof Int64 = new Int64('1000000000000000'); -const int64_minus_2_pow_60: typeof Int64 = new Int64('f000000000000000'); - - (function() { - 'use strict'; - - // Rudimentary test helper functions - // TODO: Return error code based on kind of errors rather than throw - var ok = function(t, msg) { - if (!t) { - console.log('*** FAILED ***'); - throw new Error(msg); - } - }; - var equal = function(a, b) { - if (a !== b) { - console.log('*** FAILED ***'); - throw new Error(); - } - }; - var test = function(name, f) { - console.log('TEST : ' + name); - f(); - console.log('OK\n'); +const int64_2_pow_60: typeof Int64 = new Int64("1000000000000000"); +const int64_minus_2_pow_60: typeof Int64 = new Int64("f000000000000000"); + +(function () { + "use strict"; + + // Rudimentary test helper functions + // TODO: Return error code based on kind of errors rather than throw + var ok = function (t, msg) { + if (!t) { + console.log("*** FAILED ***"); + throw new Error(msg); + } + }; + var equal = function (a, b) { + if (a !== b) { + console.log("*** FAILED ***"); + throw new Error(); + } + }; + var test = function (name, f) { + console.log("TEST : " + name); + f(); + console.log("OK\n"); + }; + + var parseArgs = function (args) { + var skips = ["--transport=http", "--protocol=json"]; + var opts = { + port: "9090", + // protocol: 'json', }; - - var parseArgs = function(args) { - var skips = [ - '--transport=http', - '--protocol=json' - ]; - var opts = { - port: '9090' - // protocol: 'json', - }; - var keys = {}; - for (var key in opts) { - keys['--' + key + '='] = key; + var keys = {}; + for (var key in opts) { + keys["--" + key + "="] = key; + } + for (var i in args) { + var arg = args[i]; + if (skips.indexOf(arg) != -1) { + continue; } - for (var i in args) { - var arg = args[i]; - if (skips.indexOf(arg) != -1) { - continue; - } - var hit = false; - for (var k in keys) { - if (arg.slice(0, k.length) === k) { - opts[keys[k]] = arg.slice(k.length); - hit = true; - break; - } - } - if (!hit) { - throw new Error('Unknown argument: ' + arg); + var hit = false; + for (var k in keys) { + if (arg.slice(0, k.length) === k) { + opts[keys[k]] = arg.slice(k.length); + hit = true; + break; } } - var portAsInt: number = parseInt(opts.port, 10); - if (!opts.port || portAsInt < 1 || portAsInt > 65535) { - throw new Error('Invalid port number'); + if (!hit) { + throw new Error("Unknown argument: " + arg); } - return opts; - }; - - var execute = function() { - console.log('### Apache Thrift Javascript standalone test client'); - console.log('------------------------------------------------------------'); - - phantom.page.injectJs('thrift.js'); - phantom.page.injectJs('gen-js/ThriftTest_types.js'); - phantom.page.injectJs('gen-js/ThriftTest.js'); - - var system = require('system'); - var opts = parseArgs(system.args.slice(1)); - var port = opts.port; - var transport = new Thrift.Transport('http://localhost:' + port + '/service'); - var protocol = new Thrift.Protocol(transport); - var client = new ThriftTest.ThriftTestClient(protocol); - - - // TODO: Remove duplicate code with test.js. - // all Languages in UTF-8 - var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmål)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; - - function checkRecursively(map1, map2) { - if (typeof map1 !== 'function' && typeof map2 !== 'function') { - if (!map1 || typeof map1 !== 'object') { - equal(map1, map2); - } else { - for (var key in map1) { - checkRecursively(map1[key], map2[key]); - } + } + var portAsInt: number = parseInt(opts.port, 10); + if (!opts.port || portAsInt < 1 || portAsInt > 65535) { + throw new Error("Invalid port number"); + } + return opts; + }; + + var execute = function () { + console.log("### Apache Thrift Javascript standalone test client"); + console.log("------------------------------------------------------------"); + + phantom.page.injectJs("thrift.js"); + phantom.page.injectJs("gen-js/ThriftTest_types.js"); + phantom.page.injectJs("gen-js/ThriftTest.js"); + + var system = require("system"); + var opts = parseArgs(system.args.slice(1)); + var port = opts.port; + var transport = new Thrift.Transport( + "http://localhost:" + port + "/service", + ); + var protocol = new Thrift.Protocol(transport); + var client = new ThriftTest.ThriftTestClient(protocol); + + // TODO: Remove duplicate code with test.js. + // all Languages in UTF-8 + var stringTest = + "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmål)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; + + function checkRecursively(map1, map2) { + if (typeof map1 !== "function" && typeof map2 !== "function") { + if (!map1 || typeof map1 !== "object") { + equal(map1, map2); + } else { + for (var key in map1) { + checkRecursively(map1[key], map2[key]); } } } - - test('Void', function() { - equal(client.testVoid(), undefined); - }); - test('Binary (String)', function() { - var binary: string = ''; - for (var v = 255; v >= 0; --v) { - binary += String.fromCharCode(v); - } - equal(client.testBinary(binary), binary); - }); - test('Binary (Uint8Array)', function() { - var binary: string = ''; - for (var v = 255; v >= 0; --v) { - binary += String.fromCharCode(v); - } - var arr = new Uint8Array(binary.length); - for (var i = 0; i < binary.length; ++i) { - arr[i] = binary[i].charCodeAt(0); - } - const hexEncodedString = Array.from(arr, function(byte) { - return String.fromCharCode(byte); - }).join('') - equal(client.testBinary(hexEncodedString), binary); - }); - test('String', function() { - equal(client.testString(''), ''); - equal(client.testString(stringTest), stringTest); - - var specialCharacters = 'quote: \" backslash:' + - ' forwardslash-escaped: \/ ' + - ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + - ' now-all-of-them-together: "\\\/\b\n\r\t' + - ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><'; - equal(client.testString(specialCharacters), specialCharacters); - }); - test('Double', function() { - equal(client.testDouble(0), 0); - equal(client.testDouble(-1), -1); - equal(client.testDouble(3.14), 3.14); - equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60)); - }); - test('Bool', function() { - equal(client.testBool(true), true); - equal(client.testBool(false), false); - }); - test('I8', function() { - equal(client.testByte(0), 0); - equal(client.testByte(0x01), 0x01); - }); - test('I32', function() { - equal(client.testI32(0), 0); - equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30)); - equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30)); - }); - test('I64', function() { - equal(client.testI64(new Int64(0)), 0); - equal(client.testI64(int64_2_pow_60), Math.pow(2, 52)); - equal(client.testI64(int64_minus_2_pow_60), -Math.pow(2, 52)); - }); - - test('Struct', function() { - var structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); - structTestInput.string_thing = 'worked'; - structTestInput.byte_thing = 0x01; - structTestInput.i32_thing = Math.pow(2, 30); - structTestInput.i64_thing = int64_2_pow_60; - - var structTestOutput: ThriftTest.Xtruct = client.testStruct(structTestInput); - - equal(structTestOutput.string_thing, structTestInput.string_thing); - equal(structTestOutput.byte_thing, structTestInput.byte_thing); - equal(structTestOutput.i32_thing, structTestInput.i32_thing); - equal(structTestOutput.i64_thing, structTestInput.i64_thing); - - equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput)); - }); - - test('Nest', function() { - var xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); - xtrTestInput.string_thing = 'worked'; - xtrTestInput.byte_thing = 0x01; - xtrTestInput.i32_thing = Math.pow(2, 30); - xtrTestInput.i64_thing = int64_2_pow_60; - - var nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2(); - nestTestInput.byte_thing = 0x02; - nestTestInput.struct_thing = xtrTestInput; - nestTestInput.i32_thing = Math.pow(2, 15); - - var nestTestOutput = client.testNest(nestTestInput); - - equal(nestTestOutput.byte_thing, nestTestInput.byte_thing); - equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing); - equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing); - equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing); - equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing); - equal(nestTestOutput.i32_thing, nestTestInput.i32_thing); - - equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput)); - }); - - test('Map', function() { - var mapTestInput: {[k: number]: number;} = {7: 77, 8: 88, 9: 99}; - - var mapTestOutput: {[k: number]: number;} = client.testMap(mapTestInput); - - for (var key in mapTestOutput) { - equal(mapTestOutput[key], mapTestInput[key]); - } - }); - - test('StringMap', function() { - var mapTestInput: {[k: string]: string;} = { - 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key', - 'longValue': stringTest, stringTest: 'long key' - }; - - var mapTestOutput: {[k: string]: string;} = client.testStringMap(mapTestInput); - - for (var key in mapTestOutput) { - equal(mapTestOutput[key], mapTestInput[key]); - } - }); - - test('Set', function() { - var setTestInput: number[] = [1, 2, 3]; - ok(client.testSet(setTestInput), setTestInput); - }); - - test('List', function() { - var listTestInput: number[] = [1, 2, 3]; - ok(client.testList(listTestInput), listTestInput); - }); - - test('Enum', function() { - equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE); - }); - - test('TypeDef', function() { - equal(client.testTypedef(new Int64(69)), 69); - }); - - test('MapMap', function() { - var mapMapTestExpectedResult: {[K: number]: {[k: number]: number}} = { - '4': {'1': 1, '2': 2, '3': 3, '4': 4}, - '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1} - }; - - var mapMapTestOutput = client.testMapMap(1); - - - for (var key in mapMapTestOutput) { - for (var key2 in mapMapTestOutput[key]) { - equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]); - } - } - - checkRecursively(mapMapTestOutput, mapMapTestExpectedResult); - }); - - test('Xception', function() { - try { - client.testException('Xception'); - ok(false, "expected an exception but there was no exception"); - } catch (e) { - equal(e.errorCode, 1001); - equal(e.message, 'Xception'); - } - }); - - test('no Exception', function() { - try { - client.testException('no Exception'); - } catch (e) { - ok(false, "expected no exception but here was an exception"); - } - }); - - test('TException', function() { - try { - client.testException('TException'); - ok(false, "expected an exception but there was no exception"); - } catch (e) { - ok(ok, "succesfully got exception"); + } + + test("Void", function () { + equal(client.testVoid(), undefined); + }); + test("Binary (String)", function () { + var binary: string = ""; + for (var v = 255; v >= 0; --v) { + binary += String.fromCharCode(v); + } + equal(client.testBinary(binary), binary); + }); + test("Binary (Uint8Array)", function () { + var binary: string = ""; + for (var v = 255; v >= 0; --v) { + binary += String.fromCharCode(v); + } + var arr = new Uint8Array(binary.length); + for (var i = 0; i < binary.length; ++i) { + arr[i] = binary[i].charCodeAt(0); + } + const hexEncodedString = Array.from(arr, function (byte) { + return String.fromCharCode(byte); + }).join(""); + equal(client.testBinary(hexEncodedString), binary); + }); + test("String", function () { + equal(client.testString(""), ""); + equal(client.testString(stringTest), stringTest); + + var specialCharacters = + 'quote: \" backslash:' + + " forwardslash-escaped: \/ " + + " backspace: \b formfeed: \f newline: \n return: \r tab: " + + ' now-all-of-them-together: "\\\/\b\n\r\t' + + " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><"; + equal(client.testString(specialCharacters), specialCharacters); + }); + test("Double", function () { + equal(client.testDouble(0), 0); + equal(client.testDouble(-1), -1); + equal(client.testDouble(3.14), 3.14); + equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60)); + }); + test("Bool", function () { + equal(client.testBool(true), true); + equal(client.testBool(false), false); + }); + test("I8", function () { + equal(client.testByte(0), 0); + equal(client.testByte(0x01), 0x01); + }); + test("I32", function () { + equal(client.testI32(0), 0); + equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30)); + equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30)); + }); + test("I64", function () { + equal(client.testI64(new Int64(0)), 0); + equal(client.testI64(int64_2_pow_60), Math.pow(2, 52)); + equal(client.testI64(int64_minus_2_pow_60), -Math.pow(2, 52)); + }); + + test("Struct", function () { + var structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); + structTestInput.string_thing = "worked"; + structTestInput.byte_thing = 0x01; + structTestInput.i32_thing = Math.pow(2, 30); + structTestInput.i64_thing = int64_2_pow_60; + + var structTestOutput: ThriftTest.Xtruct = + client.testStruct(structTestInput); + + equal(structTestOutput.string_thing, structTestInput.string_thing); + equal(structTestOutput.byte_thing, structTestInput.byte_thing); + equal(structTestOutput.i32_thing, structTestInput.i32_thing); + equal(structTestOutput.i64_thing, structTestInput.i64_thing); + + equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput)); + }); + + test("Nest", function () { + var xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); + xtrTestInput.string_thing = "worked"; + xtrTestInput.byte_thing = 0x01; + xtrTestInput.i32_thing = Math.pow(2, 30); + xtrTestInput.i64_thing = int64_2_pow_60; + + var nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2(); + nestTestInput.byte_thing = 0x02; + nestTestInput.struct_thing = xtrTestInput; + nestTestInput.i32_thing = Math.pow(2, 15); + + var nestTestOutput = client.testNest(nestTestInput); + + equal(nestTestOutput.byte_thing, nestTestInput.byte_thing); + equal( + nestTestOutput.struct_thing.string_thing, + nestTestInput.struct_thing.string_thing, + ); + equal( + nestTestOutput.struct_thing.byte_thing, + nestTestInput.struct_thing.byte_thing, + ); + equal( + nestTestOutput.struct_thing.i32_thing, + nestTestInput.struct_thing.i32_thing, + ); + equal( + nestTestOutput.struct_thing.i64_thing, + nestTestInput.struct_thing.i64_thing, + ); + equal(nestTestOutput.i32_thing, nestTestInput.i32_thing); + + equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput)); + }); + + test("Map", function () { + var mapTestInput: { [k: number]: number } = { 7: 77, 8: 88, 9: 99 }; + + var mapTestOutput: { [k: number]: number } = client.testMap(mapTestInput); + + for (var key in mapTestOutput) { + equal(mapTestOutput[key], mapTestInput[key]); + } + }); + + test("StringMap", function () { + var mapTestInput: { [k: string]: string } = { + a: "123", + "a b": "with spaces ", + same: "same", + "0": "numeric key", + longValue: stringTest, + stringTest: "long key", + }; + + var mapTestOutput: { [k: string]: string } = + client.testStringMap(mapTestInput); + + for (var key in mapTestOutput) { + equal(mapTestOutput[key], mapTestInput[key]); + } + }); + + test("Set", function () { + var setTestInput: number[] = [1, 2, 3]; + ok(client.testSet(setTestInput), setTestInput); + }); + + test("List", function () { + var listTestInput: number[] = [1, 2, 3]; + ok(client.testList(listTestInput), listTestInput); + }); + + test("Enum", function () { + equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE); + }); + + test("TypeDef", function () { + equal(client.testTypedef(new Int64(69)), 69); + }); + + test("MapMap", function () { + var mapMapTestExpectedResult: { [K: number]: { [k: number]: number } } = { + "4": { "1": 1, "2": 2, "3": 3, "4": 4 }, + "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 }, + }; + + var mapMapTestOutput = client.testMapMap(1); + + for (var key in mapMapTestOutput) { + for (var key2 in mapMapTestOutput[key]) { + equal( + mapMapTestOutput[key][key2], + mapMapTestExpectedResult[key][key2], + ); } - }); - - const crazy: ThriftTest.Insanity = { - 'userMap': { '5': new Int64(5), '8': new Int64(8) }, - 'xtructs': [{ - 'string_thing': 'Goodbye4', - 'byte_thing': 4, - 'i32_thing': 4, - 'i64_thing': new Int64(4) + } + + checkRecursively(mapMapTestOutput, mapMapTestExpectedResult); + }); + + test("Xception", function () { + try { + client.testException("Xception"); + ok(false, "expected an exception but there was no exception"); + } catch (e) { + equal(e.errorCode, 1001); + equal(e.message, "Xception"); + } + }); + + test("no Exception", function () { + try { + client.testException("no Exception"); + } catch (e) { + ok(false, "expected no exception but here was an exception"); + } + }); + + test("TException", function () { + try { + client.testException("TException"); + ok(false, "expected an exception but there was no exception"); + } catch (e) { + ok(ok, "succesfully got exception"); + } + }); + + const crazy: ThriftTest.Insanity = { + userMap: { "5": new Int64(5), "8": new Int64(8) }, + xtructs: [ + { + string_thing: "Goodbye4", + byte_thing: 4, + i32_thing: 4, + i64_thing: new Int64(4), }, { - 'string_thing': 'Hello2', - 'byte_thing': 2, - 'i32_thing': 2, - 'i64_thing': new Int64(2) - }] - }; - test('Insanity', function() { - const insanity: {[k: number]: (ThriftTest.Insanity | {[k:number]: ThriftTest.Insanity})} = { - '1': { - '2': crazy, - '3': crazy - }, - '2': { '6': new ThriftTest.Insanity() } - }; - var res = client.testInsanity(new ThriftTest.Insanity(crazy)); - ok(res, JSON.stringify(res)); - ok(insanity, JSON.stringify(insanity)); - - checkRecursively(res, insanity); - }); - - console.log('------------------------------------------------------------'); - console.log('### All tests succeeded.'); - return 0; + string_thing: "Hello2", + byte_thing: 2, + i32_thing: 2, + i64_thing: new Int64(2), + }, + ], }; - - try { - var ret = execute(); - phantom.exit(ret); - } catch (err) { - // Catch all and exit to avoid hang. - console.error(err); - phantom.exit(1); - } - })(); - \ No newline at end of file + test("Insanity", function () { + const insanity: { + [k: number]: ThriftTest.Insanity | { [k: number]: ThriftTest.Insanity }; + } = { + "1": { + "2": crazy, + "3": crazy, + }, + "2": { "6": new ThriftTest.Insanity() }, + }; + var res = client.testInsanity(new ThriftTest.Insanity(crazy)); + ok(res, JSON.stringify(res)); + ok(insanity, JSON.stringify(insanity)); + + checkRecursively(res, insanity); + }); + + console.log("------------------------------------------------------------"); + console.log("### All tests succeeded."); + return 0; + }; + + try { + var ret = execute(); + phantom.exit(ret); + } catch (err) { + // Catch all and exit to avoid hang. + console.error(err); + phantom.exit(1); + } +})(); diff --git a/lib/ts/test/server_http.js b/lib/ts/test/server_http.js index 8380c3a7732..662a0a7b313 100644 --- a/lib/ts/test/server_http.js +++ b/lib/ts/test/server_http.js @@ -28,28 +28,30 @@ // for the es6 environment or for pre-es6 environment. // -const thrift = require('../../nodejs/lib/thrift'); -const es6Mode = process.argv.includes('--es6'); -const genFolder = es6Mode ? 'gen-nodejs-es6' : 'gen-nodejs'; +const thrift = require("../../nodejs/lib/thrift"); +const es6Mode = process.argv.includes("--es6"); +const genFolder = es6Mode ? "gen-nodejs-es6" : "gen-nodejs"; const ThriftTestSvc = require(`./${genFolder}/ThriftTest.js`); -const ThriftTestHandler = require('./test_handler').ThriftTestHandler; +const ThriftTestHandler = require("./test_handler").ThriftTestHandler; const ThriftTestSvcOpt = { - transport: thrift.TBufferedTransport, - protocol: thrift.TJSONProtocol, - processor: ThriftTestSvc, - handler: ThriftTestHandler + transport: thrift.TBufferedTransport, + protocol: thrift.TJSONProtocol, + processor: ThriftTestSvc, + handler: ThriftTestHandler, }; const ThriftWebServerOptions = { - files: __dirname, - services: { - '/service': ThriftTestSvcOpt - } + files: __dirname, + services: { + "/service": ThriftTestSvcOpt, + }, }; const server = thrift.createWebServer(ThriftWebServerOptions); const port = es6Mode ? 8088 : 8089; server.listen(port); console.log(`Serving files from: ${__dirname}`); -console.log(`Http/Thrift Server (ES6 mode ${es6Mode}) running on port: ${port}`); +console.log( + `Http/Thrift Server (ES6 mode ${es6Mode}) running on port: ${port}`, +); diff --git a/lib/ts/test/test-int64.ts b/lib/ts/test/test-int64.ts index 254d8d7bfcc..10e5946fc96 100644 --- a/lib/ts/test/test-int64.ts +++ b/lib/ts/test/test-int64.ts @@ -16,86 +16,90 @@ * specific language governing permissions and limitations * under the License. */ - /* jshint -W100 */ +/* jshint -W100 */ var Int64 = require("node-int64"); var JSONInt64 = require("json-int64"); import { Int64Test } from "./gen-js/Int64Test_types"; - // Work around for old API used by QUnitAdapter of jsTestDriver -if (typeof QUnit.log == 'function') { +if (typeof QUnit.log == "function") { // When using real QUnit (fron PhantomJS) log failures to console - QUnit.log(function(details) { + QUnit.log(function (details) { if (!details.result) { - console.log('======== FAIL ========'); - console.log('TestName: ' + details.name); + console.log("======== FAIL ========"); + console.log("TestName: " + details.name); if (details.message) console.log(details.message); - console.log('Expected: ' + details.expected); - console.log('Actual : ' + details.actual); - console.log('======================'); + console.log("Expected: " + details.expected); + console.log("Actual : " + details.actual); + console.log("======================"); } }); } -QUnit.module('Int64'); - - QUnit.test('Int64', function(assert) { - console.log('Int64 test -- starts'); - const EXPECTED_SMALL_INT64_AS_NUMBER: number = 42; - const EXPECTED_SMALL_INT64: typeof Int64 = new Int64(42); - const EXPECTED_MAX_JS_SAFE_INT64: typeof Int64 = new Int64(Number.MAX_SAFE_INTEGER); - const EXPECTED_MIN_JS_SAFE_INT64: typeof Int64 = new Int64(Number.MIN_SAFE_INTEGER); - const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: typeof Int64 = new Int64("0020000000000000"); // hex-encoded - const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: typeof Int64 = new Int64("ffe0000000000000"); // hex-encoded 2's complement - const EXPECTED_MAX_SIGNED_INT64: typeof Int64 = new Int64("7fffffffffffffff"); // hex-encoded - const EXPECTED_MIN_SIGNED_INT64: typeof Int64 = new Int64("8000000000000000"); // hex-encoded 2's complement - const EXPECTED_INT64_LIST = [ - EXPECTED_SMALL_INT64, - EXPECTED_MAX_JS_SAFE_INT64, - EXPECTED_MIN_JS_SAFE_INT64, - EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64, - EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64, - EXPECTED_MAX_SIGNED_INT64, - EXPECTED_MIN_SIGNED_INT64 - ]; - assert.ok(EXPECTED_SMALL_INT64.equals(Int64Test.SMALL_INT64)); - assert.ok(EXPECTED_MAX_JS_SAFE_INT64.equals(Int64Test.MAX_JS_SAFE_INT64)); - assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(Int64Test.MIN_JS_SAFE_INT64)); - assert.ok( - EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals( - Int64Test.MAX_JS_SAFE_PLUS_ONE_INT64 - ) - ); - assert.ok( - EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals( - Int64Test.MIN_JS_SAFE_MINUS_ONE_INT64 - ) - ); - assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(Int64Test.MAX_SIGNED_INT64)); - assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(Int64Test.MIN_SIGNED_INT64)); - assert.equal( - EXPECTED_SMALL_INT64_AS_NUMBER, - Int64Test.SMALL_INT64.toNumber() - ); - assert.equal( - Number.MAX_SAFE_INTEGER, - Int64Test.MAX_JS_SAFE_INT64.toNumber() - ); - assert.equal( - Number.MIN_SAFE_INTEGER, - Int64Test.MIN_JS_SAFE_INT64.toNumber() - ); +QUnit.module("Int64"); - for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) { - assert.ok(EXPECTED_INT64_LIST[i].equals(Int64Test.INT64_LIST[i])); - } +QUnit.test("Int64", function (assert) { + console.log("Int64 test -- starts"); + const EXPECTED_SMALL_INT64_AS_NUMBER: number = 42; + const EXPECTED_SMALL_INT64: typeof Int64 = new Int64(42); + const EXPECTED_MAX_JS_SAFE_INT64: typeof Int64 = new Int64( + Number.MAX_SAFE_INTEGER, + ); + const EXPECTED_MIN_JS_SAFE_INT64: typeof Int64 = new Int64( + Number.MIN_SAFE_INTEGER, + ); + const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: typeof Int64 = new Int64( + "0020000000000000", + ); // hex-encoded + const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: typeof Int64 = new Int64( + "ffe0000000000000", + ); // hex-encoded 2's complement + const EXPECTED_MAX_SIGNED_INT64: typeof Int64 = new Int64("7fffffffffffffff"); // hex-encoded + const EXPECTED_MIN_SIGNED_INT64: typeof Int64 = new Int64("8000000000000000"); // hex-encoded 2's complement + const EXPECTED_INT64_LIST = [ + EXPECTED_SMALL_INT64, + EXPECTED_MAX_JS_SAFE_INT64, + EXPECTED_MIN_JS_SAFE_INT64, + EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64, + EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64, + EXPECTED_MAX_SIGNED_INT64, + EXPECTED_MIN_SIGNED_INT64, + ]; + assert.ok(EXPECTED_SMALL_INT64.equals(Int64Test.SMALL_INT64)); + assert.ok(EXPECTED_MAX_JS_SAFE_INT64.equals(Int64Test.MAX_JS_SAFE_INT64)); + assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(Int64Test.MIN_JS_SAFE_INT64)); + assert.ok( + EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals( + Int64Test.MAX_JS_SAFE_PLUS_ONE_INT64, + ), + ); + assert.ok( + EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals( + Int64Test.MIN_JS_SAFE_MINUS_ONE_INT64, + ), + ); + assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(Int64Test.MAX_SIGNED_INT64)); + assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(Int64Test.MIN_SIGNED_INT64)); + assert.equal( + EXPECTED_SMALL_INT64_AS_NUMBER, + Int64Test.SMALL_INT64.toNumber(), + ); + assert.equal(Number.MAX_SAFE_INTEGER, Int64Test.MAX_JS_SAFE_INT64.toNumber()); + assert.equal(Number.MIN_SAFE_INTEGER, Int64Test.MIN_JS_SAFE_INT64.toNumber()); - for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i){ - let int64Object = EXPECTED_INT64_LIST[i]; - assert.ok(Int64Test.INT64_2_INT64_MAP[JSONInt64.toDecimalString(int64Object)].equals(int64Object)); - } + for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) { + assert.ok(EXPECTED_INT64_LIST[i].equals(Int64Test.INT64_LIST[i])); + } - console.log('Int64 test -- ends'); - }); + for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) { + let int64Object = EXPECTED_INT64_LIST[i]; + assert.ok( + Int64Test.INT64_2_INT64_MAP[ + JSONInt64.toDecimalString(int64Object) + ].equals(int64Object), + ); + } + console.log("Int64 test -- ends"); +}); diff --git a/lib/ts/test/test.ts b/lib/ts/test/test.ts index 31fdcbff8bc..614461dc1fc 100644 --- a/lib/ts/test/test.ts +++ b/lib/ts/test/test.ts @@ -7,336 +7,365 @@ var QUnit = require("./qunit"); const transport: Thrift.Transport = new Thrift.Transport("/service"); const protocol: Thrift.Protocol = new Thrift.Protocol(transport); -const client: ThriftTest.ThriftTestClient = new ThriftTest.ThriftTestClient(protocol); +const client: ThriftTest.ThriftTestClient = new ThriftTest.ThriftTestClient( + protocol, +); -const int64_2_pow_60: typeof Int64 = new Int64('1000000000000000'); -const int64_minus_2_pow_60: typeof Int64 = new Int64('f000000000000000'); +const int64_2_pow_60: typeof Int64 = new Int64("1000000000000000"); +const int64_minus_2_pow_60: typeof Int64 = new Int64("f000000000000000"); // Work around for old API used by QUnitAdapter of jsTestDriver -if (typeof QUnit.log == 'function') { - // When using real QUnit (fron PhantomJS) log failures to console - QUnit.log(function(details) { - if (!details.result) { - console.log('======== FAIL ========'); - console.log('TestName: ' + details.name); - if (details.message) console.log(details.message); - console.log('Expected: ' + JSONInt64.stringify(details.expected)); - console.log('Actual : ' + JSONInt64.stringify(details.actual)); - console.log('======================'); - } - }); +if (typeof QUnit.log == "function") { + // When using real QUnit (fron PhantomJS) log failures to console + QUnit.log(function (details) { + if (!details.result) { + console.log("======== FAIL ========"); + console.log("TestName: " + details.name); + if (details.message) console.log(details.message); + console.log("Expected: " + JSONInt64.stringify(details.expected)); + console.log("Actual : " + JSONInt64.stringify(details.actual)); + console.log("======================"); + } + }); } // all Languages in UTF-8 -const stringTest: string = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmål)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; - +const stringTest: string = + "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmål)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; function checkRecursively(assert, map1: Object, map2: Object): void { - if (typeof map1 !== 'function' && typeof map2 !== 'function') { - if (!map1 || typeof map1 !== 'object') { - assert.equal(map1, map2); - } else { - for (let key in map1) { - checkRecursively(assert, map1[key], map2[key]); - } - } + if (typeof map1 !== "function" && typeof map2 !== "function") { + if (!map1 || typeof map1 !== "object") { + assert.equal(map1, map2); + } else { + for (let key in map1) { + checkRecursively(assert, map1[key], map2[key]); + } } + } } - -QUnit.module('Base Types'); - - QUnit.test('Void', function(assert) { - assert.equal(client.testVoid(), undefined); - }); - QUnit.test('Binary (String)', function(assert) { - let binary: string = ''; - for (let v = 255; v >= 0; --v) { - binary += String.fromCharCode(v); - } - assert.equal(client.testBinary(binary), binary); - }); - QUnit.test('Binary (Uint8Array)', function(assert) { - let binary: string = ''; - for (let v = 255; v >= 0; --v) { - binary += String.fromCharCode(v); - } - const arr: Uint8Array = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; ++i) { - arr[i] = binary[i].charCodeAt(0); - } - const hexEncodedString = Array.from(arr, function(byte) { - return String.fromCharCode(byte); - }).join('') - assert.equal(client.testBinary(hexEncodedString), binary); - }); - QUnit.test('String', function(assert) { - assert.equal(client.testString(''), ''); - assert.equal(client.testString(stringTest), stringTest); - - const specialCharacters: string = 'quote: \" backslash:' + - ' forwardslash-escaped: \/ ' + - ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + - ' now-all-of-them-together: "\\\/\b\n\r\t' + - ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><'; - assert.equal(client.testString(specialCharacters), specialCharacters); - }); - QUnit.test('Double', function(assert) { - assert.equal(client.testDouble(0), 0); - assert.equal(client.testDouble(-1), -1); - assert.equal(client.testDouble(3.14), 3.14); - assert.equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60)); - }); - QUnit.test('Byte', function(assert) { - assert.equal(client.testByte(0), 0); - assert.equal(client.testByte(0x01), 0x01); - }); - QUnit.test('I32', function(assert) { - assert.equal(client.testI32(0), 0); - assert.equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30)); - assert.equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30)); - }); - QUnit.test('I64', function(assert) { - assert.equal(client.testI64(new Int64(0)), 0); - - let int64_2_pow_60_result: typeof Int64 = client.testI64(int64_2_pow_60); - assert.ok(int64_2_pow_60.equals(int64_2_pow_60_result)); - - let int64_minus_2_pow_60_result: typeof Int64 = client.testI64(int64_minus_2_pow_60); - assert.ok(int64_minus_2_pow_60.equals(int64_minus_2_pow_60_result)); - }); - - -QUnit.module('Structured Types'); - - QUnit.test('Struct', function(assert) { - const structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); - structTestInput.string_thing = 'worked'; - structTestInput.byte_thing = 0x01; - structTestInput.i32_thing = Math.pow(2, 30); - structTestInput.i64_thing = int64_2_pow_60; - - const structTestOutput: ThriftTest.Xtruct = client.testStruct(structTestInput); - - assert.equal(structTestOutput.string_thing, structTestInput.string_thing); - assert.equal(structTestOutput.byte_thing, structTestInput.byte_thing); - assert.equal(structTestOutput.i32_thing, structTestInput.i32_thing); - assert.ok(structTestOutput.i64_thing.equals(structTestInput.i64_thing)); - assert.ok(structTestInput.i64_thing.equals(structTestOutput.i64_thing)); - - assert.equal(JSONInt64.stringify(structTestOutput), JSONInt64.stringify(structTestInput)); - }); - - QUnit.test('Nest', function(assert) { - const xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); - xtrTestInput.string_thing = 'worked'; - xtrTestInput.byte_thing = 0x01; - xtrTestInput.i32_thing = Math.pow(2, 30); - xtrTestInput.i64_thing = int64_2_pow_60; - - const nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2(); - nestTestInput.byte_thing = 0x02; - nestTestInput.struct_thing = xtrTestInput; - nestTestInput.i32_thing = Math.pow(2, 15); - - const nestTestOutput: ThriftTest.Xtruct2 = client.testNest(nestTestInput); - - assert.equal(nestTestOutput.byte_thing, nestTestInput.byte_thing); - assert.equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing); - assert.equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing); - assert.equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing); - assert.ok(nestTestOutput.struct_thing.i64_thing.equals(nestTestInput.struct_thing.i64_thing)); - assert.equal(nestTestOutput.i32_thing, nestTestInput.i32_thing); - - assert.equal(JSONInt64.stringify(nestTestOutput), JSONInt64.stringify(nestTestInput)); - }); - - QUnit.test('Map', function(assert) { - const mapTestInput: {[k: number]: number;} = {7: 77, 8: 88, 9: 99}; - - const mapTestOutput: {[k: number]: number;} = client.testMap(mapTestInput); - - for (let key in mapTestOutput) { - assert.equal(mapTestOutput[key], mapTestInput[key]); - } - }); - - QUnit.test('StringMap', function(assert) { - const mapTestInput: {[k: string]: string;} = { - 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key', - 'longValue': stringTest, stringTest: 'long key' - }; - - const mapTestOutput: {[k: string]: string;} = client.testStringMap(mapTestInput); - - for (let key in mapTestOutput) { - assert.equal(mapTestOutput[key], mapTestInput[key]); - } - }); - - QUnit.test('Set', function(assert) { - const setTestInput: number[] = [1, 2, 3]; - assert.ok(client.testSet(setTestInput), setTestInput); - }); - - QUnit.test('List', function(assert) { - const listTestInput: number[] = [1, 2, 3]; - assert.ok(client.testList(listTestInput), listTestInput); - }); - - QUnit.test('Enum', function(assert) { - assert.equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE); - }); - - QUnit.test('TypeDef', function(assert) { - assert.equal(client.testTypedef(new Int64(69)), 69); - }); - - -QUnit.module('deeper!'); - - QUnit.test('MapMap', function(assert) { - const mapMapTestExpectedResult: {[K: number]: {[k: number]: number}} = { - '4': {'1': 1, '2': 2, '3': 3, '4': 4}, - '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1} - }; - - const mapMapTestOutput = client.testMapMap(1); - - - for (let key in mapMapTestOutput) { - for (let key2 in mapMapTestOutput[key]) { - assert.equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]); - } - } - - checkRecursively(assert, mapMapTestOutput, mapMapTestExpectedResult); - }); - - -QUnit.module('Exception'); - - QUnit.test('Xception', function(assert) { - assert.expect(2); - const done = assert.async(); - try { - client.testException('Xception'); - assert.ok(false); - }catch (e) { - assert.equal(e.errorCode, 1001); - assert.equal(e.message, 'Xception'); - done(); - } - }); - - QUnit.test('no Exception', function(assert) { - assert.expect(1); - try { - client.testException('no Exception'); - assert.ok(true); - }catch (e) { - assert.ok(false); - } - }); - - QUnit.test('TException', function(assert) { - //ThriftTest does not list TException as a legal exception so it will - // generate an exception on the server that does not propagate back to - // the client. This test has been modified to equate to "no exception" - assert.expect(1); - try { - client.testException('TException'); - } catch (e) { - //assert.ok(false); - } - assert.ok(true); - }); - - -QUnit.module('Insanity'); - - const crazy: ThriftTest.Insanity = { - 'userMap': { '5': new Int64(5), '8': new Int64(8) }, - 'xtructs': [{ - 'string_thing': 'Goodbye4', - 'byte_thing': 4, - 'i32_thing': 4, - 'i64_thing': new Int64(4) - }, - { - 'string_thing': 'Hello2', - 'byte_thing': 2, - 'i32_thing': 2, - 'i64_thing': new Int64(2) - }] - }; - QUnit.test('testInsanity', function(assert) { - const insanity: {[k: number]: (ThriftTest.Insanity | {[k:number]: ThriftTest.Insanity})} = { - '1': { - '2': crazy, - '3': crazy - }, - '2': { '6': new ThriftTest.Insanity() } - }; - const res = client.testInsanity(new ThriftTest.Insanity(crazy)); - assert.ok(res, JSONInt64.stringify(res)); - assert.ok(insanity, JSONInt64.stringify(insanity)); - - checkRecursively(assert, res, insanity); - }); - +QUnit.module("Base Types"); + +QUnit.test("Void", function (assert) { + assert.equal(client.testVoid(), undefined); +}); +QUnit.test("Binary (String)", function (assert) { + let binary: string = ""; + for (let v = 255; v >= 0; --v) { + binary += String.fromCharCode(v); + } + assert.equal(client.testBinary(binary), binary); +}); +QUnit.test("Binary (Uint8Array)", function (assert) { + let binary: string = ""; + for (let v = 255; v >= 0; --v) { + binary += String.fromCharCode(v); + } + const arr: Uint8Array = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; ++i) { + arr[i] = binary[i].charCodeAt(0); + } + const hexEncodedString = Array.from(arr, function (byte) { + return String.fromCharCode(byte); + }).join(""); + assert.equal(client.testBinary(hexEncodedString), binary); +}); +QUnit.test("String", function (assert) { + assert.equal(client.testString(""), ""); + assert.equal(client.testString(stringTest), stringTest); + + const specialCharacters: string = + 'quote: \" backslash:' + + " forwardslash-escaped: \/ " + + " backspace: \b formfeed: \f newline: \n return: \r tab: " + + ' now-all-of-them-together: "\\\/\b\n\r\t' + + " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><"; + assert.equal(client.testString(specialCharacters), specialCharacters); +}); +QUnit.test("Double", function (assert) { + assert.equal(client.testDouble(0), 0); + assert.equal(client.testDouble(-1), -1); + assert.equal(client.testDouble(3.14), 3.14); + assert.equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60)); +}); +QUnit.test("Byte", function (assert) { + assert.equal(client.testByte(0), 0); + assert.equal(client.testByte(0x01), 0x01); +}); +QUnit.test("I32", function (assert) { + assert.equal(client.testI32(0), 0); + assert.equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30)); + assert.equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30)); +}); +QUnit.test("I64", function (assert) { + assert.equal(client.testI64(new Int64(0)), 0); + + let int64_2_pow_60_result: typeof Int64 = client.testI64(int64_2_pow_60); + assert.ok(int64_2_pow_60.equals(int64_2_pow_60_result)); + + let int64_minus_2_pow_60_result: typeof Int64 = + client.testI64(int64_minus_2_pow_60); + assert.ok(int64_minus_2_pow_60.equals(int64_minus_2_pow_60_result)); +}); + +QUnit.module("Structured Types"); + +QUnit.test("Struct", function (assert) { + const structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); + structTestInput.string_thing = "worked"; + structTestInput.byte_thing = 0x01; + structTestInput.i32_thing = Math.pow(2, 30); + structTestInput.i64_thing = int64_2_pow_60; + + const structTestOutput: ThriftTest.Xtruct = + client.testStruct(structTestInput); + + assert.equal(structTestOutput.string_thing, structTestInput.string_thing); + assert.equal(structTestOutput.byte_thing, structTestInput.byte_thing); + assert.equal(structTestOutput.i32_thing, structTestInput.i32_thing); + assert.ok(structTestOutput.i64_thing.equals(structTestInput.i64_thing)); + assert.ok(structTestInput.i64_thing.equals(structTestOutput.i64_thing)); + + assert.equal( + JSONInt64.stringify(structTestOutput), + JSONInt64.stringify(structTestInput), + ); +}); + +QUnit.test("Nest", function (assert) { + const xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct(); + xtrTestInput.string_thing = "worked"; + xtrTestInput.byte_thing = 0x01; + xtrTestInput.i32_thing = Math.pow(2, 30); + xtrTestInput.i64_thing = int64_2_pow_60; + + const nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2(); + nestTestInput.byte_thing = 0x02; + nestTestInput.struct_thing = xtrTestInput; + nestTestInput.i32_thing = Math.pow(2, 15); + + const nestTestOutput: ThriftTest.Xtruct2 = client.testNest(nestTestInput); + + assert.equal(nestTestOutput.byte_thing, nestTestInput.byte_thing); + assert.equal( + nestTestOutput.struct_thing.string_thing, + nestTestInput.struct_thing.string_thing, + ); + assert.equal( + nestTestOutput.struct_thing.byte_thing, + nestTestInput.struct_thing.byte_thing, + ); + assert.equal( + nestTestOutput.struct_thing.i32_thing, + nestTestInput.struct_thing.i32_thing, + ); + assert.ok( + nestTestOutput.struct_thing.i64_thing.equals( + nestTestInput.struct_thing.i64_thing, + ), + ); + assert.equal(nestTestOutput.i32_thing, nestTestInput.i32_thing); + + assert.equal( + JSONInt64.stringify(nestTestOutput), + JSONInt64.stringify(nestTestInput), + ); +}); + +QUnit.test("Map", function (assert) { + const mapTestInput: { [k: number]: number } = { 7: 77, 8: 88, 9: 99 }; + + const mapTestOutput: { [k: number]: number } = client.testMap(mapTestInput); + + for (let key in mapTestOutput) { + assert.equal(mapTestOutput[key], mapTestInput[key]); + } +}); + +QUnit.test("StringMap", function (assert) { + const mapTestInput: { [k: string]: string } = { + a: "123", + "a b": "with spaces ", + same: "same", + "0": "numeric key", + longValue: stringTest, + stringTest: "long key", + }; + + const mapTestOutput: { [k: string]: string } = + client.testStringMap(mapTestInput); + + for (let key in mapTestOutput) { + assert.equal(mapTestOutput[key], mapTestInput[key]); + } +}); + +QUnit.test("Set", function (assert) { + const setTestInput: number[] = [1, 2, 3]; + assert.ok(client.testSet(setTestInput), setTestInput); +}); + +QUnit.test("List", function (assert) { + const listTestInput: number[] = [1, 2, 3]; + assert.ok(client.testList(listTestInput), listTestInput); +}); + +QUnit.test("Enum", function (assert) { + assert.equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE); +}); + +QUnit.test("TypeDef", function (assert) { + assert.equal(client.testTypedef(new Int64(69)), 69); +}); + +QUnit.module("deeper!"); + +QUnit.test("MapMap", function (assert) { + const mapMapTestExpectedResult: { [K: number]: { [k: number]: number } } = { + "4": { "1": 1, "2": 2, "3": 3, "4": 4 }, + "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 }, + }; + + const mapMapTestOutput = client.testMapMap(1); + + for (let key in mapMapTestOutput) { + for (let key2 in mapMapTestOutput[key]) { + assert.equal( + mapMapTestOutput[key][key2], + mapMapTestExpectedResult[key][key2], + ); + } + } + + checkRecursively(assert, mapMapTestOutput, mapMapTestExpectedResult); +}); + +QUnit.module("Exception"); + +QUnit.test("Xception", function (assert) { + assert.expect(2); + const done = assert.async(); + try { + client.testException("Xception"); + assert.ok(false); + } catch (e) { + assert.equal(e.errorCode, 1001); + assert.equal(e.message, "Xception"); + done(); + } +}); + +QUnit.test("no Exception", function (assert) { + assert.expect(1); + try { + client.testException("no Exception"); + assert.ok(true); + } catch (e) { + assert.ok(false); + } +}); + +QUnit.test("TException", function (assert) { + //ThriftTest does not list TException as a legal exception so it will + // generate an exception on the server that does not propagate back to + // the client. This test has been modified to equate to "no exception" + assert.expect(1); + try { + client.testException("TException"); + } catch (e) { + //assert.ok(false); + } + assert.ok(true); +}); + +QUnit.module("Insanity"); + +const crazy: ThriftTest.Insanity = { + userMap: { "5": new Int64(5), "8": new Int64(8) }, + xtructs: [ + { + string_thing: "Goodbye4", + byte_thing: 4, + i32_thing: 4, + i64_thing: new Int64(4), + }, + { + string_thing: "Hello2", + byte_thing: 2, + i32_thing: 2, + i64_thing: new Int64(2), + }, + ], +}; +QUnit.test("testInsanity", function (assert) { + const insanity: { + [k: number]: ThriftTest.Insanity | { [k: number]: ThriftTest.Insanity }; + } = { + "1": { + "2": crazy, + "3": crazy, + }, + "2": { "6": new ThriftTest.Insanity() }, + }; + const res = client.testInsanity(new ThriftTest.Insanity(crazy)); + assert.ok(res, JSONInt64.stringify(res)); + assert.ok(insanity, JSONInt64.stringify(insanity)); + + checkRecursively(assert, res, insanity); +}); ////////////////////////////////// //Run same tests asynchronously -QUnit.module('Async'); - - QUnit.test('Double', function(assert) { - assert.expect(1); - - const done = assert.async(); - client.testDouble(3.14159265, function(result) { - assert.equal(result, 3.14159265); - done(); - }); - }); - - QUnit.test('Byte', function(assert) { - assert.expect(1); - - const done = assert.async(); - client.testByte(0x01, function(result) { - assert.equal(result, 0x01); - done(); - }); - }); - - QUnit.test('I32', function(assert) { - assert.expect(2); - - const done = assert.async(2); - client.testI32(Math.pow(2, 30), function(result) { - assert.equal(result, Math.pow(2, 30)); - done(); - }); - - client.testI32(Math.pow(-2, 31), function(result) { - assert.equal(result, Math.pow(-2, 31)); - done(); - }); - }); - - QUnit.test('I64', function(assert) { - assert.expect(2); - - const done = assert.async(2); - client.testI64(int64_2_pow_60, function(result) { - assert.ok(int64_2_pow_60.equals(result)); - done(); - }); - - client.testI64(int64_minus_2_pow_60, function(result) { - assert.ok(int64_minus_2_pow_60.equals(result)); - done(); - }); - }); +QUnit.module("Async"); + +QUnit.test("Double", function (assert) { + assert.expect(1); + + const done = assert.async(); + client.testDouble(3.14159265, function (result) { + assert.equal(result, 3.14159265); + done(); + }); +}); + +QUnit.test("Byte", function (assert) { + assert.expect(1); + + const done = assert.async(); + client.testByte(0x01, function (result) { + assert.equal(result, 0x01); + done(); + }); +}); + +QUnit.test("I32", function (assert) { + assert.expect(2); + + const done = assert.async(2); + client.testI32(Math.pow(2, 30), function (result) { + assert.equal(result, Math.pow(2, 30)); + done(); + }); + + client.testI32(Math.pow(-2, 31), function (result) { + assert.equal(result, Math.pow(-2, 31)); + done(); + }); +}); + +QUnit.test("I64", function (assert) { + assert.expect(2); + + const done = assert.async(2); + client.testI64(int64_2_pow_60, function (result) { + assert.ok(int64_2_pow_60.equals(result)); + done(); + }); + + client.testI64(int64_minus_2_pow_60, function (result) { + assert.ok(int64_minus_2_pow_60.equals(result)); + done(); + }); +}); diff --git a/lib/ts/test/test_handler.js b/lib/ts/test/test_handler.js index 8ba296ba108..825c5675c8c 100644 --- a/lib/ts/test/test_handler.js +++ b/lib/ts/test/test_handler.js @@ -20,87 +20,87 @@ //This is the server side Node test handler for the standard // Apache Thrift test service. -const es6Mode = process.argv.includes('--es6'); -const genFolder = es6Mode ? 'gen-nodejs-es6' : 'gen-nodejs'; +const es6Mode = process.argv.includes("--es6"); +const genFolder = es6Mode ? "gen-nodejs-es6" : "gen-nodejs"; const ttypes = require(`./${genFolder}/ThriftTest_types`); -const TException = require('../../nodejs/lib/thrift').TException; -const Int64 = require('node-int64'); +const TException = require("../../nodejs/lib/thrift").TException; +const Int64 = require("node-int64"); exports.ThriftTestHandler = { - testVoid: function(result) { - console.log('testVoid()'); + testVoid: function (result) { + console.log("testVoid()"); result(null); }, - testString: function(thing, result) { - console.log('testString(\'' + thing + '\')'); + testString: function (thing, result) { + console.log("testString('" + thing + "')"); result(null, thing); }, - testByte: function(thing, result) { - console.log('testByte(' + thing + ')'); + testByte: function (thing, result) { + console.log("testByte(" + thing + ")"); result(null, thing); }, - testI32: function(thing, result) { - console.log('testI32(' + thing + ')'); + testI32: function (thing, result) { + console.log("testI32(" + thing + ")"); result(null, thing); }, - testI64: function(thing, result) { - console.log('testI64(' + thing + ')'); + testI64: function (thing, result) { + console.log("testI64(" + thing + ")"); result(null, thing); }, - testDouble: function(thing, result) { - console.log('testDouble(' + thing + ')'); + testDouble: function (thing, result) { + console.log("testDouble(" + thing + ")"); result(null, thing); }, - testBinary: function(thing, result) { - console.log('testBinary(\'' + thing + '\')'); + testBinary: function (thing, result) { + console.log("testBinary('" + thing + "')"); result(null, thing); }, - testStruct: function(thing, result) { - console.log('testStruct('); + testStruct: function (thing, result) { + console.log("testStruct("); console.log(thing); - console.log(')'); + console.log(")"); result(null, thing); }, - testNest: function(nest, result) { - console.log('testNest('); + testNest: function (nest, result) { + console.log("testNest("); console.log(nest); - console.log(')'); + console.log(")"); result(null, nest); }, - testMap: function(thing, result) { - console.log('testMap('); + testMap: function (thing, result) { + console.log("testMap("); console.log(thing); - console.log(')'); + console.log(")"); result(null, thing); }, - testStringMap: function(thing, result) { - console.log('testStringMap('); + testStringMap: function (thing, result) { + console.log("testStringMap("); console.log(thing); - console.log(')'); + console.log(")"); result(null, thing); }, - testSet: function(thing, result) { - console.log('testSet('); + testSet: function (thing, result) { + console.log("testSet("); console.log(thing); - console.log(')'); + console.log(")"); result(null, thing); }, - testList: function(thing, result) { - console.log('testList('); + testList: function (thing, result) { + console.log("testList("); console.log(thing); - console.log(')'); + console.log(")"); result(null, thing); }, - testEnum: function(thing, result) { - console.log('testEnum(' + thing + ')'); + testEnum: function (thing, result) { + console.log("testEnum(" + thing + ")"); result(null, thing); }, - testTypedef: function(thing, result) { - console.log('testTypedef(' + thing + ')'); + testTypedef: function (thing, result) { + console.log("testTypedef(" + thing + ")"); result(null, thing); }, - testMapMap: function(hello, result) { - console.log('testMapMap(' + hello + ')'); + testMapMap: function (hello, result) { + console.log("testMapMap(" + hello + ")"); const mapmap = []; const pos = []; @@ -114,19 +114,19 @@ exports.ThriftTestHandler = { result(null, mapmap); }, - testInsanity: function(argument, result) { - console.log('testInsanity('); + testInsanity: function (argument, result) { + console.log("testInsanity("); console.log(argument); - console.log(')'); + console.log(")"); const hello = new ttypes.Xtruct(); - hello.string_thing = 'Hello2'; + hello.string_thing = "Hello2"; hello.byte_thing = 2; hello.i32_thing = 2; hello.i64_thing = new Int64(2); const goodbye = new ttypes.Xtruct(); - goodbye.string_thing = 'Goodbye4'; + goodbye.string_thing = "Goodbye4"; goodbye.byte_thing = 4; goodbye.i32_thing = 4; goodbye.i64_thing = new Int64(4); @@ -150,45 +150,45 @@ exports.ThriftTestHandler = { insane[1] = first_map; insane[2] = second_map; - console.log('insane result:'); + console.log("insane result:"); console.log(insane); result(null, insane); }, - testMulti: function(arg0, arg1, arg2, arg3, arg4, arg5, result) { - console.log('testMulti()'); + testMulti: function (arg0, arg1, arg2, arg3, arg4, arg5, result) { + console.log("testMulti()"); const hello = new ttypes.Xtruct(); - hello.string_thing = 'Hello2'; + hello.string_thing = "Hello2"; hello.byte_thing = arg0; hello.i32_thing = arg1; hello.i64_thing = arg2; result(null, hello); }, - testException: function(arg, result) { - console.log('testException(' + arg + ')'); - if (arg === 'Xception') { + testException: function (arg, result) { + console.log("testException(" + arg + ")"); + if (arg === "Xception") { const x = new ttypes.Xception(); x.errorCode = 1001; x.message = arg; result(x); - } else if (arg === 'TException') { + } else if (arg === "TException") { result(new TException(arg)); } else { result(null); } }, - testMultiException: function(arg0, arg1, result) { - console.log('testMultiException(' + arg0 + ', ' + arg1 + ')'); - if (arg0 === ('Xception')) { + testMultiException: function (arg0, arg1, result) { + console.log("testMultiException(" + arg0 + ", " + arg1 + ")"); + if (arg0 === "Xception") { const x = new ttypes.Xception(); x.errorCode = 1001; - x.message = 'This is an Xception'; + x.message = "This is an Xception"; result(x); - } else if (arg0 === ('Xception2')) { + } else if (arg0 === "Xception2") { const x2 = new ttypes.Xception2(); x2.errorCode = 2002; x2.struct_thing = new ttypes.Xtruct(); - x2.struct_thing.string_thing = 'This is an Xception2'; + x2.struct_thing.string_thing = "This is an Xception2"; result(x2); } @@ -196,7 +196,9 @@ exports.ThriftTestHandler = { res.string_thing = arg1; result(null, res); }, - testOneway: function(sleepFor, result) { - console.log('testOneway(' + sleepFor + ') => JavaScript (like Rust) never sleeps!'); - } -}; //ThriftTestSvcHandler + testOneway: function (sleepFor, result) { + console.log( + "testOneway(" + sleepFor + ") => JavaScript (like Rust) never sleeps!", + ); + }, +}; //ThriftTestSvcHandler diff --git a/lib/ts/thrift.d.ts b/lib/ts/thrift.d.ts index 0ba46c91497..8e9d565fab5 100644 --- a/lib/ts/thrift.d.ts +++ b/lib/ts/thrift.d.ts @@ -29,7 +29,7 @@ declare module Thrift { * @property {number} VOID - No value (only legal for return types). * @property {number} BOOL - True/False integer. * @property {number} BYTE - Signed 8 bit integer. - * @property {number} I08 - Signed 8 bit integer. + * @property {number} I08 - Signed 8 bit integer. * @property {number} DOUBLE - 64 bit IEEE 854 floating point. * @property {number} I16 - Signed 16 bit integer. * @property {number} I32 - Signed 32 bit integer. @@ -44,23 +44,23 @@ declare module Thrift { * @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters. */ interface Type { - 'STOP': number; - 'VOID': number; - 'BOOL': number; - 'BYTE': number; - 'I08': number; - 'DOUBLE': number; - 'I16': number; - 'I32': number; - 'I64': number; - 'STRING': number; - 'UTF7': number; - 'STRUCT': number; - 'MAP': number; - 'SET': number; - 'LIST': number; - 'UTF8': number; - 'UTF16': number; + STOP: number; + VOID: number; + BOOL: number; + BYTE: number; + I08: number; + DOUBLE: number; + I16: number; + I32: number; + I64: number; + STRING: number; + UTF7: number; + STRUCT: number; + MAP: number; + SET: number; + LIST: number; + UTF8: number; + UTF16: number; } var Type: Type; @@ -72,10 +72,10 @@ declare module Thrift { * @property {number} ONEWAY - Oneway RPC call from client to server with no response. */ interface MessageType { - 'CALL': number; - 'REPLY': number; - 'EXCEPTION': number; - 'ONEWAY': number; + CALL: number; + REPLY: number; + EXCEPTION: number; + ONEWAY: number; } var MessageType: MessageType; @@ -92,7 +92,11 @@ declare module Thrift { * @param {function} superConstructor - Contstructor function to set as base. * @param {string} [name] - Type name to set as name property in derived prototype. */ - function inherits(constructor: Function, superConstructor: Function, name?: string): void; + function inherits( + constructor: Function, + superConstructor: Function, + name?: string, + ): void; /** * TException is the base class for all Thrift exceptions types. @@ -129,17 +133,17 @@ declare module Thrift { * @property {number} UNSUPPORTED_CLIENT_TYPE - Unused. */ interface TApplicationExceptionType { - 'UNKNOWN': number; - 'UNKNOWN_METHOD': number; - 'INVALID_MESSAGE_TYPE': number; - 'WRONG_METHOD_NAME': number; - 'BAD_SEQUENCE_ID': number; - 'MISSING_RESULT': number; - 'INTERNAL_ERROR': number; - 'PROTOCOL_ERROR': number; - 'INVALID_TRANSFORM': number; - 'INVALID_PROTOCOL': number; - 'UNSUPPORTED_CLIENT_TYPE': number; + UNKNOWN: number; + UNKNOWN_METHOD: number; + INVALID_MESSAGE_TYPE: number; + WRONG_METHOD_NAME: number; + BAD_SEQUENCE_ID: number; + MISSING_RESULT: number; + INTERNAL_ERROR: number; + PROTOCOL_ERROR: number; + INVALID_TRANSFORM: number; + INVALID_PROTOCOL: number; + UNSUPPORTED_CLIENT_TYPE: number; } var TApplicationExceptionType: TApplicationExceptionType; @@ -179,7 +183,7 @@ declare module Thrift { /** * The Apache Thrift Transport layer performs byte level I/O between RPC * clients and servers. The JavaScript Transport object type uses Http[s]/XHR and is - * the sole browser based Thrift transport. Target servers must implement the http[s] + * the sole browser based Thrift transport. Target servers must implement the http[s] * transport (see: node.js example server). */ class TXHRTransport { @@ -208,7 +212,7 @@ declare module Thrift { /** * Sends the current XRH request if the transport was created with a URL and * the async parameter if false. If the transport was not created with a URL - * or the async parameter is True or the URL is an empty string, the current + * or the async parameter is True or the URL is an empty string, the current * send buffer is returned. * @param {object} async - If true the current send buffer is returned. * @param {function} callback - Optional async completion callback. @@ -224,7 +228,12 @@ declare module Thrift { * @param {function} recv_method - The Thrift Service Client receive method for the call. * @returns {object} A new jQuery XHR object. */ - jqRequest(client: Object, postData: any, args: Function, recv_method: Function): Object; + jqRequest( + client: Object, + postData: any, + args: Function, + recv_method: Function, + ): Object; /** * Sets the buffer to use when receiving server responses. @@ -281,22 +290,22 @@ declare module Thrift { /** * Old alias of the TXHRTransport for backwards compatibility. */ - class Transport extends TXHRTransport { } + class Transport extends TXHRTransport {} /** - * The Apache Thrift Transport layer performs byte level I/O - * between RPC clients and servers. The JavaScript TWebSocketTransport object + * The Apache Thrift Transport layer performs byte level I/O + * between RPC clients and servers. The JavaScript TWebSocketTransport object * uses the WebSocket protocol. Target servers must implement WebSocket. */ class TWebSocketTransport { - url: string; //Where to connect - socket: any; //The web socket + url: string; //Where to connect + socket: any; //The web socket callbacks: Function[]; //Pending callbacks - send_pending: any[]; //Buffers/Callback pairs waiting to be sent - send_buf: string; //Outbound data, immutable until sent - recv_buf: string; //Inbound data - rb_wpos: number; //Network write position in receive buffer - rb_rpos: number; //Client read position in receive buffer + send_pending: any[]; //Buffers/Callback pairs waiting to be sent + send_buf: string; //Outbound data, immutable until sent + recv_buf: string; //Inbound data + rb_wpos: number; //Network write position in receive buffer + rb_rpos: number; //Client read position in receive buffer /** * Constructor Function for the WebSocket transport. @@ -307,12 +316,12 @@ declare module Thrift { __reset(url: string): void; /** - * Sends the current WS request and registers callback. The async - * parameter is ignored (WS flush is always async) and the callback + * Sends the current WS request and registers callback. The async + * parameter is ignored (WS flush is always async) and the callback * function parameter is required. * @param {object} async - Ignored. * @param {function} callback - The client completion callback. - * @returns {undefined|string} Nothing (undefined) + * @returns {undefined|string} Nothing (undefined) */ flush(async: any, callback: Function): string; @@ -332,7 +341,7 @@ declare module Thrift { /** * Returns true if the transport is open - * @returns {boolean} + * @returns {boolean} */ isOpen(): boolean; @@ -374,8 +383,8 @@ declare module Thrift { } /** - * Apache Thrift Protocols perform serialization which enables cross - * language RPC. The Protocol type is the JavaScript browser implementation + * Apache Thrift Protocols perform serialization which enables cross + * language RPC. The Protocol type is the JavaScript browser implementation * of the Apache Thrift TJSONProtocol. */ class TJSONProtocol { @@ -401,17 +410,17 @@ declare module Thrift { /** * Thrift IDL type string to Id mapping. * The mapping table looks as follows: - * "tf" -> Thrift.Type.BOOL - * "i8" -> Thrift.Type.BYTE - * "i16" -> Thrift.Type.I16 - * "i32" -> Thrift.Type.I32 - * "i64" -> Thrift.Type.I64 + * "tf" -> Thrift.Type.BOOL + * "i8" -> Thrift.Type.BYTE + * "i16" -> Thrift.Type.I16 + * "i32" -> Thrift.Type.I32 + * "i64" -> Thrift.Type.I64 * "dbl" -> Thrift.Type.DOUBLE * "rec" -> Thrift.Type.STRUCT * "str" -> Thrift.Type.STRING - * "map" -> Thrift.Type.MAP - * "lst" -> Thrift.Type.LIST - * "set" -> Thrift.Type.SET + * "map" -> Thrift.Type.MAP + * "lst" -> Thrift.Type.LIST + * "set" -> Thrift.Type.SET */ RType: { [k: string]: number }; @@ -542,8 +551,8 @@ declare module Thrift { @property {Thrift.MessageType} mtype - The type of message call. @property {number} rseqid - The sequence number of the message (0 in Thrift RPC). */ - /** - * Deserializes the beginning of a message. + /** + * Deserializes the beginning of a message. * @returns {AnonReadMessageBeginReturn} */ readMessageBegin(): { fname: string; mtype: number; rseqid: number }; @@ -551,8 +560,8 @@ declare module Thrift { /** Deserializes the end of a message. */ readMessageEnd(): void; - /** - * Deserializes the beginning of a struct. + /** + * Deserializes the beginning of a struct. * @param {string} [name] - The name of the struct (ignored). * @returns {object} - An object with an empty string fname property. */ @@ -568,8 +577,8 @@ declare module Thrift { @property {Thrift.Type} ftype - The data type of the field. @property {number} fid - The unique identifier of the field. */ - /** - * Deserializes the beginning of a field. + /** + * Deserializes the beginning of a field. * @returns {AnonReadFieldBeginReturn} */ readFieldBegin(): { fname: string; ftype: number; fid: number }; @@ -584,8 +593,8 @@ declare module Thrift { @property {Thrift.Type} vtype - The data type of the value. @property {number} size - The number of elements in the map. */ - /** - * Deserializes the beginning of a map. + /** + * Deserializes the beginning of a map. * @returns {AnonReadMapBeginReturn} */ readMapBegin(): { ktype: number; vtype: number; size: number }; @@ -599,8 +608,8 @@ declare module Thrift { @property {Thrift.Type} etype - The data type of the element. @property {number} size - The number of elements in the collection. */ - /** - * Deserializes the beginning of a list. + /** + * Deserializes the beginning of a list. * @returns {AnonReadColBeginReturn} */ readListBegin(): { etype: number; size: number }; @@ -608,19 +617,22 @@ declare module Thrift { /** Deserializes the end of a list. */ readListEnd(): void; - /** - * Deserializes the beginning of a set. + /** + * Deserializes the beginning of a set. * @param {Thrift.Type} elemType - The data type of the elements (ignored). * @param {number} size - The number of elements in the list (ignored). * @returns {AnonReadColBeginReturn} */ - readSetBegin(elemType?: number, size?: number): { etype: number; size: number }; + readSetBegin( + elemType?: number, + size?: number, + ): { etype: number; size: number }; /** Deserializes the end of a set. */ readSetEnd(): void; - /** Returns an object with a value property set to - * False unless the next number in the protocol buffer + /** Returns an object with a value property set to + * False unless the next number in the protocol buffer * is 1, in which case the value property is True. */ readBool(): Object; @@ -652,7 +664,7 @@ declare module Thrift { next value found in the protocol buffer. */ readBinary(): Object; - /** + /** * Method to arbitrarily skip over data (not implemented). */ skip(type: number): void; @@ -661,7 +673,7 @@ declare module Thrift { /** * Old alias of the TXHRTransport for backwards compatibility. */ - class Protocol extends TJSONProtocol { } + class Protocol extends TJSONProtocol {} class MultiplexProtocol extends TJSONProtocol { serviceName: string; @@ -673,7 +685,12 @@ declare module Thrift { * @param {any} [strictRead] * @param {any} [strictWrite] */ - constructor(srvName: string, trans: Object, strictRead?: any, strictWrite?: any); + constructor( + srvName: string, + trans: Object, + strictRead?: any, + strictWrite?: any, + ); /** * Override writeMessageBegin method of prototype diff --git a/package-lock.json b/package-lock.json index 50f7d58558f..9b7db5c87d0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,20 +16,22 @@ "ws": "^5.2.3" }, "devDependencies": { + "@eslint/js": "^9.18.0", "@types/node": "^10.12.6", "@types/node-int64": "^0.4.29", "@types/q": "^1.5.1", "buffer-equals": "^1.0.4", "commander": "^2.14.1", "connect": "^3.6.6", - "eslint": "^5.7.0", - "eslint-config-prettier": "^3.1.0", - "eslint-plugin-prettier": "^3.0.0", + "eslint": "^9.18.0", + "eslint-config-prettier": "^10.0.1", + "eslint-plugin-prettier": "^5.2.1", + "globals": "^15.14.0", "html-validator-cli": "^2.0.0", "jsdoc": "^4.0.2", "json-int64": "^1.0.2", "nyc": "^15.0.0", - "prettier": "^1.14.3", + "prettier": "^3.4.2", "tape": "^4.9.0", "typescript": "^3.1.6", "utf-8-validate": "^5.0.0" @@ -285,6 +287,15 @@ "ms": "^2.1.1" } }, + "node_modules/@babel/traverse/node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, "node_modules/@babel/traverse/node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -305,6 +316,262 @@ "node": ">=6.9.0" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", + "integrity": "sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", + "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.19.1.tgz", + "integrity": "sha512-fo6Mtm5mWyKjA/Chy1BYTdn5mGJoDNjC7C64ug20ADsRDGrA85bN3uK3MaKbeRkRuuIEAR5N33Jr1pbm411/PA==", + "dev": true, + "dependencies": { + "@eslint/object-schema": "^2.1.5", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@eslint/config-array/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/@eslint/core": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.10.0.tgz", + "integrity": "sha512-gFHJ+xBOo4G3WRlR1e/3G8A6/KZAH6zcE/hkLRCZTi/B9avAG365QhFA8uOGzTMqgTghpn7/fSnscW++dpMSAw==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.2.0.tgz", + "integrity": "sha512-grOjVNN8P3hjJn/eIETF1wwd12DdnwFDoyceUJLYYdkpbwq3nLi+4fqrTAONx7XDALqlL220wC/RHSC/QTI/0w==", + "dev": true, + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "node_modules/@eslint/eslintrc/node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/eslintrc/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/@eslint/js": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.18.0.tgz", + "integrity": "sha512-fK6L7rxcq6/z+AaQMtiFTkvbHkBLNlwyRxHpKawP0x3u9+NC6MQTnFW+AdpwC6gfHTW0051cokQgtTN2FqlxQA==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.5.tgz", + "integrity": "sha512-o0bhxnL89h5Bae5T318nFoFzGy+YE5i/gGkoPAgkmTVdRKTiv3p8JHevPiPaMwoloKfEiiaHlawCqaZMqRm+XQ==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.5.tgz", + "integrity": "sha512-lB05FkqEdUg2AA0xEbUz0SnkXT1LcCTa438W4IWTUh4hdOnVbQyOJ81OrDXsJk/LSiJHubgGEFoR5EHq1NsH1A==", + "dev": true, + "dependencies": { + "@eslint/core": "^0.10.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.6", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.6.tgz", + "integrity": "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==", + "dev": true, + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.3.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node/node_modules/@humanwhocodes/retry": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz", + "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.1.tgz", + "integrity": "sha512-c7hNEllBlenFTHBky65mhq8WD2kbN9Q6gk0bTk8lSBvc554jpXSkST1iePudpt7+A/AQvuHs9EMqjHDXMY1lrA==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.0.0.tgz", @@ -398,12 +665,36 @@ "node": ">=v12.0.0" } }, + "node_modules/@pkgr/core": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.1.1.tgz", + "integrity": "sha512-cq8o4cWH0ibXh9VGi5P20Tu9XF/0fFXl9EUinr9QfTM7a7p0oTA4iJRCQWppXR1Pg8dSM0UCItCkPwsk9qWWYA==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + } + }, "node_modules/@types/color-name": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", "dev": true }, + "node_modules/@types/estree": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "dev": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true + }, "node_modules/@types/linkify-it": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-3.0.2.tgz", @@ -448,9 +739,9 @@ "dev": true }, "node_modules/acorn": { - "version": "6.4.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.2.tgz", - "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", + "version": "8.14.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", + "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -460,12 +751,12 @@ } }, "node_modules/acorn-jsx": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.0.0.tgz", - "integrity": "sha512-XkB50fn0MURDyww9+UYL3c1yLbOBz0ZFvrdYlGB8l+Ije1oSC75qAqrzSPjYQbdnQUzhlUGNKuesryAv0gxZOg==", + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", "dev": true, "peerDependencies": { - "acorn": "^6.0.0" + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "node_modules/aggregate-error": { @@ -497,30 +788,6 @@ "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/ajv/node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true - }, - "node_modules/ansi-escapes": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/ansi-regex": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", - "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", @@ -560,36 +827,6 @@ "sprintf-js": "~1.0.2" } }, - "node_modules/array-union": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", - "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", - "dev": true, - "dependencies": { - "array-uniq": "^1.0.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/array-uniq": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", - "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/arrify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", - "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/asn1": { "version": "0.2.6", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", @@ -694,25 +931,13 @@ "node": ">=8" } }, - "node_modules/caller-path": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", - "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=", - "dev": true, - "dependencies": { - "callsites": "^0.2.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/callsites": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-0.2.0.tgz", - "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true, "engines": { - "node": ">=0.10.0" + "node": ">=6" } }, "node_modules/camelcase": { @@ -756,19 +981,6 @@ "node": ">=4" } }, - "node_modules/chardet": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", - "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", - "dev": true - }, - "node_modules/circular-json": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz", - "integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==", - "deprecated": "CircularJSON is in maintenance only, flatted is its successor.", - "dev": true - }, "node_modules/clean-stack": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", @@ -778,24 +990,6 @@ "node": ">=6" } }, - "node_modules/cli-cursor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", - "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", - "dev": true, - "dependencies": { - "restore-cursor": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/cli-width": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", - "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", - "dev": true - }, "node_modules/cliui": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", @@ -927,19 +1121,17 @@ "dev": true }, "node_modules/cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "dependencies": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" }, "engines": { - "node": ">=4.8" + "node": ">= 8" } }, "node_modules/dashdash": { @@ -979,9 +1171,9 @@ "dev": true }, "node_modules/deep-is": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true }, "node_modules/default-require-extensions": { @@ -1014,24 +1206,6 @@ "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=", "dev": true }, - "node_modules/del": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", - "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", - "dev": true, - "dependencies": { - "globby": "^5.0.0", - "is-path-cwd": "^1.0.0", - "is-path-in-cwd": "^1.0.0", - "object-assign": "^4.0.1", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0", - "rimraf": "^2.2.8" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -1041,18 +1215,6 @@ "node": ">=0.4.0" } }, - "node_modules/doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/ecc-jsbn": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", @@ -1145,159 +1307,315 @@ } }, "node_modules/eslint": { - "version": "5.7.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.7.0.tgz", - "integrity": "sha512-zYCeFQahsxffGl87U2aJ7DPyH8CbWgxBC213Y8+TCanhUTf2gEvfq3EKpHmEcozTLyPmGe9LZdMAwC/CpJBM5A==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.0.0", - "ajv": "^6.5.3", - "chalk": "^2.1.0", - "cross-spawn": "^6.0.5", - "debug": "^4.0.1", - "doctrine": "^2.1.0", - "eslint-scope": "^4.0.0", - "eslint-utils": "^1.3.1", - "eslint-visitor-keys": "^1.0.0", - "espree": "^4.0.0", - "esquery": "^1.0.1", + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.18.0.tgz", + "integrity": "sha512-+waTfRWQlSbpt3KWE+CjrPPYnbq9kfZIYUqapc0uBXyjTp8aYXZDsUH16m39Ryq3NjAVP4tjuF7KaukeqoCoaA==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.19.0", + "@eslint/core": "^0.10.0", + "@eslint/eslintrc": "^3.2.0", + "@eslint/js": "9.18.0", + "@eslint/plugin-kit": "^0.2.5", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.1", + "@types/estree": "^1.0.6", + "@types/json-schema": "^7.0.15", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.2.0", + "eslint-visitor-keys": "^4.2.0", + "espree": "^10.3.0", + "esquery": "^1.5.0", "esutils": "^2.0.2", - "file-entry-cache": "^2.0.0", - "functional-red-black-tree": "^1.0.1", - "glob": "^7.1.2", - "globals": "^11.7.0", - "ignore": "^4.0.6", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", "imurmurhash": "^0.1.4", - "inquirer": "^6.1.0", - "is-resolvable": "^1.1.0", - "js-yaml": "^3.12.0", + "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.3.0", - "lodash": "^4.17.5", - "minimatch": "^3.0.4", - "mkdirp": "^0.5.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", "natural-compare": "^1.4.0", - "optionator": "^0.8.2", - "path-is-inside": "^1.0.2", - "pluralize": "^7.0.0", - "progress": "^2.0.0", - "regexpp": "^2.0.1", - "require-uncached": "^1.0.3", - "semver": "^5.5.1", - "strip-ansi": "^4.0.0", - "strip-json-comments": "^2.0.1", - "table": "^5.0.2", - "text-table": "^0.2.0" + "optionator": "^0.9.3" }, "bin": { "eslint": "bin/eslint.js" }, "engines": { - "node": "^6.14.0 || ^8.10.0 || >=9.10.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } } }, "node_modules/eslint-config-prettier": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-3.1.0.tgz", - "integrity": "sha512-QYGfmzuc4q4J6XIhlp8vRKdI/fI0tQfQPy1dME3UOLprE+v4ssH/3W9LM2Q7h5qBcy5m0ehCrBDU2YF8q6OY8w==", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.0.1.tgz", + "integrity": "sha512-lZBts941cyJyeaooiKxAtzoPHTN+GbQTJFAIdQbRhA4/8whaAraEh47Whw/ZFfrjNSnlAxqfm9i0XVAEkULjCw==", "dev": true, - "dependencies": { - "get-stdin": "^6.0.0" - }, "bin": { - "eslint-config-prettier-check": "bin/cli.js" + "eslint-config-prettier": "build/bin/cli.js" }, "peerDependencies": { - "eslint": ">=3.14.1" + "eslint": ">=7.0.0" } }, "node_modules/eslint-plugin-prettier": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.0.0.tgz", - "integrity": "sha512-4g11opzhqq/8+AMmo5Vc2Gn7z9alZ4JqrbZ+D4i8KlSyxeQhZHlmIrY8U9Akf514MoEhogPa87Jgkq87aZ2Ohw==", + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.1.tgz", + "integrity": "sha512-gH3iR3g4JfF+yYPaJYkN7jEl9QbweL/YfkoRlNnuIEHEz1vHVlCmWOS+eGGiRuzHQXdJFCOTxRgvju9b8VUmrw==", "dev": true, "dependencies": { - "prettier-linter-helpers": "^1.0.0" + "prettier-linter-helpers": "^1.0.0", + "synckit": "^0.9.1" }, "engines": { - "node": ">=6.0.0" + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-plugin-prettier" }, "peerDependencies": { - "eslint": ">= 5.0.0", - "prettier": ">= 1.13.0" + "@types/eslint": ">=8.0.0", + "eslint": ">=8.0.0", + "eslint-config-prettier": "*", + "prettier": ">=3.0.0" + }, + "peerDependenciesMeta": { + "@types/eslint": { + "optional": true + }, + "eslint-config-prettier": { + "optional": true + } } }, "node_modules/eslint-scope": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.2.0.tgz", + "integrity": "sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", + "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/eslint/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/eslint/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/eslint/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/eslint/node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/eslint/node_modules/escape-string-regexp": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.0.tgz", - "integrity": "sha512-1G6UTDi7Jc1ELFwnR58HV4fK9OQK4S6N985f166xqXxpjU6plxFISJa2Ba9KCQuFa8RCnj/lSFJbHo7UFDBnUA==", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "dependencies": { - "esrecurse": "^4.1.0", - "estraverse": "^4.1.1" + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" }, "engines": { - "node": ">=4.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint-utils": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.3.tgz", - "integrity": "sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==", + "node_modules/eslint/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/eslint/node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/eslint/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "dependencies": { - "eslint-visitor-keys": "^1.1.0" + "yocto-queue": "^0.1.0" }, "engines": { - "node": ">=6" - } - }, - "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz", - "integrity": "sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A==", - "dev": true, - "engines": { - "node": ">=4" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint-visitor-keys": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", - "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", + "node_modules/eslint/node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, "engines": { - "node": ">=4" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint/node_modules/debug": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.0.tgz", - "integrity": "sha512-heNPJUJIqC+xB6ayLAMHaIrmN9HKa7aQO8MGqKpvCA+uJYVcvR6l5kgdrhRuwPFHU7P5/A1w0BjByPHwpfTDKg==", - "deprecated": "Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)", + "node_modules/eslint/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "dependencies": { - "ms": "^2.1.1" + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" } }, - "node_modules/eslint/node_modules/ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", - "dev": true - }, "node_modules/espree": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-4.1.0.tgz", - "integrity": "sha512-I5BycZW6FCVIub93TeVY1s7vjhP9CY6cXCznIRfiig7nRviKZYdRnj/sHEWC6A7WE9RDWOFq9+7OsWSYz8qv2w==", + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.3.0.tgz", + "integrity": "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==", "dev": true, "dependencies": { - "acorn": "^6.0.2", - "acorn-jsx": "^5.0.0", - "eslint-visitor-keys": "^1.0.0" + "acorn": "^8.14.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.0" }, "engines": { - "node": ">=6.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, "node_modules/esprima": { @@ -1314,42 +1632,42 @@ } }, "node_modules/esquery": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", - "integrity": "sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", "dev": true, "dependencies": { - "estraverse": "^4.0.0" + "estraverse": "^5.1.0" }, "engines": { - "node": ">=0.6" + "node": ">=0.10" } }, "node_modules/esrecurse": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", - "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "dependencies": { - "estraverse": "^4.1.0" + "estraverse": "^5.2.0" }, "engines": { "node": ">=4.0" } }, "node_modules/estraverse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", - "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, "engines": { - "node": ">=0.10.0" + "node": ">=4.0" } }, "node_modules/esutils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true, "engines": { "node": ">=0.10.0" @@ -1361,20 +1679,6 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true }, - "node_modules/external-editor": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.0.3.tgz", - "integrity": "sha512-bn71H9+qWoOQKyZDo25mOMVpSmXROAsTJVVVYzrrtol3d4y+AsKjf4Iwl2Q+IuT0kFSQ1qo166UuIwqYq7mGnA==", - "dev": true, - "dependencies": { - "chardet": "^0.7.0", - "iconv-lite": "^0.4.24", - "tmp": "^0.0.33" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", @@ -1384,6 +1688,12 @@ "node >=0.6.0" ] }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, "node_modules/fast-diff": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", @@ -1399,32 +1709,19 @@ "node_modules/fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", "dev": true }, - "node_modules/figures": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", - "dev": true, - "dependencies": { - "escape-string-regexp": "^1.0.5" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/file-entry-cache": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-2.0.0.tgz", - "integrity": "sha1-w5KZDD5oR4PYOLjISkXYoEhFg2E=", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", "dev": true, "dependencies": { - "flat-cache": "^1.2.1", - "object-assign": "^4.0.1" + "flat-cache": "^4.0.0" }, "engines": { - "node": ">=0.10.0" + "node": ">=16.0.0" } }, "node_modules/finalhandler": { @@ -1476,20 +1773,24 @@ } }, "node_modules/flat-cache": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-1.3.0.tgz", - "integrity": "sha1-0wMLMrOBVPTjt+nHCfSQ9++XxIE=", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", "dev": true, "dependencies": { - "circular-json": "^0.3.1", - "del": "^2.0.2", - "graceful-fs": "^4.1.2", - "write": "^0.2.1" + "flatted": "^3.2.9", + "keyv": "^4.5.4" }, "engines": { - "node": ">=0.10.0" + "node": ">=16" } }, + "node_modules/flatted": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz", + "integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==", + "dev": true + }, "node_modules/for-each": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", @@ -1512,65 +1813,6 @@ "node": ">=8.0.0" } }, - "node_modules/foreground-child/node_modules/cross-spawn": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz", - "integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==", - "dev": true, - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/foreground-child/node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/foreground-child/node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/foreground-child/node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/foreground-child/node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", @@ -1612,12 +1854,6 @@ "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, - "node_modules/functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true - }, "node_modules/gensync": { "version": "1.0.0-beta.1", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.1.tgz", @@ -1636,15 +1872,6 @@ "node": "6.* || 8.* || >= 10.*" } }, - "node_modules/get-stdin": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", - "integrity": "sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/getpass": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", @@ -1671,30 +1898,28 @@ "node": "*" } }, - "node_modules/globals": { - "version": "11.8.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.8.0.tgz", - "integrity": "sha512-io6LkyPVuzCHBSQV9fmOwxZkUk6nIaGmxheLDgmuFv89j0fm2aqDbIXKAGfzCMHqz3HLF2Zf8WSG6VqMh2qFmA==", + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, + "dependencies": { + "is-glob": "^4.0.3" + }, "engines": { - "node": ">=4" + "node": ">=10.13.0" } }, - "node_modules/globby": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", - "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", + "node_modules/globals": { + "version": "15.14.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-15.14.0.tgz", + "integrity": "sha512-OkToC372DtlQeje9/zHIo5CT8lRP/FUgEOKBEhU4e0abL7J7CD24fD9ohiLN5hagG/kWCYj4K5oaxxtj2Z0Dig==", "dev": true, - "dependencies": { - "array-union": "^1.0.1", - "arrify": "^1.0.0", - "glob": "^7.0.3", - "object-assign": "^4.0.1", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0" - }, "engines": { - "node": ">=0.10.0" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/graceful-fs": { @@ -1826,25 +2051,29 @@ "npm": ">=1.3.7" } }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", "dev": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, "engines": { - "node": ">=0.10.0" + "node": ">= 4" } }, - "node_modules/ignore": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, "engines": { - "node": ">= 4" + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/imurmurhash": { @@ -1881,30 +2110,6 @@ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "dev": true }, - "node_modules/inquirer": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.0.tgz", - "integrity": "sha512-QIEQG4YyQ2UYZGDC4srMZ7BjHOmNk1lR2JQj5UknBapklm6WHA+VVH7N+sUdX3A7NeCfGF8o4X1S3Ao7nAcIeg==", - "dev": true, - "dependencies": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", - "cli-cursor": "^2.1.0", - "cli-width": "^2.0.0", - "external-editor": "^3.0.0", - "figures": "^2.0.0", - "lodash": "^4.17.10", - "mute-stream": "0.0.7", - "run-async": "^2.2.0", - "rxjs": "^6.1.0", - "string-width": "^2.1.0", - "strip-ansi": "^4.0.0", - "through": "^2.3.6" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/is-callable": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", @@ -1923,54 +2128,27 @@ "node": ">= 0.4" } }, - "node_modules/is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/is-path-cwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", - "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-path-in-cwd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz", - "integrity": "sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ==", + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "dev": true, - "dependencies": { - "is-path-inside": "^1.0.0" - }, "engines": { "node": ">=0.10.0" } }, - "node_modules/is-path-inside": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", - "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "dependencies": { - "path-is-inside": "^1.0.1" + "is-extglob": "^2.1.1" }, "engines": { "node": ">=0.10.0" } }, - "node_modules/is-promise": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", - "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", - "dev": true - }, "node_modules/is-regex": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", @@ -1983,12 +2161,6 @@ "node": ">= 0.4" } }, - "node_modules/is-resolvable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz", - "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==", - "dev": true - }, "node_modules/is-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", @@ -2111,29 +2283,6 @@ "node": ">=8" } }, - "node_modules/istanbul-lib-processinfo/node_modules/cross-spawn": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz", - "integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==", - "dev": true, - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/istanbul-lib-processinfo/node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/istanbul-lib-processinfo/node_modules/rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", @@ -2149,42 +2298,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/istanbul-lib-processinfo/node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-processinfo/node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-processinfo/node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/istanbul-lib-report": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", @@ -2350,22 +2463,10 @@ "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", "dev": true, "bin": { - "mkdirp": "bin/cmd.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jsdoc/node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "engines": { - "node": ">=8" + "mkdirp": "bin/cmd.js" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "engines": { + "node": ">=10" } }, "node_modules/jsesc": { @@ -2380,6 +2481,12 @@ "node": ">=4" } }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true + }, "node_modules/json-int64": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/json-int64/-/json-int64-1.0.2.tgz", @@ -2440,6 +2547,15 @@ "node": ">=0.6.0" } }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "dependencies": { + "json-buffer": "3.0.1" + } + }, "node_modules/klaw": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", @@ -2450,13 +2566,13 @@ } }, "node_modules/levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "dependencies": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" }, "engines": { "node": ">= 0.8.0" @@ -2495,6 +2611,12 @@ "integrity": "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI=", "dev": true }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, "node_modules/make-dir": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", @@ -2590,15 +2712,6 @@ "node": ">= 0.6" } }, - "node_modules/mimic-fn": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", - "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -2620,42 +2733,18 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/mkdirp": { - "version": "0.5.5", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", - "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", - "dev": true, - "dependencies": { - "minimist": "^1.2.5" - }, - "bin": { - "mkdirp": "bin/cmd.js" - } - }, "node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, - "node_modules/mute-stream": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", - "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", - "dev": true - }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", "dev": true }, - "node_modules/nice-try": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", - "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", - "dev": true - }, "node_modules/node-gyp-build": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-3.7.0.tgz", @@ -2779,15 +2868,6 @@ "node": "*" } }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/object-inspect": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.6.0.tgz", @@ -2824,44 +2904,23 @@ "wrappy": "1" } }, - "node_modules/onetime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", - "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", - "dev": true, - "dependencies": { - "mimic-fn": "^1.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/optionator": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", - "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", "dev": true, "dependencies": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.4", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "wordwrap": "~1.0.0" + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" }, "engines": { "node": ">= 0.8.0" } }, - "node_modules/os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/p-limit": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.2.tgz", @@ -2931,6 +2990,18 @@ "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==", "dev": true }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/parseurl": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", @@ -2958,19 +3029,13 @@ "node": ">=0.10.0" } }, - "node_modules/path-is-inside": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", - "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", - "dev": true - }, "node_modules/path-key": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true, "engines": { - "node": ">=4" + "node": ">=8" } }, "node_modules/performance-now": { @@ -2979,36 +3044,6 @@ "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==", "dev": true }, - "node_modules/pify": { - "version": "2.3.0", - "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "dependencies": { - "pinkie": "^2.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", @@ -3021,34 +3056,28 @@ "node": ">=8" } }, - "node_modules/pluralize": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", - "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true, "engines": { "node": ">= 0.8.0" } }, "node_modules/prettier": { - "version": "1.14.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.14.3.tgz", - "integrity": "sha512-qZDVnCrnpsRJJq5nSsiHCE3BYMED2OtsI+cmzIzF1QIfqm5ALf8tEJcO27zV1gKNKRPdhjO0dNWnrzssDQ1tFg==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", + "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", "dev": true, "bin": { - "prettier": "bin-prettier.js" + "prettier": "bin/prettier.cjs" }, "engines": { - "node": ">=4" + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" } }, "node_modules/prettier-linter-helpers": { @@ -3075,15 +3104,6 @@ "node": ">=8" } }, - "node_modules/progress": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.1.tgz", - "integrity": "sha512-OE+a6vzqazc+K6LxJrX5UPyKFvGnL5CYmq2jFGNIBWHpc4QyE49/YOumcrpQFJpfejmvRtbJzgO1zPmMCqlbBg==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/psl": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", @@ -3117,15 +3137,6 @@ "node": ">=0.6" } }, - "node_modules/regexpp": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", - "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", - "dev": true, - "engines": { - "node": ">=6.5.0" - } - }, "node_modules/release-zalgo": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz", @@ -3185,19 +3196,6 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, - "node_modules/require-uncached": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz", - "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", - "dev": true, - "dependencies": { - "caller-path": "^0.1.0", - "resolve-from": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/requizzle": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.3.tgz", @@ -3208,23 +3206,10 @@ } }, "node_modules/resolve-from": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz", - "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/restore-cursor": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", - "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", "dev": true, - "dependencies": { - "onetime": "^2.0.0", - "signal-exit": "^3.0.2" - }, "engines": { "node": ">=4" } @@ -3238,42 +3223,6 @@ "through": "~2.3.4" } }, - "node_modules/rimraf": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", - "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", - "dev": true, - "dependencies": { - "glob": "^7.0.5" - }, - "bin": { - "rimraf": "bin.js" - } - }, - "node_modules/run-async": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", - "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", - "dev": true, - "dependencies": { - "is-promise": "^2.1.0" - }, - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", - "dev": true, - "dependencies": { - "tslib": "^1.9.0" - }, - "engines": { - "npm": ">=2.0.0" - } - }, "node_modules/safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -3302,24 +3251,24 @@ "dev": true }, "node_modules/shebang-command": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "dependencies": { - "shebang-regex": "^1.0.0" + "shebang-regex": "^3.0.0" }, "engines": { - "node": ">=0.10.0" + "node": ">=8" } }, "node_modules/shebang-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true, "engines": { - "node": ">=0.10.0" + "node": ">=8" } }, "node_modules/signal-exit": { @@ -3328,18 +3277,6 @@ "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", "dev": true }, - "node_modules/slice-ansi": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", - "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", - "dev": true, - "dependencies": { - "is-fullwidth-code-point": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/spawn-wrap": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-2.0.0.tgz", @@ -3372,21 +3309,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/spawn-wrap/node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -3427,19 +3349,6 @@ "node": ">= 0.6" } }, - "node_modules/string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "dev": true, - "dependencies": { - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^4.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/string.prototype.trim": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.1.2.tgz", @@ -3454,18 +3363,6 @@ "node": ">= 0.4" } }, - "node_modules/strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "dev": true, - "dependencies": { - "ansi-regex": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/strip-bom": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", @@ -3476,12 +3373,15 @@ } }, "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true, "engines": { - "node": ">=0.10.0" + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/supports-color": { @@ -3496,19 +3396,20 @@ "node": ">=4" } }, - "node_modules/table": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/table/-/table-5.1.0.tgz", - "integrity": "sha512-e542in22ZLhD/fOIuXs/8yDZ9W61ltF8daM88rkRNtgTIct+vI2fTnAyu/Db2TCfEcI8i7mjZz6meLq0nW7TYg==", + "node_modules/synckit": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.9.2.tgz", + "integrity": "sha512-vrozgXDQwYO72vHjUb/HnFbQx1exDjoKzqx23aXEg2a9VIg2TSFZ8FmeZpTjUCFMYw7mpX4BE2SFu8wI7asYsw==", "dev": true, "dependencies": { - "ajv": "^6.5.3", - "lodash": "^4.17.10", - "slice-ansi": "1.0.0", - "string-width": "^2.1.1" + "@pkgr/core": "^0.1.0", + "tslib": "^2.6.2" }, "engines": { - "node": ">=6.0.0" + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" } }, "node_modules/tape": { @@ -3584,30 +3485,12 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", - "dev": true - }, "node_modules/through": { "version": "2.3.8", "resolved": "http://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", "dev": true }, - "node_modules/tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "dev": true, - "dependencies": { - "os-tmpdir": "~1.0.2" - }, - "engines": { - "node": ">=0.6.0" - } - }, "node_modules/to-fast-properties": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", @@ -3631,9 +3514,9 @@ } }, "node_modules/tslib": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", - "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==", + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true }, "node_modules/tunnel-agent": { @@ -3655,12 +3538,12 @@ "dev": true }, "node_modules/type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "dependencies": { - "prelude-ls": "~1.1.2" + "prelude-ls": "^1.2.1" }, "engines": { "node": ">= 0.8.0" @@ -3777,15 +3660,18 @@ } }, "node_modules/which": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "dependencies": { "isexe": "^2.0.0" }, "bin": { - "which": "bin/which" + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" } }, "node_modules/which-module": { @@ -3794,11 +3680,14 @@ "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, - "node_modules/wordwrap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", - "dev": true + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, "node_modules/wrap-ansi": { "version": "6.2.0", @@ -3898,18 +3787,6 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, - "node_modules/write": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz", - "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", - "dev": true, - "dependencies": { - "mkdirp": "^0.5.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/write-file-atomic": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.1.tgz", @@ -4020,6 +3897,18 @@ "engines": { "node": ">=6" } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/package.json b/package.json index 5b02952667b..6ed792df260 100644 --- a/package.json +++ b/package.json @@ -43,20 +43,22 @@ "ws": "^5.2.3" }, "devDependencies": { + "@eslint/js": "^9.18.0", "@types/node": "^10.12.6", "@types/node-int64": "^0.4.29", "@types/q": "^1.5.1", "buffer-equals": "^1.0.4", "commander": "^2.14.1", "connect": "^3.6.6", - "eslint": "^5.7.0", - "eslint-config-prettier": "^3.1.0", - "eslint-plugin-prettier": "^3.0.0", + "eslint": "^9.18.0", + "eslint-config-prettier": "^10.0.1", + "eslint-plugin-prettier": "^5.2.1", + "globals": "^15.14.0", "html-validator-cli": "^2.0.0", "jsdoc": "^4.0.2", "json-int64": "^1.0.2", "nyc": "^15.0.0", - "prettier": "^1.14.3", + "prettier": "^3.4.2", "tape": "^4.9.0", "typescript": "^3.1.6", "utf-8-validate": "^5.0.0" @@ -65,8 +67,8 @@ "cover": "lib/nodejs/test/testAll.sh COVER", "test": "lib/nodejs/test/testAll.sh", "test-ts": "lib/nodets/test/testAll.sh", - "prettier": "prettier --write '**/*.js'", - "lint": "eslint lib/nodejs/. --ext .js", - "lint-tests": "eslint lib/nodejs/test/. --ext .js" + "prettier": "prettier --write '**/*.{js,mjs,ts}'", + "lint": "eslint lib/nodejs", + "lint-tests": "eslint lib/nodejs/test" } } diff --git a/test/crossrunner/compat.py b/test/crossrunner/compat.py index 932a48cd6ad..a670c33f266 100644 --- a/test/crossrunner/compat.py +++ b/test/crossrunner/compat.py @@ -1,24 +1,7 @@ import os -import sys -if sys.version_info[0] == 2: - _ENCODE = sys.getfilesystemencoding() +path_join = os.path.join +str_join = str.join - def path_join(*args): - bin_args = map(lambda a: a.decode(_ENCODE), args) - return os.path.join(*bin_args).encode(_ENCODE) - - def str_join(left, right): - bin_args = map(lambda a: a.decode(_ENCODE), right) - b = left.decode(_ENCODE) - return b.join(bin_args).encode(_ENCODE) - - logfile_open = open - -else: - - path_join = os.path.join - str_join = str.join - - def logfile_open(*args): - return open(*args, errors='replace') +def logfile_open(*args): + return open(*args, errors='replace') diff --git a/test/crossrunner/report.py b/test/crossrunner/report.py index 5baf1619524..7e1b0c747e9 100644 --- a/test/crossrunner/report.py +++ b/test/crossrunner/report.py @@ -17,7 +17,6 @@ # under the License. # -from __future__ import print_function import datetime import json import multiprocessing @@ -317,10 +316,7 @@ def _print_unexpected_success(self): self._print_bar() def _http_server_command(self, port): - if sys.version_info[0] < 3: - return 'python -m SimpleHTTPServer %d' % port - else: - return 'python -m http.server %d' % port + return 'python -m http.server %d' % port def _print_footer(self): fail_count = len(self._expected_failure) + len(self._unexpected_failure) diff --git a/test/py/FastbinaryTest.py b/test/py/FastbinaryTest.py index 05c0bb6d15a..f6803575cdb 100755 --- a/test/py/FastbinaryTest.py +++ b/test/py/FastbinaryTest.py @@ -25,8 +25,6 @@ # TODO(dreiss): Test error cases. Check for memory leaks. -from __future__ import print_function - import math import os import sys @@ -68,15 +66,11 @@ def isOpen(self): ooe2.integer64 = 64 ooe2.double_precision = (math.sqrt(5) + 1) / 2 ooe2.some_characters = ":R (me going \"rrrr\")" -ooe2.zomg_unicode = u"\xd3\x80\xe2\x85\xae\xce\x9d\x20"\ - u"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe"\ - u"\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"\ - u"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba"\ - u"\xc7\x83\xe2\x80\xbc" - -if sys.version_info[0] == 2 and os.environ.get('THRIFT_TEST_PY_NO_UTF8STRINGS'): - ooe1.zomg_unicode = ooe1.zomg_unicode.encode('utf8') - ooe2.zomg_unicode = ooe2.zomg_unicode.encode('utf8') +ooe2.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"\ + "\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe"\ + "\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"\ + "\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba"\ + "\xc7\x83\xe2\x80\xbc" hm = HolyMoley(**{"big": [], "contain": set(), "bonks": {}}) hm.big.append(ooe1) @@ -86,10 +80,7 @@ def isOpen(self): hm.contain.add(("and a one", "and a two")) hm.contain.add(("then a one, two", "three!", "FOUR!")) -if sys.version_info[0] == 2 and os.environ.get('THRIFT_TEST_PY_NO_UTF8STRINGS'): - hm.contain.add((u"\xd7\n\a\t".encode('utf8'),)) -else: - hm.contain.add((u"\xd7\n\a\t",)) +hm.contain.add(("\xd7\n\a\t",)) hm.contain.add(()) hm.bonks["nothing"] = [] diff --git a/test/py/RunClientServer.py b/test/py/RunClientServer.py index 583d88a6422..f48224fa5cf 100755 --- a/test/py/RunClientServer.py +++ b/test/py/RunClientServer.py @@ -19,8 +19,6 @@ # under the License. # -from __future__ import division -from __future__ import print_function import platform import copy import os diff --git a/test/py/SerializationTest.py b/test/py/SerializationTest.py index f47c3d4d6af..218f26c43be 100755 --- a/test/py/SerializationTest.py +++ b/test/py/SerializationTest.py @@ -278,9 +278,6 @@ def testCompactStruct(self): self.assertTrue(len(rep) > 0) def testIntegerLimits(self): - if (sys.version_info[0] == 2 and sys.version_info[1] <= 6): - print('Skipping testIntegerLimits for Python 2.6') - return bad_values = [CompactProtoTestStruct(a_byte=128), CompactProtoTestStruct(a_byte=-129), CompactProtoTestStruct(a_i16=32768), CompactProtoTestStruct(a_i16=-32769), CompactProtoTestStruct(a_i32=2147483648), CompactProtoTestStruct(a_i32=-2147483649), diff --git a/test/py/TestClient.py b/test/py/TestClient.py index 61a9c60404f..d80ddf46f70 100755 --- a/test/py/TestClient.py +++ b/test/py/TestClient.py @@ -106,9 +106,6 @@ def testString(self): Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語""" - if sys.version_info[0] == 2 and os.environ.get('THRIFT_TEST_PY_NO_UTF8STRINGS'): - s1 = s1.encode('utf8') - s2 = s2.encode('utf8') self.assertEqual(self.client.testString(s1), s1) self.assertEqual(self.client.testString(s2), s2) diff --git a/test/py/TestServer.py b/test/py/TestServer.py index 81ae1ad62ee..e062378a8fa 100755 --- a/test/py/TestServer.py +++ b/test/py/TestServer.py @@ -18,7 +18,6 @@ # specific language governing permissions and limitations # under the License. # -from __future__ import division import logging import os import signal diff --git a/test/result.js b/test/result.js index 18b1a593d18..a6dd00a7a9f 100644 --- a/test/result.js +++ b/test/result.js @@ -18,47 +18,62 @@ */ -$.getJSON('results.json', function(results) { - $(document).ready(function() { - var transport = 3; - var socket = 4; - var success = 5; - var expected = 6; - var returnCode = 7; - var logFile = 8; - testTable = $('#test_results').DataTable({ - data: results['results'], - columnDefs: [ - { - targets: 3, - render: function(data, type, row) { - return row[transport] + '-' + row[socket]; - }, - }, - { - targets: 4, - render: function(data, type, row) { - return (row[success] ? 'success' : 'failure') - + '(' + (row[returnCode] == 128 ? 'timeout' : row[returnCode]) + ')' - + '(Server, ' - + 'Client)'; - }, - }, - { - targets: 5, - render: function(data, type, row) { - // 'yes' rather than 'expected' to ease search - return row[expected] ? 'yes' : 'unexpected'; - }, - } - ], - }); - $('#test_results_filter label input').focus().val('unexpected failure'); - $('#test_info').text( - "Test Date: " + results['date'] + "\n" + - "Revision: " + results['revision'] + "\n" + - "Platform: " + results['platform'] + "\n" + - "Test duration: " + results['duration']) + " seconds"; +$.getJSON("results.json", function (results) { + $(document).ready(function () { + var transport = 3; + var socket = 4; + var success = 5; + var expected = 6; + var returnCode = 7; + var logFile = 8; + testTable = $("#test_results").DataTable({ + data: results["results"], + columnDefs: [ + { + targets: 3, + render: function (data, type, row) { + return row[transport] + "-" + row[socket]; + }, + }, + { + targets: 4, + render: function (data, type, row) { + return ( + (row[success] ? "success" : "failure") + + "(" + + (row[returnCode] == 128 ? "timeout" : row[returnCode]) + + ")" + + '(Server, ' + + 'Client)' + ); + }, + }, + { + targets: 5, + render: function (data, type, row) { + // 'yes' rather than 'expected' to ease search + return row[expected] ? "yes" : "unexpected"; + }, + }, + ], }); + $("#test_results_filter label input").focus().val("unexpected failure"); + $("#test_info").text( + "Test Date: " + + results["date"] + + "\n" + + "Revision: " + + results["revision"] + + "\n" + + "Platform: " + + results["platform"] + + "\n" + + "Test duration: " + + results["duration"], + ) + " seconds"; + }); }); - diff --git a/test/test.py b/test/test.py index cd5c4d41d6e..a288c265ae1 100755 --- a/test/test.py +++ b/test/test.py @@ -27,7 +27,6 @@ # subprocess management that are needed for reliability. # -from __future__ import print_function from itertools import chain import json import logging diff --git a/tutorial/nodejs/NodeClient.js b/tutorial/nodejs/NodeClient.js index b4886e82608..e4e92cc0f30 100644 --- a/tutorial/nodejs/NodeClient.js +++ b/tutorial/nodejs/NodeClient.js @@ -17,47 +17,44 @@ * under the License. */ -var thrift = require('thrift'); -var Calculator = require('./gen-nodejs/Calculator'); -var ttypes = require('./gen-nodejs/tutorial_types'); -const assert = require('assert'); +var thrift = require("thrift"); +var Calculator = require("./gen-nodejs/Calculator"); +var ttypes = require("./gen-nodejs/tutorial_types"); +const assert = require("assert"); var transport = thrift.TBufferedTransport; var protocol = thrift.TBinaryProtocol; var connection = thrift.createConnection("localhost", 9090, { - transport : transport, - protocol : protocol + transport: transport, + protocol: protocol, }); -connection.on('error', function(err) { +connection.on("error", function (err) { assert(false, err); }); // Create a Calculator client with the connection var client = thrift.createClient(Calculator, connection); - -client.ping(function(err, response) { - console.log('ping()'); +client.ping(function (err, response) { + console.log("ping()"); }); - -client.add(1,1, function(err, response) { +client.add(1, 1, function (err, response) { console.log("1+1=" + response); }); - work = new ttypes.Work(); work.op = ttypes.Operation.DIVIDE; work.num1 = 1; work.num2 = 0; -client.calculate(1, work, function(err, message) { +client.calculate(1, work, function (err, message) { if (err) { console.log("InvalidOperation " + err); } else { - console.log('Whoa? You know how to divide by zero?'); + console.log("Whoa? You know how to divide by zero?"); } }); @@ -65,11 +62,11 @@ work.op = ttypes.Operation.SUBTRACT; work.num1 = 15; work.num2 = 10; -client.calculate(1, work, function(err, message) { - console.log('15-10=' + message); +client.calculate(1, work, function (err, message) { + console.log("15-10=" + message); - client.getStruct(1, function(err, message){ - console.log('Check log: ' + message.value); + client.getStruct(1, function (err, message) { + console.log("Check log: " + message.value); //close the connection once we're done connection.end(); diff --git a/tutorial/nodejs/NodeClientPromise.js b/tutorial/nodejs/NodeClientPromise.js index e6ff2d7f42c..0ba5f4f005f 100644 --- a/tutorial/nodejs/NodeClientPromise.js +++ b/tutorial/nodejs/NodeClientPromise.js @@ -17,64 +17,62 @@ * under the License. */ -var thrift = require('thrift'); -var Calculator = require('./gen-nodejs/Calculator'); -var ttypes = require('./gen-nodejs/tutorial_types'); -const assert = require('assert'); +var thrift = require("thrift"); +var Calculator = require("./gen-nodejs/Calculator"); +var ttypes = require("./gen-nodejs/tutorial_types"); +const assert = require("assert"); var transport = thrift.TBufferedTransport; var protocol = thrift.TBinaryProtocol; var connection = thrift.createConnection("localhost", 9090, { - transport : transport, - protocol : protocol + transport: transport, + protocol: protocol, }); -connection.on('error', function(err) { +connection.on("error", function (err) { assert(false, err); }); // Create a Calculator client with the connection var client = thrift.createClient(Calculator, connection); +client.ping().then(function () { + console.log("ping()"); +}); -client.ping() - .then(function() { - console.log('ping()'); - }); - -client.add(1,1) - .then(function(response) { - console.log("1+1=" + response); - }); +client.add(1, 1).then(function (response) { + console.log("1+1=" + response); +}); work = new ttypes.Work(); work.op = ttypes.Operation.DIVIDE; work.num1 = 1; work.num2 = 0; -client.calculate(1, work) - .then(function(message) { - console.log('Whoa? You know how to divide by zero?'); +client + .calculate(1, work) + .then(function (message) { + console.log("Whoa? You know how to divide by zero?"); }) - .catch(function(err) { + .catch(function (err) { console.log("InvalidOperation " + err); }); - work.op = ttypes.Operation.SUBTRACT; work.num1 = 15; work.num2 = 10; -client.calculate(1, work) - .then(function(value) { - console.log('15-10=' + value); - return client.getStruct(1); +client + .calculate(1, work) + .then(function (value) { + console.log("15-10=" + value); + return client.getStruct(1); }) - .then(function(message) { - console.log('Check log: ' + message.value); + .then(function (message) { + console.log("Check log: " + message.value); }) - .finally(function() { - //close the connection once we're done - connection.end(); + .finally(function () { + //close the connection once we're done + connection.end(); }); diff --git a/tutorial/nodejs/NodeServer.js b/tutorial/nodejs/NodeServer.js index 2e198825c10..5181e5128d2 100644 --- a/tutorial/nodejs/NodeServer.js +++ b/tutorial/nodejs/NodeServer.js @@ -25,17 +25,17 @@ var SharedStruct = require("./gen-nodejs/shared_types").SharedStruct; var data = {}; var server = thrift.createServer(Calculator, { - ping: function(result) { + ping: function (result) { console.log("ping()"); result(null); }, - add: function(n1, n2, result) { + add: function (n1, n2, result) { console.log("add(", n1, ",", n2, ")"); result(null, n1 + n2); }, - calculate: function(logid, work, result) { + calculate: function (logid, work, result) { console.log("calculate(", logid, ",", work, ")"); var val = 0; @@ -49,7 +49,7 @@ var server = thrift.createServer(Calculator, { if (work.num2 === 0) { var x = new ttypes.InvalidOperation(); x.whatOp = work.op; - x.why = 'Cannot divide by 0'; + x.why = "Cannot divide by 0"; result(x); return; } @@ -57,28 +57,27 @@ var server = thrift.createServer(Calculator, { } else { var x = new ttypes.InvalidOperation(); x.whatOp = work.op; - x.why = 'Invalid operation'; + x.why = "Invalid operation"; result(x); return; } var entry = new SharedStruct(); entry.key = logid; - entry.value = ""+val; + entry.value = "" + val; data[logid] = entry; result(null, val); }, - getStruct: function(key, result) { + getStruct: function (key, result) { console.log("getStruct(", key, ")"); result(null, data[key]); }, - zip: function() { + zip: function () { console.log("zip()"); - } - + }, }); server.listen(9090); diff --git a/tutorial/nodejs/NodeServerPromise.js b/tutorial/nodejs/NodeServerPromise.js index bff287b1823..ddd18f4990c 100644 --- a/tutorial/nodejs/NodeServerPromise.js +++ b/tutorial/nodejs/NodeServerPromise.js @@ -25,16 +25,16 @@ var SharedStruct = require("./gen-nodejs/shared_types").SharedStruct; var data = {}; var server = thrift.createServer(Calculator, { - ping: function() { + ping: function () { console.log("ping()"); }, - add: function(n1, n2) { + add: function (n1, n2) { console.log("add(", n1, ",", n2, ")"); return n1 + n2; }, - calculate: function(logid, work) { + calculate: function (logid, work) { console.log("calculate(", logid, ",", work, ")"); var val = 0; @@ -48,33 +48,32 @@ var server = thrift.createServer(Calculator, { if (work.num2 === 0) { var x = new ttypes.InvalidOperation(); x.whatOp = work.op; - x.why = 'Cannot divide by 0'; - throw x; + x.why = "Cannot divide by 0"; + throw x; } val = work.num1 / work.num2; } else { var x = new ttypes.InvalidOperation(); x.whatOp = work.op; - x.why = 'Invalid operation'; + x.why = "Invalid operation"; throw x; } var entry = new SharedStruct(); entry.key = logid; - entry.value = ""+val; + entry.value = "" + val; data[logid] = entry; return val; }, - getStruct: function(key) { + getStruct: function (key) { console.log("getStruct(", key, ")"); return data[key]; }, - zip: function() { + zip: function () { console.log("zip()"); - } - + }, }); server.listen(9090); diff --git a/tutorial/rs/src/bin/tutorial_client.rs b/tutorial/rs/src/bin/tutorial_client.rs index 4bf2ec098a0..b79ae83e204 100644 --- a/tutorial/rs/src/bin/tutorial_client.rs +++ b/tutorial/rs/src/bin/tutorial_client.rs @@ -107,7 +107,7 @@ fn new_client( // open the underlying TCP stream println!("connecting to tutorial server on {}:{}", host, port); - c.open(&format!("{}:{}", host, port))?; + c.open(format!("{}:{}", host, port))?; // clone the TCP channel into two halves, one which // we'll use for reading, the other for writing