From 7be87b62076914ab979dace6525303f693cebc53 Mon Sep 17 00:00:00 2001 From: Jane He Date: Sat, 14 Dec 2024 00:20:29 +0800 Subject: [PATCH 1/5] tsconfig.json --- .gitignore | 3 +- index.d.ts | 414 -------------------------------- lib/auth/index.d.ts | 47 ---- lib/concurrent/index.d.ts | 45 ---- lib/datastax/graph/index.d.ts | 92 ------- lib/datastax/index.d.ts | 24 -- lib/datastax/search/index.d.ts | 58 ----- lib/geometry/index.d.ts | 67 ------ index.js => lib/index.js | 36 +-- lib/mapping/index.d.ts | 189 --------------- lib/metadata/index.d.ts | 211 ---------------- lib/metrics/index.d.ts | 89 ------- lib/policies/index.d.ts | 210 ---------------- lib/tracker/index.d.ts | 58 ----- lib/types/index.d.ts | 427 --------------------------------- package-lock.json | 18 +- package.json | 6 +- tsconfig.json | 25 ++ 18 files changed, 52 insertions(+), 1967 deletions(-) delete mode 100644 index.d.ts delete mode 100644 lib/auth/index.d.ts delete mode 100644 lib/concurrent/index.d.ts delete mode 100644 lib/datastax/graph/index.d.ts delete mode 100644 lib/datastax/index.d.ts delete mode 100644 lib/datastax/search/index.d.ts delete mode 100644 lib/geometry/index.d.ts rename index.js => lib/index.js (50%) delete mode 100644 lib/mapping/index.d.ts delete mode 100644 lib/metadata/index.d.ts delete mode 100644 lib/metrics/index.d.ts delete mode 100644 lib/policies/index.d.ts delete mode 100644 lib/tracker/index.d.ts delete mode 100644 lib/types/index.d.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore index 1677f5bc7..278d36064 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,5 @@ out/ /docs **/typescript/*.js **/typescript/*.js.map -**/typescript/generated.ts \ No newline at end of file +**/typescript/generated.ts +dist \ No newline at end of file diff --git a/index.d.ts b/index.d.ts deleted file mode 100644 index cf44d76e9..000000000 --- a/index.d.ts +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as events from 'events'; -import * as tls from 'tls'; -import { URL } from 'url'; -import { auth } from './lib/auth'; -import { policies } from './lib/policies'; -import { types } from './lib/types'; -import { metrics } from './lib/metrics'; -import { tracker } from './lib/tracker'; -import { metadata } from './lib/metadata'; -import { datastax } from './lib/datastax/'; -import Long = types.Long; -import Uuid = types.Uuid; -import graph = datastax.graph; - -// Export imported submodules -export { concurrent } from './lib/concurrent'; -export { mapping } from './lib/mapping'; -export { geometry } from './lib/geometry'; -export { auth, datastax, metadata, metrics, policies, tracker, types }; - -export const version: number; - -export function defaultOptions(): ClientOptions; - -export type ValueCallback = (err: Error, val: T) => void; -export type EmptyCallback = (err: Error) => void; -export type ArrayOrObject = any[]|{[key: string]: any}; - -export class Client extends events.EventEmitter { - hosts: HostMap; - keyspace: string; - metadata: metadata.Metadata; - metrics: metrics.ClientMetrics; - - constructor(options: DseClientOptions); - - connect(): Promise; - - connect(callback: EmptyCallback): void; - - execute(query: string, params?: ArrayOrObject, options?: QueryOptions): Promise; - - execute(query: string, params: ArrayOrObject, options: QueryOptions, callback: ValueCallback): void; - - execute(query: string, params: ArrayOrObject, callback: ValueCallback): void; - - execute(query: string, callback: ValueCallback): void; - - executeGraph( - traversal: string, - parameters: { [name: string]: any } | undefined, - options: GraphQueryOptions, - callback: ValueCallback): void; - - executeGraph( - traversal: string, - parameters: { [name: string]: any } | undefined, - callback: ValueCallback): void; - - executeGraph(traversal: string, callback: ValueCallback): void; - - executeGraph( - traversal: string, - parameters?: { [name: string]: any }, - options?: GraphQueryOptions): Promise; - - eachRow(query: string, - params: ArrayOrObject, - options: QueryOptions, - rowCallback: (n: number, row: types.Row) => void, - callback?: ValueCallback): void; - - eachRow(query: string, - params: ArrayOrObject, - rowCallback: (n: number, row: types.Row) => void, - callback?: ValueCallback): void; - - eachRow(query: string, - rowCallback: (n: number, row: types.Row) => void): void; - - stream(query: string, params?: ArrayOrObject, options?: QueryOptions, callback?: EmptyCallback): events.EventEmitter; - - batch( - queries: Array, - options?: QueryOptions): Promise; - - batch( - queries: Array, - options: QueryOptions, - callback: ValueCallback): void; - - batch( - queries: Array, - callback: ValueCallback): void; - - shutdown(): Promise; - - shutdown(callback: EmptyCallback): void; - - getReplicas(keyspace: string, token: Buffer): Host[]; - - getState(): metadata.ClientState; -} - -export interface HostMap extends events.EventEmitter { - length: number; - - forEach(callback: (value: Host, key: string) => void): void; - - get(key: string): Host; - - keys(): string[]; - - values(): Host[]; -} - -export interface Host extends events.EventEmitter { - address: string; - cassandraVersion: string; - datacenter: string; - rack: string; - tokens: string[]; - hostId: types.Uuid; - - canBeConsideredAsUp(): boolean; - - getCassandraVersion(): number[]; - - isUp(): boolean; -} - -export interface ExecutionOptions { - getCaptureStackTrace(): boolean; - - getConsistency(): types.consistencies; - - getCustomPayload(): { [key: string]: any }; - - getFetchSize(): number; - - getFixedHost(): Host; - - getHints(): string[] | string[][]; - - isAutoPage(): boolean; - - isBatchCounter(): boolean; - - isBatchLogged(): boolean; - - isIdempotent(): boolean; - - isPrepared(): boolean; - - isQueryTracing(): boolean; - - getKeyspace(): string; - - getLoadBalancingPolicy(): policies.loadBalancing.LoadBalancingPolicy; - - getPageState(): Buffer; - - getRawQueryOptions(): QueryOptions; - - getReadTimeout(): number; - - getRetryPolicy(): policies.retry.RetryPolicy; - - getRoutingKey(): Buffer | Buffer[]; - - getSerialConsistency(): types.consistencies; - - getTimestamp(): number | Long | undefined | null; - - setHints(hints: string[]): void; -} - -export interface ClientOptions { - contactPoints?: string[]; - localDataCenter?: string; - keyspace?: string; - authProvider?: auth.AuthProvider; - credentials?: { - username: string; - password: string; - } - - cloud?: { - secureConnectBundle: string | URL; - }; - - encoding?: { - map?: Function; - set?: Function; - copyBuffer?: boolean; - useUndefinedAsUnset?: boolean; - useBigIntAsLong?: boolean; - useBigIntAsVarint?: boolean; - }; - isMetadataSyncEnabled?: boolean; - maxPrepared?: number; - metrics?: metrics.ClientMetrics; - policies?: { - addressResolution?: policies.addressResolution.AddressTranslator; - loadBalancing?: policies.loadBalancing.LoadBalancingPolicy; - reconnection?: policies.reconnection.ReconnectionPolicy; - retry?: policies.retry.RetryPolicy; - speculativeExecution?: policies.speculativeExecution.SpeculativeExecutionPolicy; - timestampGeneration?: policies.timestampGeneration.TimestampGenerator; - }; - pooling?: { - coreConnectionsPerHost?: { [key: number]: number; }; - heartBeatInterval?: number; - maxRequestsPerConnection?: number; - warmup?: boolean; - }; - prepareOnAllHosts?: boolean; - profiles?: ExecutionProfile[]; - protocolOptions?: { - maxSchemaAgreementWaitSeconds?: number; - maxVersion?: number; - noCompact?: boolean; - port?: number; - }; - promiseFactory?: (handler: (callback: (err: Error, result?: any) => void) => void) => Promise; - queryOptions?: QueryOptions; - refreshSchemaDelay?: number; - rePrepareOnUp?: boolean; - requestTracker?: tracker.RequestTracker; - socketOptions?: { - coalescingThreshold?: number; - connectTimeout?: number; - defunctReadTimeoutThreshold?: number; - keepAlive?: boolean; - keepAliveDelay?: number; - readTimeout?: number; - tcpNoDelay?: boolean; - }; - sslOptions?: tls.ConnectionOptions; -} - -export interface QueryOptions { - autoPage?: boolean; - captureStackTrace?: boolean; - consistency?: number; - counter?: boolean; - customPayload?: any; - executionProfile?: string | ExecutionProfile; - fetchSize?: number; - hints?: string[] | string[][]; - host?: Host; - isIdempotent?: boolean; - keyspace?: string; - logged?: boolean; - pageState?: Buffer | string; - prepare?: boolean; - readTimeout?: number; - retry?: policies.retry.RetryPolicy; - routingIndexes?: number[]; - routingKey?: Buffer | Buffer[]; - routingNames?: string[]; - serialConsistency?: number; - timestamp?: number | Long; - traceQuery?: boolean; -} - -export interface DseClientOptions extends ClientOptions { - id?: Uuid; - applicationName?: string; - applicationVersion?: string; - monitorReporting?: { enabled?: boolean }; - graphOptions?: GraphOptions; -} - -export interface GraphQueryOptions extends QueryOptions { - graphLanguage?: string; - graphName?: string; - graphReadConsistency?: types.consistencies; - graphSource?: string; - graphWriteConsistency?: types.consistencies; -} - -export type GraphOptions = { - language?: string; - name?: string; - readConsistency?: types.consistencies; - readTimeout?: number; - source?: string; - writeConsistency?: types.consistencies; -}; - -export class ExecutionProfile { - consistency?: types.consistencies; - loadBalancing?: policies.loadBalancing.LoadBalancingPolicy; - name: string; - readTimeout?: number; - retry?: policies.retry.RetryPolicy; - serialConsistency?: types.consistencies; - graphOptions?: { - name?: string; - language?: string; - source?: string; - readConsistency?: types.consistencies; - writeConsistency?: types.consistencies; - }; - - constructor(name: string, options: { - consistency?: types.consistencies; - loadBalancing?: policies.loadBalancing.LoadBalancingPolicy; - readTimeout?: number; - retry?: policies.retry.RetryPolicy; - serialConsistency?: types.consistencies; - graphOptions?: { - name?: string; - language?: string; - source?: string; - readConsistency?: types.consistencies; - writeConsistency?: types.consistencies; - }; - }); -} - -export namespace errors { - class ArgumentError extends DriverError { - constructor(message: string); - } - - class AuthenticationError extends DriverError { - constructor(message: string); - } - - class BusyConnectionError extends DriverError { - constructor(address: string, maxRequestsPerConnection: number, connectionLength: number); - } - - abstract class DriverError extends Error { - info: string; - - constructor(message: string, constructor?: any); - } - - class DriverInternalError extends DriverError { - constructor(message: string); - } - - class NoHostAvailableError extends DriverError { - innerErrors: any; - - constructor(innerErrors: any, message?: string); - } - - class NotSupportedError extends DriverError { - constructor(message: string); - } - - class OperationTimedOutError extends DriverError { - host?: string; - - constructor(message: string, host?: string); - } - - class ResponseError extends DriverError { - code: number; - - constructor(code: number, message: string); - } -} - -export namespace token { - interface Token { - compare(other: Token): number; - - equals(other: Token): boolean; - - getType(): { code: types.dataTypes, info: any }; - - getValue(): any; - } - - interface TokenRange { - start: Token; - end: Token; - - compare(other: TokenRange): number; - - contains(token: Token): boolean; - - equals(other: TokenRange): boolean; - - isEmpty(): boolean; - - isWrappedAround(): boolean; - - splitEvenly(numberOfSplits: number): TokenRange[]; - - unwrap(): TokenRange[]; - } -} \ No newline at end of file diff --git a/lib/auth/index.d.ts b/lib/auth/index.d.ts deleted file mode 100644 index c1c374134..000000000 --- a/lib/auth/index.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export namespace auth { - interface Authenticator { - initialResponse(callback: Function): void; - - evaluateChallenge(challenge: Buffer, callback: Function): void; - - onAuthenticationSuccess(token?: Buffer): void; - } - - interface AuthProvider { - newAuthenticator(endpoint: string, name: string): Authenticator; - } - - class PlainTextAuthProvider implements AuthProvider { - constructor(username: string, password: string); - - newAuthenticator(endpoint: string, name: string): Authenticator; - } - - class DsePlainTextAuthProvider implements AuthProvider { - constructor(username: string, password: string, authorizationId?: string); - - newAuthenticator(endpoint: string, name: string): Authenticator; - } - - class DseGssapiAuthProvider implements AuthProvider { - constructor(gssOptions?: { authorizationId?: string, service?: string, hostNameResolver?: Function }); - - newAuthenticator(endpoint: string, name: string): Authenticator; - } -} \ No newline at end of file diff --git a/lib/concurrent/index.d.ts b/lib/concurrent/index.d.ts deleted file mode 100644 index 91ab56f7d..000000000 --- a/lib/concurrent/index.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Client } from '../../'; -import { Readable } from 'stream'; - -export namespace concurrent { - interface ResultSetGroup { - errors: Error[]; - resultItems: any[]; - totalExecuted: number; - } - - type Options = { - collectResults?: boolean; - concurrencyLevel?: number; - executionProfile?: string; - maxErrors?: number; - raiseOnFirstError?: boolean; - } - - function executeConcurrent( - client: Client, - query: string, - parameters: any[][]|Readable, - options?: Options): Promise; - - function executeConcurrent( - client: Client, - queries: Array<{query: string, params: any[]}>, - options?: Options): Promise; -} \ No newline at end of file diff --git a/lib/datastax/graph/index.d.ts b/lib/datastax/graph/index.d.ts deleted file mode 100644 index b6e860c42..000000000 --- a/lib/datastax/graph/index.d.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { types } from '../../types'; - -export namespace graph { - interface Edge extends Element { - outV?: Vertex; - outVLabel?: string; - inV?: Vertex; - inVLabel?: string; - properties?: object; - } - - interface Element { - id: any; - label: string; - } - - class GraphResultSet implements Iterator { - constructor(rs: types.ResultSet); - - first(): any; - - toArray(): any[]; - - values(): Iterator; - - next(value?: any): IteratorResult; - } - - interface Path { - labels: any[]; - objects: any[]; - } - - interface Property { - value: any - key: any - } - - interface Vertex extends Element { - properties?: { [key: string]: any[] } - } - - interface VertexProperty extends Element { - value: any - key: string - properties?: any - } - - function asDouble(value: number): object; - - function asFloat(value: number): object; - - function asInt(value: number): object; - - function asTimestamp(value: Date): object; - - function asUdt(value: object): object; - - interface EnumValue { - toString(): string - } - - namespace t { - const id: EnumValue; - const key: EnumValue; - const label: EnumValue; - const value: EnumValue; - } - - namespace direction { - // `in` is a reserved word - const in_: EnumValue; - const out: EnumValue; - const both: EnumValue; - } -} \ No newline at end of file diff --git a/lib/datastax/index.d.ts b/lib/datastax/index.d.ts deleted file mode 100644 index e41483f8e..000000000 --- a/lib/datastax/index.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as graphModule from './graph'; -import * as searchModule from './search'; - -export namespace datastax { - export import graph = graphModule.graph; - - export import search = searchModule.search; -} \ No newline at end of file diff --git a/lib/datastax/search/index.d.ts b/lib/datastax/search/index.d.ts deleted file mode 100644 index 57ba44f7a..000000000 --- a/lib/datastax/search/index.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export namespace search { - enum dateRangePrecision { - year = 0, - month, - day, - hour, - minute, - second, - millisecond - } - - class DateRange { - lowerBound: DateRangeBound; - upperBound: DateRangeBound; - - constructor(lowerBound: DateRangeBound, upperBound: DateRangeBound); - - equals(other: DateRangeBound): boolean; - - toString(): string; - - static fromString(value: string): DateRange; - - static fromBuffer(value: Buffer): DateRange; - } - - class DateRangeBound { - date: Date; - - precision: number; - - equals(other: DateRangeBound): boolean; - - toString(): string; - - static fromString(value: string): DateRangeBound; - - static toLowerBound(bound: DateRangeBound): DateRangeBound; - - static toUpperBound(bound: DateRangeBound): DateRangeBound; - } -} \ No newline at end of file diff --git a/lib/geometry/index.d.ts b/lib/geometry/index.d.ts deleted file mode 100644 index 82ad292ba..000000000 --- a/lib/geometry/index.d.ts +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export namespace geometry { - class LineString { - constructor(...args: Point[]); - - static fromBuffer(buffer: Buffer): LineString; - - static fromString(textValue: string): LineString; - - equals(other: LineString): boolean; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - - } - - class Point { - constructor(x: number, y: number); - - static fromBuffer(buffer: Buffer): Point; - - static fromString(textValue: string): Point; - - equals(other: Point): boolean; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - - } - - class Polygon { - constructor(...args: Point[]); - - static fromBuffer(buffer: Buffer): Polygon; - - static fromString(textValue: string): Polygon; - - equals(other: Polygon): boolean; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - } -} \ No newline at end of file diff --git a/index.js b/lib/index.js similarity index 50% rename from index.js rename to lib/index.js index 2acf5ccb6..de6580703 100644 --- a/index.js +++ b/lib/index.js @@ -14,35 +14,35 @@ * limitations under the License. */ 'use strict'; -const clientOptions = require('./lib/client-options'); -exports.Client = require('./lib/client'); -exports.ExecutionProfile = require('./lib/execution-profile').ExecutionProfile; -exports.ExecutionOptions = require('./lib/execution-options').ExecutionOptions; -exports.types = require('./lib/types'); -exports.errors = require('./lib/errors'); -exports.policies = require('./lib/policies'); -exports.auth = require('./lib/auth'); -exports.mapping = require('./lib/mapping'); -exports.tracker = require('./lib/tracker'); -exports.metrics = require('./lib/metrics'); -exports.concurrent = require('./lib/concurrent'); +const clientOptions = require('./client-options'); +exports.Client = require('./client'); +exports.ExecutionProfile = require('./execution-profile').ExecutionProfile; +exports.ExecutionOptions = require('./execution-options').ExecutionOptions; +exports.types = require('./types'); +exports.errors = require('./errors'); +exports.policies = require('./policies'); +exports.auth = require('./auth'); +exports.mapping = require('./mapping'); +exports.tracker = require('./tracker'); +exports.metrics = require('./metrics'); +exports.concurrent = require('./concurrent'); -const token = require('./lib/token'); +const token = require('./token'); exports.token = { Token: token.Token, TokenRange: token.TokenRange }; -const Metadata = require('./lib/metadata'); +const Metadata = require('./metadata'); exports.metadata = { Metadata: Metadata }; -exports.Encoder = require('./lib/encoder'); -exports.geometry = require('./lib/geometry'); -exports.datastax = require('./lib/datastax'); +exports.Encoder = require('./encoder'); +exports.geometry = require('./geometry'); +exports.datastax = require('./datastax'); /** * Returns a new instance of the default [options]{@link ClientOptions} used by the driver. */ exports.defaultOptions = function () { return clientOptions.defaultOptions(); }; -exports.version = require('./package.json').version; \ No newline at end of file +exports.version = require('../package.json').version; \ No newline at end of file diff --git a/lib/mapping/index.d.ts b/lib/mapping/index.d.ts deleted file mode 100644 index 694e789cf..000000000 --- a/lib/mapping/index.d.ts +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { types } from '../types'; -import { Client } from '../../'; -import Long = types.Long; - -export namespace mapping { - interface TableMappings { - getColumnName(propName: string): string; - - getPropertyName(columnName: string): string; - - newObjectInstance(): any; - } - - class DefaultTableMappings implements TableMappings { - getColumnName(propName: string): string; - - getPropertyName(columnName: string): string; - - newObjectInstance(): any; - } - - class UnderscoreCqlToCamelCaseMappings implements TableMappings { - getColumnName(propName: string): string; - - getPropertyName(columnName: string): string; - - newObjectInstance(): any; - } - - interface Result extends Iterator { - wasApplied(): boolean; - - first(): T | null; - - forEach(callback: (currentValue: T, index: number) => void, thisArg?: any): void; - - toArray(): T[]; - } - - type MappingExecutionOptions = { - executionProfile?: string; - isIdempotent?: boolean; - logged?: boolean; - timestamp?: number | Long; - fetchSize?: number; - pageState?: number; - } - - interface ModelTables { - name: string; - isView: boolean; - } - - class Mapper { - constructor(client: Client, options?: MappingOptions); - - batch(items: ModelBatchItem[], executionOptions?: string | MappingExecutionOptions): Promise; - - forModel(name: string): ModelMapper; - } - - type MappingOptions = { - models: { [key: string]: ModelOptions }; - } - - type FindDocInfo = { - fields?: string[]; - orderBy?: { [key: string]: string }; - limit?: number; - } - - type InsertDocInfo = { - fields?: string[]; - ttl?: number; - ifNotExists?: boolean; - } - - type UpdateDocInfo = { - fields?: string[]; - ttl?: number; - ifExists?: boolean; - when?: { [key: string]: any }; - orderBy?: { [key: string]: string }; - limit?: number; - deleteOnlyColumns?: boolean; - } - - type RemoveDocInfo = { - fields?: string[]; - ttl?: number; - ifExists?: boolean; - when?: { [key: string]: any }; - deleteOnlyColumns?: boolean; - } - - type ModelOptions = { - tables?: string[] | ModelTables[]; - mappings?: TableMappings; - columns?: { [key: string]: string|ModelColumnOptions }; - keyspace?: string; - } - - type ModelColumnOptions = { - name: string; - toModel?: (columnValue: any) => any; - fromModel?: (modelValue: any) => any; - }; - - interface ModelBatchItem { - - } - - interface ModelBatchMapper { - insert(doc: any, docInfo?: InsertDocInfo): ModelBatchItem; - - remove(doc: any, docInfo?: RemoveDocInfo): ModelBatchItem; - - update(doc: any, docInfo?: UpdateDocInfo): ModelBatchItem; - } - - interface ModelMapper { - name: string; - batching: ModelBatchMapper; - - get(doc: { [key: string]: any }, docInfo?: { fields?: string[] }, executionOptions?: string | MappingExecutionOptions): Promise; - - find(doc: { [key: string]: any }, docInfo?: FindDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - findAll(docInfo?: FindDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - insert(doc: { [key: string]: any }, docInfo?: InsertDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - update(doc: { [key: string]: any }, docInfo?: UpdateDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - remove(doc: { [key: string]: any }, docInfo?: RemoveDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - mapWithQuery( - query: string, - paramsHandler: (doc: any) => any[], - executionOptions?: string | MappingExecutionOptions - ): (doc: any, executionOptions?: string | MappingExecutionOptions) => Promise>; - } - - namespace q { - interface QueryOperator { - - } - - function in_(arr: any): QueryOperator; - - function gt(value: any): QueryOperator; - - function gte(value: any): QueryOperator; - - function lt(value: any): QueryOperator; - - function lte(value: any): QueryOperator; - - function notEq(value: any): QueryOperator; - - function and(condition1: any, condition2: any): QueryOperator; - - function incr(value: any): QueryOperator; - - function decr(value: any): QueryOperator; - - function append(value: any): QueryOperator; - - function prepend(value: any): QueryOperator; - - function remove(value: any): QueryOperator; - } -} \ No newline at end of file diff --git a/lib/metadata/index.d.ts b/lib/metadata/index.d.ts deleted file mode 100644 index 80c0d9673..000000000 --- a/lib/metadata/index.d.ts +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { types } from '../types'; -import { EmptyCallback, Host, token, ValueCallback } from '../../'; -import dataTypes = types.dataTypes; -import Uuid = types.Uuid; -import InetAddress = types.InetAddress; - -export namespace metadata { - - interface Aggregate { - argumentTypes: Array<{ code: dataTypes, info: any }>; - finalFunction: string; - initCondition: string; - keyspaceName: string; - returnType: string; - signature: string[]; - stateFunction: string; - stateType: string; - } - - interface ClientState { - getConnectedHosts(): Host[]; - - getInFlightQueries(host: Host): number; - - getOpenConnections(host: Host): number; - - toString(): string; - } - - interface DataTypeInfo { - code: dataTypes; - info: string | DataTypeInfo | DataTypeInfo[]; - options: { - frozen: boolean; - reversed: boolean; - }; - } - - interface ColumnInfo { - name: string; - type: DataTypeInfo; - } - - enum IndexKind { - custom = 0, - keys, - composites - } - - interface Index { - kind: IndexKind; - name: string; - options: object; - target: string; - - isCompositesKind(): boolean; - - isCustomKind(): boolean; - - isKeysKind(): boolean; - } - - interface DataCollection { - bloomFilterFalsePositiveChance: number; - caching: string; - clusteringKeys: ColumnInfo[]; - clusteringOrder: string[]; - columns: ColumnInfo[]; - columnsByName: { [key: string]: ColumnInfo }; - comment: string; - compactionClass: string; - compactionOptions: { [option: string]: any; }; - compression: { - class?: string; - [option: string]: any; - }; - crcCheckChange?: number; - defaultTtl: number; - extensions: { [option: string]: any; }; - gcGraceSeconds: number; - localReadRepairChance: number; - maxIndexInterval?: number; - minIndexInterval?: number; - name: string; - partitionKeys: ColumnInfo[]; - populateCacheOnFlush: boolean; - readRepairChance: number; - speculativeRetry: string; - } - - interface MaterializedView extends DataCollection { - tableName: string; - whereClause: string; - includeAllColumns: boolean; - } - - interface TableMetadata extends DataCollection { - indexes: Index[]; - indexInterval?: number; - isCompact: boolean; - memtableFlushPeriod: number; - replicateOnWrite: boolean; - cdc?: boolean; - virtual: boolean; - } - - interface QueryTrace { - requestType: string; - coordinator: InetAddress; - parameters: { [key: string]: any }; - startedAt: number | types.Long; - duration: number; - clientAddress: string; - events: Array<{ id: Uuid; activity: any; source: any; elapsed: any; thread: any }>; - } - - interface SchemaFunction { - argumentNames: string[]; - argumentTypes: Array<{ code: dataTypes, info: any }>; - body: string; - calledOnNullInput: boolean; - keyspaceName: string; - language: string; - name: string; - returnType: string; - signature: string[]; - } - - interface Udt { - name: string; - fields: ColumnInfo[] - } - - interface Metadata { - keyspaces: { [name: string]: { name: string, strategy: string }}; - - clearPrepared(): void; - - getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: ValueCallback): void; - - getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; - - getAggregates(keyspaceName: string, name: string, callback: ValueCallback): void; - - getAggregates(keyspaceName: string, name: string): Promise; - - getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: ValueCallback): void; - - getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; - - getFunctions(keyspaceName: string, name: string, callback: ValueCallback): void; - - getFunctions(keyspaceName: string, name: string): Promise; - - getMaterializedView(keyspaceName: string, name: string, callback: ValueCallback): void; - - getMaterializedView(keyspaceName: string, name: string, callback: EmptyCallback): Promise; - - getReplicas(keyspaceName: string, token: Buffer | token.Token | token.TokenRange): Host[]; - - getTable(keyspaceName: string, name: string, callback: ValueCallback): void; - - getTable(keyspaceName: string, name: string): Promise; - - getTokenRanges(): Set; - - getTokenRangesForHost(keyspaceName: string, host: Host): Set | null; - - getTrace(traceId: Uuid, consistency: types.consistencies, callback: ValueCallback): void; - - getTrace(traceId: Uuid, consistency: types.consistencies): Promise; - - getTrace(traceId: Uuid, callback: ValueCallback): void; - - getTrace(traceId: Uuid): Promise; - - getUdt(keyspaceName: string, name: string, callback: ValueCallback): void; - - getUdt(keyspaceName: string, name: string): Promise; - - newToken(components: Buffer[] | Buffer | string): token.Token; - - newTokenRange(start: token.Token, end: token.Token): token.TokenRange; - - refreshKeyspace(name: string, callback: EmptyCallback): void; - - refreshKeyspace(name: string): Promise; - - refreshKeyspaces(waitReconnect: boolean, callback: EmptyCallback): void; - - refreshKeyspaces(waitReconnect?: boolean): Promise; - - refreshKeyspaces(callback: EmptyCallback): void; - } -} \ No newline at end of file diff --git a/lib/metrics/index.d.ts b/lib/metrics/index.d.ts deleted file mode 100644 index 4ad80054c..000000000 --- a/lib/metrics/index.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { errors } from '../../'; - -export namespace metrics { - interface ClientMetrics { - onAuthenticationError(e: Error | errors.AuthenticationError): void; - - onClientTimeoutError(e: errors.OperationTimedOutError): void; - - onClientTimeoutRetry(e: Error): void; - - onConnectionError(e: Error): void; - - onIgnoreError(e: Error): void; - - onOtherError(e: Error): void; - - onOtherErrorRetry(e: Error): void; - - onReadTimeoutError(e: errors.ResponseError): void; - - onReadTimeoutRetry(e: Error): void; - - onResponse(latency: number[]): void; - - onSpeculativeExecution(): void; - - onSuccessfulResponse(latency: number[]): void; - - onUnavailableError(e: errors.ResponseError): void; - - onUnavailableRetry(e: Error): void; - - onWriteTimeoutError(e: errors.ResponseError): void; - - onWriteTimeoutRetry(e: Error): void; - } - - class DefaultMetrics implements ClientMetrics { - constructor(); - - onAuthenticationError(e: Error | errors.AuthenticationError): void; - - onClientTimeoutError(e: errors.OperationTimedOutError): void; - - onClientTimeoutRetry(e: Error): void; - - onConnectionError(e: Error): void; - - onIgnoreError(e: Error): void; - - onOtherError(e: Error): void; - - onOtherErrorRetry(e: Error): void; - - onReadTimeoutError(e: errors.ResponseError): void; - - onReadTimeoutRetry(e: Error): void; - - onResponse(latency: number[]): void; - - onSpeculativeExecution(): void; - - onSuccessfulResponse(latency: number[]): void; - - onUnavailableError(e: errors.ResponseError): void; - - onUnavailableRetry(e: Error): void; - - onWriteTimeoutError(e: errors.ResponseError): void; - - onWriteTimeoutRetry(e: Error): void; - } -} \ No newline at end of file diff --git a/lib/policies/index.d.ts b/lib/policies/index.d.ts deleted file mode 100644 index ffae185be..000000000 --- a/lib/policies/index.d.ts +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Client, EmptyCallback, ExecutionOptions, Host, HostMap } from '../../'; -import { types } from '../types'; - - -export namespace policies { - function defaultAddressTranslator(): addressResolution.AddressTranslator; - - function defaultLoadBalancingPolicy(localDc?: string): loadBalancing.LoadBalancingPolicy; - - function defaultReconnectionPolicy(): reconnection.ReconnectionPolicy; - - function defaultRetryPolicy(): retry.RetryPolicy; - - function defaultSpeculativeExecutionPolicy(): speculativeExecution.SpeculativeExecutionPolicy; - - function defaultTimestampGenerator(): timestampGeneration.TimestampGenerator; - - namespace addressResolution { - interface AddressTranslator { - translate(address: string, port: number, callback: Function): void; - } - - class EC2MultiRegionTranslator implements AddressTranslator { - translate(address: string, port: number, callback: Function): void; - } - } - - namespace loadBalancing { - abstract class LoadBalancingPolicy { - init(client: Client, hosts: HostMap, callback: EmptyCallback): void; - - getDistance(host: Host): types.distance; - - newQueryPlan( - keyspace: string, - executionOptions: ExecutionOptions, - callback: (error: Error, iterator: Iterator) => void): void; - - getOptions(): Map; - } - - class DCAwareRoundRobinPolicy extends LoadBalancingPolicy { - constructor(localDc: string); - } - - class TokenAwarePolicy extends LoadBalancingPolicy { - constructor(childPolicy: LoadBalancingPolicy); - } - - class AllowListPolicy extends LoadBalancingPolicy { - constructor(childPolicy: LoadBalancingPolicy, allowList: string[]); - } - - class WhiteListPolicy extends AllowListPolicy { - } - - class RoundRobinPolicy extends LoadBalancingPolicy { - constructor(); - } - - class DefaultLoadBalancingPolicy extends LoadBalancingPolicy { - constructor(options?: { localDc?: string, filter?: (host: Host) => boolean }); - } - } - - namespace reconnection { - class ConstantReconnectionPolicy implements ReconnectionPolicy { - constructor(delay: number); - - getOptions(): Map; - - newSchedule(): Iterator; - - } - - class ExponentialReconnectionPolicy implements ReconnectionPolicy { - constructor(baseDelay: number, maxDelay: number, startWithNoDelay?: boolean); - - getOptions(): Map; - - newSchedule(): Iterator; - } - - interface ReconnectionPolicy { - getOptions(): Map; - - newSchedule(): Iterator; - } - } - - namespace retry { - class DecisionInfo { - decision: number; - consistency: types.consistencies; - } - - class OperationInfo { - query: string; - executionOptions: ExecutionOptions; - nbRetry: number; - } - - class IdempotenceAwareRetryPolicy extends RetryPolicy { - constructor(childPolicy: RetryPolicy); - } - - class FallthroughRetryPolicy extends RetryPolicy { - constructor(); - } - - class RetryPolicy { - onReadTimeout( - info: OperationInfo, - consistency: types.consistencies, - received: number, - blockFor: number, - isDataPresent: boolean): DecisionInfo; - - onRequestError(info: OperationInfo, consistency: types.consistencies, err: Error): DecisionInfo; - - onUnavailable( - info: OperationInfo, consistency: types.consistencies, required: number, alive: boolean): DecisionInfo; - - onWriteTimeout( - info: OperationInfo, - consistency: types.consistencies, - received: number, - blockFor: number, - writeType: string): DecisionInfo; - - rethrowResult(): DecisionInfo; - - retryResult(consistency: types.consistencies, useCurrentHost?: boolean): DecisionInfo; - } - - namespace RetryDecision { - enum retryDecision { - ignore, - rethrow, - retry - } - } - } - - namespace speculativeExecution { - class ConstantSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { - constructor(delay: number, maxSpeculativeExecutions: number); - - getOptions(): Map; - - init(client: Client): void; - - newPlan(keyspace: string, queryInfo: string | Array): { nextExecution: Function }; - - shutdown(): void; - } - - class NoSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { - constructor(); - - getOptions(): Map; - - init(client: Client): void; - - newPlan(keyspace: string, queryInfo: string | Array): { nextExecution: Function }; - - shutdown(): void; - } - - interface SpeculativeExecutionPolicy { - getOptions(): Map; - - init(client: Client): void; - - newPlan(keyspace: string, queryInfo: string|Array): { nextExecution: Function }; - - shutdown(): void; - } - } - - namespace timestampGeneration { - class MonotonicTimestampGenerator implements TimestampGenerator { - constructor(warningThreshold: number, minLogInterval: number); - - getDate(): number; - - next(client: Client): types.Long | number; - } - - interface TimestampGenerator { - next(client: Client): types.Long|number; - } - } -} \ No newline at end of file diff --git a/lib/tracker/index.d.ts b/lib/tracker/index.d.ts deleted file mode 100644 index e39e8bae3..000000000 --- a/lib/tracker/index.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { ExecutionOptions, Host } from '../../'; - -export namespace tracker { - interface RequestTracker { - onError( - host: Host, - query: string | Array<{ query: string, params?: any }>, - parameters: any[] | { [key: string]: any } | null, - executionOptions: ExecutionOptions, - requestLength: number, - err: Error, - latency: number[]): void; - - onSuccess( - host: Host, - query: string | Array<{ query: string, params?: any }>, - parameters: any[] | { [key: string]: any } | null, - executionOptions: ExecutionOptions, - requestLength: number, - responseLength: number, - latency: number[]): void; - - shutdown(): void; - } - - class RequestLogger implements RequestTracker { - constructor(options: { - slowThreshold?: number; - logNormalRequests?: boolean; - logErroredRequests?: boolean; - messageMaxQueryLength?: number; - messageMaxParameterValueLength?: number; - messageMaxErrorStackTraceLength?: number; - }); - - onError(host: Host, query: string | Array<{ query: string; params?: any }>, parameters: any[] | { [p: string]: any } | null, executionOptions: ExecutionOptions, requestLength: number, err: Error, latency: number[]): void; - - onSuccess(host: Host, query: string | Array<{ query: string; params?: any }>, parameters: any[] | { [p: string]: any } | null, executionOptions: ExecutionOptions, requestLength: number, responseLength: number, latency: number[]): void; - - shutdown(): void; - } -} \ No newline at end of file diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts deleted file mode 100644 index b03186cf6..000000000 --- a/lib/types/index.d.ts +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import _Long = require('long'); -import * as stream from 'stream'; -import { ValueCallback } from '../../'; - -export namespace types { - class Long extends _Long { - - } - - enum consistencies { - any = 0x00, - one = 0x01, - two = 0x02, - three = 0x03, - quorum = 0x04, - all = 0x05, - localQuorum = 0x06, - eachQuorum = 0x07, - serial = 0x08, - localSerial = 0x09, - localOne = 0x0a - } - - enum dataTypes { - custom = 0x0000, - ascii = 0x0001, - bigint = 0x0002, - blob = 0x0003, - boolean = 0x0004, - counter = 0x0005, - decimal = 0x0006, - double = 0x0007, - float = 0x0008, - int = 0x0009, - text = 0x000a, - timestamp = 0x000b, - uuid = 0x000c, - varchar = 0x000d, - varint = 0x000e, - timeuuid = 0x000f, - inet = 0x0010, - date = 0x0011, - time = 0x0012, - smallint = 0x0013, - tinyint = 0x0014, - duration = 0x0015, - list = 0x0020, - map = 0x0021, - set = 0x0022, - udt = 0x0030, - tuple = 0x0031, - } - - enum distance { - local = 0, - remote, - ignored - } - - enum responseErrorCodes { - serverError = 0x0000, - protocolError = 0x000A, - badCredentials = 0x0100, - unavailableException = 0x1000, - overloaded = 0x1001, - isBootstrapping = 0x1002, - truncateError = 0x1003, - writeTimeout = 0x1100, - readTimeout = 0x1200, - readFailure = 0x1300, - functionFailure = 0x1400, - writeFailure = 0x1500, - syntaxError = 0x2000, - unauthorized = 0x2100, - invalid = 0x2200, - configError = 0x2300, - alreadyExists = 0x2400, - unprepared = 0x2500, - clientWriteFailure = 0x8000 - } - - enum protocolVersion { - v1 = 0x01, - v2 = 0x02, - v3 = 0x03, - v4 = 0x04, - v5 = 0x05, - v6 = 0x06, - dseV1 = 0x41, - dseV2 = 0x42, - maxSupported = dseV2, - minSupported = v1 - } - - namespace protocolVersion { - function isSupported(version: protocolVersion): boolean; - } - - const unset: object; - - class BigDecimal { - constructor(unscaledValue: number, scale: number); - - static fromBuffer(buf: Buffer): BigDecimal; - - static fromString(value: string): BigDecimal; - - static toBuffer(value: BigDecimal): Buffer; - - static fromNumber(value: number): BigDecimal; - - add(other: BigDecimal): BigDecimal; - - compare(other: BigDecimal): number; - - equals(other: BigDecimal): boolean; - - greaterThan(other: BigDecimal): boolean; - - isNegative(): boolean; - - isZero(): boolean; - - notEquals(other: BigDecimal): boolean; - - subtract(other: BigDecimal): BigDecimal; - - toNumber(): number; - - toString(): string; - - toJSON(): string; - } - - class Duration { - constructor(month: number, days: number, nanoseconds: number | Long); - - static fromBuffer(buffer: Buffer): Duration; - - static fromString(input: string): Duration; - - equals(other: Duration): boolean; - - toBuffer(): Buffer; - - toString(): string; - } - - class InetAddress { - length: number; - - version: number; - - constructor(buffer: Buffer); - - static fromString(value: string): InetAddress; - - equals(other: InetAddress): boolean; - - getBuffer(): Buffer; - - toString(): string; - - toJSON(): string; - } - - class Integer { - static ONE: Integer; - static ZERO: Integer; - - constructor(bits: Array, sign: number); - - static fromBits(bits: Array): Integer; - - static fromBuffer(bits: Buffer): Integer; - - static fromInt(value: number): Integer; - - static fromNumber(value: number): Integer; - - static fromString(str: string, opt_radix?: number): Integer; - - static toBuffer(value: Integer): Buffer; - - abs(): Integer; - - add(other: Integer): Integer; - - compare(other: Integer): number; - - divide(other: Integer): Integer; - - equals(other: Integer): boolean; - - getBits(index: number): number; - - getBitsUnsigned(index: number): number; - - getSign(): number; - - greaterThan(other: Integer): boolean; - - greaterThanOrEqual(other: Integer): boolean; - - isNegative(): boolean; - - isOdd(): boolean; - - isZero(): boolean; - - lessThan(other: Integer): boolean; - - lessThanOrEqual(other: Integer): boolean; - - modulo(other: Integer): Integer; - - multiply(other: Integer): Integer; - - negate(): Integer; - - not(): Integer; - - notEquals(other: Integer): boolean; - - or(other: Integer): Integer; - - shiftLeft(numBits: number): Integer; - - shiftRight(numBits: number): Integer; - - shorten(numBits: number): Integer; - - subtract(other: Integer): Integer; - - toInt(): number; - - toJSON(): string; - - toNumber(): number; - - toString(opt_radix?: number): string; - - xor(other: Integer): Integer; - } - - class LocalDate { - year: number; - month: number; - day: number; - - constructor(year: number, month: number, day: number); - - static fromDate(date: Date): LocalDate; - - static fromString(value: string): LocalDate; - - static fromBuffer(buffer: Buffer): LocalDate; - - static now(): LocalDate; - - static utcNow(): LocalDate; - - equals(other: LocalDate): boolean; - - inspect(): string; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - } - - class LocalTime { - hour: number; - minute: number; - nanosecond: number; - second: number; - - constructor(totalNanoseconds: Long); - - static fromBuffer(value: Buffer): LocalTime; - - static fromDate(date: Date, nanoseconds: number): LocalTime; - - static fromMilliseconds(milliseconds: number, nanoseconds?: number): LocalTime; - - static fromString(value: string): LocalTime; - - static now(nanoseconds?: number): LocalTime; - - compare(other: LocalTime): boolean; - - equals(other: LocalTime): boolean; - - getTotalNanoseconds(): Long; - - inspect(): string; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - } - - interface ResultSet extends Iterable, AsyncIterable { - info: { - queriedHost: string, - triedHosts: { [key: string]: any; }, - speculativeExecutions: number, - achievedConsistency: consistencies, - traceId: Uuid, - warnings: string[], - customPayload: any - }; - - columns: Array<{ name: string, type: { code: dataTypes, info: any } }>; - nextPage: (() => void) | null; - pageState: string; - rowLength: number; - rows: Row[]; - - first(): Row; - - wasApplied(): boolean; - } - - interface ResultStream extends stream.Readable { - buffer: Buffer; - paused: boolean; - - add(chunk: Buffer): void; - } - - interface Row { - get(columnName: string | number): any; - - keys(): string[]; - - forEach(callback: (row: Row) => void): void; - - values(): any[]; - - [key: string]: any; - } - - class TimeUuid extends Uuid { - static now(): TimeUuid; - - static now(nodeId: string | Buffer, clockId?: string | Buffer): TimeUuid; - - static now(nodeId: string | Buffer, clockId: string | Buffer, callback: ValueCallback): void; - - static now(callback: ValueCallback): void; - - static fromDate(date: Date, ticks?: number, nodeId?: string | Buffer, clockId?: string | Buffer): TimeUuid; - - static fromDate( - date: Date, - ticks: number, - nodeId: string | Buffer, - clockId: string | Buffer, - callback: ValueCallback): void; - - static fromString(value: string): TimeUuid; - - static max(date: Date, ticks: number): TimeUuid; - - static min(date: Date, ticks: number): TimeUuid; - - getDatePrecision(): { date: Date, ticks: number }; - - getDate(): Date; - } - - class Tuple { - elements: any[]; - length: number; - - constructor(...args: any[]); - - static fromArray(elements: any[]): Tuple; - - get(index: number): any; - - toString(): string; - - toJSON(): string; - - values(): any[]; - } - - class Uuid { - constructor(buffer: Buffer); - - static fromString(value: string): Uuid; - - static random(callback: ValueCallback): void; - - static random(): Uuid; - - equals(other: Uuid): boolean; - - getBuffer(): Buffer; - - toString(): string; - - toJSON(): string; - } -} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index d35a5d25c..d874f2382 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,8 +9,7 @@ "version": "4.7.2", "license": "Apache-2.0", "dependencies": { - "@types/long": "~5.0.0", - "@types/node": "^18.11.18", + "@types/node": "^18.19.68", "adm-zip": "~0.5.10", "long": "~5.2.3" }, @@ -71,19 +70,10 @@ "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==", "dev": true }, - "node_modules/@types/long": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@types/long/-/long-5.0.0.tgz", - "integrity": "sha512-eQs9RsucA/LNjnMoJvWG/nXa7Pot/RbBzilF/QRIU/xRl+0ApxrSUFsV5lmf01SvSlqMzJ7Zwxe440wmz2SJGA==", - "deprecated": "This is a stub types definition. long provides its own type definitions, so you do not need this installed.", - "dependencies": { - "long": "*" - } - }, "node_modules/@types/node": { - "version": "18.19.53", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.53.tgz", - "integrity": "sha512-GLxgUgHhDKO1Edw9Q0lvMbiO/IQXJwJlMaqxSGBXMpPy8uhkCs2iiPFaB2Q/gmobnFkckD3rqTBMVjXdwq+nKg==", + "version": "18.19.68", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.68.tgz", + "integrity": "sha512-QGtpFH1vB99ZmTa63K4/FU8twThj4fuVSBkGddTp7uIL/cuoLWIUSL2RcOaigBhfR+hg5pgGkBnkoOxrTVBMKw==", "dependencies": { "undici-types": "~5.26.4" } diff --git a/package.json b/package.json index 7b116e2f4..e2bc94322 100644 --- a/package.json +++ b/package.json @@ -18,10 +18,10 @@ "graphdb" ], "license": "Apache-2.0", - "types": "./index.d.ts", + "main": "lib/index.js", + "types": "dist/lib/index.d.ts", "dependencies": { - "@types/long": "~5.0.0", - "@types/node": "^18.11.18", + "@types/node": "^18.19.68", "adm-zip": "~0.5.10", "long": "~5.2.3" }, diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 000000000..71377dcdd --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,25 @@ +{ + "include": [ + "lib/**/*.js" + ], + "exclude": [ + "node_modules", + "dist" + ], + "compilerOptions": { + "resolveJsonModule": true, + "allowJs": true, + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "dist", // Emit .d.ts files to a subdirectory + "target": "es2015", + "lib": ["es2015"], + "module": "CommonJS", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "checkJs": true + } +} From 0bc06e31f111107f52bdf1485569793619a893d5 Mon Sep 17 00:00:00 2001 From: Jane He Date: Tue, 17 Dec 2024 22:48:38 +0800 Subject: [PATCH 2/5] auth folder --- lib/auth/base-dse-authenticator.js | 90 +++--- lib/auth/dse-gssapi-auth-provider.js | 346 +++++++++++------------ lib/auth/dse-plain-text-auth-provider.js | 130 ++++----- lib/auth/plain-text-auth-provider.js | 108 ++++--- lib/auth/provider.js | 84 +++--- tsconfig.json | 2 +- 6 files changed, 386 insertions(+), 374 deletions(-) diff --git a/lib/auth/base-dse-authenticator.js b/lib/auth/base-dse-authenticator.js index bddc6493e..14c69fb2a 100644 --- a/lib/auth/base-dse-authenticator.js +++ b/lib/auth/base-dse-authenticator.js @@ -14,63 +14,65 @@ * limitations under the License. */ 'use strict'; -const util = require('util'); const { Authenticator } = require('./provider'); const dseAuthenticatorName = 'com.datastax.bdp.cassandra.auth.DseAuthenticator'; /** - * Base class for Authenticator implementations that want to make use of + * @class + * @classdesc Base class for Authenticator implementations that want to make use of * the authentication scheme negotiation in the DseAuthenticator - * @param {String} authenticatorName * @extends Authenticator - * @constructor * @ignore */ -function BaseDseAuthenticator(authenticatorName) { - this.authenticatorName = authenticatorName; -} - -util.inherits(BaseDseAuthenticator, Authenticator); +class BaseDseAuthenticator extends Authenticator { + /** + * @param {String} authenticatorName + */ + constructor(authenticatorName) { + super(); + this.authenticatorName = authenticatorName; + } -/** - * Return a Buffer containing the required SASL mechanism. - * @abstract - * @returns {Buffer} - */ -BaseDseAuthenticator.prototype.getMechanism = function () { - throw new Error('Not implemented'); -}; + /** + * Return a Buffer containing the required SASL mechanism. + * @abstract + * @returns {Buffer} + */ + getMechanism() { + throw new Error('Not implemented'); + } -/** - * Return a byte array containing the expected successful server challenge. - * @abstract - * @returns {Buffer} - */ -BaseDseAuthenticator.prototype.getInitialServerChallenge = function () { - throw new Error('Not implemented'); -}; + /** + * Return a byte array containing the expected successful server challenge. + * @abstract + * @returns {Buffer} + */ + getInitialServerChallenge() { + throw new Error('Not implemented'); + } -/** - * @param {Function} callback - * @override - */ -BaseDseAuthenticator.prototype.initialResponse = function (callback) { - if (!this._isDseAuthenticator()) { - //fallback - return this.evaluateChallenge(this.getInitialServerChallenge(), callback); + /** + * @param {Function} callback + * @override + */ + initialResponse(callback) { + if (!this._isDseAuthenticator()) { + //fallback + return this.evaluateChallenge(this.getInitialServerChallenge(), callback); + } + //send the mechanism as a first auth message + callback(null, this.getMechanism()); } - //send the mechanism as a first auth message - callback(null, this.getMechanism()); -}; -/** - * Determines if the name of the authenticator matches DSE 5+ - * @protected - * @ignore - */ -BaseDseAuthenticator.prototype._isDseAuthenticator = function () { - return this.authenticatorName === dseAuthenticatorName; -}; + /** + * Determines if the name of the authenticator matches DSE 5+ + * @protected + * @ignore + */ + _isDseAuthenticator() { + return this.authenticatorName === dseAuthenticatorName; + } +} module.exports = BaseDseAuthenticator; \ No newline at end of file diff --git a/lib/auth/dse-gssapi-auth-provider.js b/lib/auth/dse-gssapi-auth-provider.js index ac25a5185..6736f0079 100644 --- a/lib/auth/dse-gssapi-auth-provider.js +++ b/lib/auth/dse-gssapi-auth-provider.js @@ -14,8 +14,7 @@ * limitations under the License. */ 'use strict'; -const util = require('util'); -const { AuthProvider } = require('./provider'); +const { AuthProvider, Authenticator } = require('./provider'); const BaseDseAuthenticator = require('./base-dse-authenticator'); const GssapiClient = require('./gssapi-client'); const dns = require('dns'); @@ -26,206 +25,199 @@ const initialServerChallenge = 'GSSAPI-START'; const emptyBuffer = utils.allocBuffer(0); /** - * Creates a new instance of DseGssapiAuthProvider. - * @classdesc - * AuthProvider that provides GSSAPI authenticator instances for clients to connect + * @class + * @classdesc AuthProvider that provides GSSAPI authenticator instances for clients to connect * to DSE clusters secured with the DseAuthenticator. - * @param {Object} [gssOptions] GSSAPI authenticator options - * @param {String} [gssOptions.authorizationId] The optional authorization ID. Providing an authorization ID allows the - * currently authenticated user to act as a different user (a.k.a. proxy authentication). - * @param {String} [gssOptions.service] The service to use. Defaults to 'dse'. - * @param {Function} [gssOptions.hostNameResolver] A method to be used to resolve the name of the Cassandra node based - * on the IP Address. Defaults to [lookupServiceResolver]{@link module:auth~DseGssapiAuthProvider.lookupServiceResolver} - * which resolves the FQDN of the provided IP to generate principals in the format of - * dse/example.com@MYREALM.COM. - * Alternatively, you can use [reverseDnsResolver]{@link module:auth~DseGssapiAuthProvider.reverseDnsResolver} to do a - * reverse DNS lookup or [useIpResolver]{@link module:auth~DseGssapiAuthProvider.useIpResolver} to simply use the IP - * address provided. - * @param {String} [gssOptions.user] DEPRECATED, it will be removed in future versions. For proxy authentication, use - * authorizationId instead. + * @extends AuthProvider + * @alias module:auth~DseGssapiAuthProvider * @example * const client = new cassandra.Client({ * contactPoints: ['h1', 'h2'], * authProvider: new cassandra.auth.DseGssapiAuthProvider() * }); - * @alias module:auth~DseGssapiAuthProvider - * @constructor */ -function DseGssapiAuthProvider(gssOptions) { - //load the kerberos at construction time - try { - // eslint-disable-next-line - this._kerberos = require('kerberos'); - } - catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - const newErr = new Error('You must install module "kerberos" to use GSSAPI auth provider: ' + - 'https://www.npmjs.com/package/kerberos'); - newErr.code = err.code; - throw newErr; +class DseGssapiAuthProvider extends AuthProvider { + /** + * @param {Object} [gssOptions] GSSAPI authenticator options + * @param {String} [gssOptions.authorizationId] The optional authorization ID. Providing an authorization ID allows the + * currently authenticated user to act as a different user (a.k.a. proxy authentication). + * @param {String} [gssOptions.service] The service to use. Defaults to 'dse'. + * @param {Function} [gssOptions.hostNameResolver] A method to be used to resolve the name of the Cassandra node based + * on the IP Address. Defaults to [lookupServiceResolver]{@link module:auth~DseGssapiAuthProvider.lookupServiceResolver} + * which resolves the FQDN of the provided IP to generate principals in the format of + * dse/example.com@MYREALM.COM. + * Alternatively, you can use [reverseDnsResolver]{@link module:auth~DseGssapiAuthProvider.reverseDnsResolver} to do a + * reverse DNS lookup or [useIpResolver]{@link module:auth~DseGssapiAuthProvider.useIpResolver} to simply use the IP + * address provided. + * @param {String} [gssOptions.user] DEPRECATED, it will be removed in future versions. For proxy authentication, use + * authorizationId instead. + */ + constructor(gssOptions = {}) { + super(); + try { + this._kerberos = require('kerberos'); + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + const newErr = new Error('You must install module "kerberos" to use GSSAPI auth provider: ' + + 'https://www.npmjs.com/package/kerberos'); + newErr.code = err.code; + throw newErr; + } + throw err; } - throw err; + this.authorizationId = gssOptions.authorizationId || gssOptions.user; + this.service = gssOptions.service; + this.hostNameResolver = gssOptions.hostNameResolver || DseGssapiAuthProvider.lookupServiceResolver; } - gssOptions = gssOptions || utils.emptyObject; - this.authorizationId = gssOptions.authorizationId || gssOptions.user; - this.service = gssOptions.service; - this.hostNameResolver = gssOptions.hostNameResolver || DseGssapiAuthProvider.lookupServiceResolver; -} - -util.inherits(DseGssapiAuthProvider, AuthProvider); -/** - * Returns an Authenticator instance to be used by the driver when connecting to a host. - * @param {String} endpoint The IP address and port number in the format ip:port. - * @param {String} name Authenticator name. - * @override - * @returns {Authenticator} - */ -DseGssapiAuthProvider.prototype.newAuthenticator = function (endpoint, name) { - let address = endpoint; - if (endpoint.indexOf(':') > 0) { - address = endpoint.split(':')[0]; + /** + * Returns an Authenticator instance to be used by the driver when connecting to a host. + * @param {String} endpoint The IP address and port number in the format ip:port. + * @param {String} name Authenticator name. + * @override + * @returns {Authenticator} + */ + newAuthenticator(endpoint, name) { + let address = endpoint; + if (endpoint.indexOf(':') > 0) { + address = endpoint.split(':')[0]; + } + return new GssapiAuthenticator( + this._kerberos, address, name, this.authorizationId, this.service, this.hostNameResolver); } - return new GssapiAuthenticator( - this._kerberos, address, name, this.authorizationId, this.service, this.hostNameResolver); -}; -/** - * Performs a lookupService query that resolves an IPv4 or IPv6 address to a hostname. This ultimately makes a - * getnameinfo() system call which depends on the OS to do hostname resolution. - *

- * Note: Depends on dns.lookupService which was added in 0.12. For older versions falls back on - * [reverseDnsResolver]{@link module:auth~DseGssapiAuthProvider.reverseDnsResolver}. - * - * @param {String} ip IP address to resolve. - * @param {Function} callback The callback function with err and hostname arguments. - */ -DseGssapiAuthProvider.lookupServiceResolver = function (ip, callback) { - if (!dns.lookupService) { - return DseGssapiAuthProvider.reverseDnsResolver(ip, callback); - } - dns.lookupService(ip, 0, function (err, hostname) { - if (err) { - return callback(err); - } - if (!hostname) { - //fallback to ip - return callback(null, ip); + /** + * Performs a lookupService query that resolves an IPv4 or IPv6 address to a hostname. This ultimately makes a + * getnameinfo() system call which depends on the OS to do hostname resolution. + *

+ * Note: Depends on dns.lookupService which was added in 0.12. For older versions falls back on + * [reverseDnsResolver]{@link module:auth~DseGssapiAuthProvider.reverseDnsResolver}. + * + * @param {String} ip IP address to resolve. + * @param {Function} callback The callback function with err and hostname arguments. + */ + static lookupServiceResolver(ip, callback) { + if (!dns.lookupService) { + return DseGssapiAuthProvider.reverseDnsResolver(ip, callback); } - callback(null, hostname); - }); -}; + dns.lookupService(ip, 0, (err, hostname) => { + if (err) { + return callback(err); + } + if (!hostname) { + return callback(null, ip); + } + callback(null, hostname); + }); + } -/** - * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to a hostname. - * @param {String} ip IP address to resolve. - * @param {Function} callback The callback function with err and hostname arguments. - */ -DseGssapiAuthProvider.reverseDnsResolver = function (ip, callback) { - dns.reverse(ip, function (err, names) { - if (err) { - return callback(err); - } - if (!names || !names.length) { - //fallback to ip - return callback(null, ip); - } - callback(null, names[0]); - }); -}; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to a hostname. + * @param {String} ip IP address to resolve. + * @param {Function} callback The callback function with err and hostname arguments. + */ + static reverseDnsResolver(ip, callback) { + dns.reverse(ip, (err, names) => { + if (err) { + return callback(err); + } + if (!names || !names.length) { + return callback(null, ip); + } + callback(null, names[0]); + }); + } -/** - * Effectively a no op operation, returns the IP address provided. - * @param {String} ip IP address to use. - * @param {Function} callback The callback function with err and hostname arguments. - */ -DseGssapiAuthProvider.useIpResolver = function (ip, callback) { - callback(null, ip); -}; + /** + * Effectively a no op operation, returns the IP address provided. + * @param {String} ip IP address to use. + * @param {Function} callback The callback function with err and hostname arguments. + */ + static useIpResolver(ip, callback) { + callback(null, ip); + } +} /** - * @param {Object} kerberosModule - * @param {String} address Host address. - * @param {String} authenticatorName - * @param {String} authorizationId - * @param {String} service - * @param {Function} hostNameResolver - * @extends Authenticator + * @class + * @classdesc Authenticator for GSSAPI. + * @extends BaseDseAuthenticator * @private */ -function GssapiAuthenticator(kerberosModule, address, authenticatorName, authorizationId, service, hostNameResolver) { - BaseDseAuthenticator.call(this, authenticatorName); - this.authorizationId = authorizationId; - this.address = address; - this.client = GssapiClient.createNew(kerberosModule, authorizationId, service); - this.hostNameResolver = hostNameResolver; -} +class GssapiAuthenticator extends BaseDseAuthenticator { + /** + * @param {Object} kerberosModule + * @param {String} address Host address. + * @param {String} authenticatorName + * @param {String} authorizationId + * @param {String} service + * @param {Function} hostNameResolver + */ + constructor(kerberosModule, address, authenticatorName, authorizationId, service, hostNameResolver) { + super(authenticatorName); + this.authorizationId = authorizationId; + this.address = address; + this.client = GssapiClient.createNew(kerberosModule, authorizationId, service); + this.hostNameResolver = hostNameResolver; + } -//noinspection JSCheckFunctionSignatures -util.inherits(GssapiAuthenticator, BaseDseAuthenticator); + getMechanism() { + return mechanism; + } -GssapiAuthenticator.prototype.getMechanism = function () { - return mechanism; -}; + getInitialServerChallenge() { + return utils.allocBufferFromString(initialServerChallenge); + } -GssapiAuthenticator.prototype.getInitialServerChallenge = function () { - return utils.allocBufferFromString(initialServerChallenge); -}; + /** + * Obtain an initial response token for initializing the SASL handshake. + * @param {Function} callback + */ + initialResponse(callback) { + let host = this.address; + utils.series([ + (next) => { + this.hostNameResolver(this.address, (err, name) => { + if (!err && name) { + host = name; + } + next(); + }); + }, + (next) => { + this.client.init(host, (err) => { + if (err) { + return next(err); + } + if (!this._isDseAuthenticator()) { + return this.evaluateChallenge(this.getInitialServerChallenge(), next); + } + next(null, this.getMechanism()); + }); + } + ], callback); + } -//noinspection JSUnusedGlobalSymbols -/** - * Obtain an initial response token for initializing the SASL handshake. - * @param {Function} callback - */ -GssapiAuthenticator.prototype.initialResponse = function (callback) { - const self = this; - //initialize the GSS client - let host = this.address; - utils.series([ - function getHostName(next) { - self.hostNameResolver(self.address, function (err, name) { - if (!err && name) { - host = name; - } - next(); - }); - }, - function initClient(next) { - self.client.init(host, function (err) { - if (err) { - return next(err); - } - if (!self._isDseAuthenticator()) { - //fallback - return self.evaluateChallenge(self.getInitialServerChallenge(), next); - } - //send the mechanism as a first auth message - next(null, self.getMechanism()); - }); + /** + * Evaluates a challenge received from the Server. Generally, this method should callback with + * no error and no additional params when authentication is complete from the client perspective. + * @param {Buffer} challenge + * @param {Function} callback + * @override + */ + evaluateChallenge(challenge, callback) { + if (!challenge || challenge.toString() === initialServerChallenge) { + challenge = emptyBuffer; } - ], callback); -}; - -/** - * Evaluates a challenge received from the Server. Generally, this method should callback with - * no error and no additional params when authentication is complete from the client perspective. - * @param {Buffer} challenge - * @param {Function} callback - * @override - */ -GssapiAuthenticator.prototype.evaluateChallenge = function (challenge, callback) { - if (!challenge || challenge.toString() === initialServerChallenge) { - challenge = emptyBuffer; + this.client.evaluateChallenge(challenge, callback); } - this.client.evaluateChallenge(challenge, callback); -}; - -/** - * @override - */ -GssapiAuthenticator.prototype.onAuthenticationSuccess = function (token) { - this.client.shutdown(function noop() { }); -}; + /** + * @override + */ + onAuthenticationSuccess(token) { + this.client.shutdown(() => {}); + } +} module.exports = DseGssapiAuthProvider; \ No newline at end of file diff --git a/lib/auth/dse-plain-text-auth-provider.js b/lib/auth/dse-plain-text-auth-provider.js index 64a0f649e..4c9c6c46a 100644 --- a/lib/auth/dse-plain-text-auth-provider.js +++ b/lib/auth/dse-plain-text-auth-provider.js @@ -14,8 +14,7 @@ * limitations under the License. */ 'use strict'; -const util = require('util'); -const { AuthProvider } = require('./provider'); +const { AuthProvider, Authenticator } = require('./provider'); const BaseDseAuthenticator = require('./base-dse-authenticator'); const utils = require('../utils'); @@ -24,14 +23,9 @@ const separatorBuffer = utils.allocBufferFromArray([0]); const initialServerChallenge = 'PLAIN-START'; /** - * Creates a new instance of DsePlainTextAuthProvider. - * @classdesc - * AuthProvider that provides plain text authenticator instances for clients to connect + * @class + * @classdesc AuthProvider that provides plain text authenticator instances for clients to connect * to DSE clusters secured with the DseAuthenticator. - * @param {String} username The username; cannot be null. - * @param {String} password The password; cannot be null. - * @param {String} [authorizationId] The optional authorization ID. Providing an authorization ID allows the currently - * authenticated user to act as a different user (a.k.a. proxy authentication). * @extends AuthProvider * @alias module:auth~DsePlainTextAuthProvider * @example @@ -39,72 +33,80 @@ const initialServerChallenge = 'PLAIN-START'; * contactPoints: ['h1', 'h2'], * authProvider: new cassandra.auth.DsePlainTextAuthProvider('user', 'p@ssword1'); * }); - * @constructor */ -function DsePlainTextAuthProvider(username, password, authorizationId) { - if (typeof username !== 'string' || typeof password !== 'string') { - // Validate for null and undefined - throw new TypeError('Username and password must be a string'); +class DsePlainTextAuthProvider extends AuthProvider { + /** + * @param {String} username The username; cannot be null. + * @param {String} password The password; cannot be null. + * @param {String} [authorizationId] The optional authorization ID. Providing an authorization ID allows the currently + * authenticated user to act as a different user (a.k.a. proxy authentication). + */ + constructor(username, password, authorizationId) { + super(); + if (typeof username !== 'string' || typeof password !== 'string') { + throw new TypeError('Username and password must be a string'); + } + this.username = username; + this.password = password; + this.authorizationId = authorizationId; } - this.username = username; - this.password = password; - this.authorizationId = authorizationId; -} - -util.inherits(DsePlainTextAuthProvider, AuthProvider); -/** - * Returns an Authenticator instance to be used by the driver when connecting to a host. - * @param {String} endpoint The IP address and port number in the format ip:port. - * @param {String} name Authenticator name. - * @override - * @returns {Authenticator} - */ -DsePlainTextAuthProvider.prototype.newAuthenticator = function (endpoint, name) { - return new PlainTextAuthenticator(name, this.username, this.password, this.authorizationId); -}; + /** + * Returns an Authenticator instance to be used by the driver when connecting to a host. + * @param {String} endpoint The IP address and port number in the format ip:port. + * @param {String} name Authenticator name. + * @override + * @returns {Authenticator} + */ + newAuthenticator(endpoint, name) { + return new PlainTextAuthenticator(name, this.username, this.password, this.authorizationId); + } +} /** - * @param {String} authenticatorName - * @param {String} authenticatorId - * @param {String} password - * @param {String} authorizationId + * @class + * @classdesc Authenticator for plain text authentication. * @extends BaseDseAuthenticator - * @constructor * @private */ -function PlainTextAuthenticator(authenticatorName, authenticatorId, password, authorizationId) { - BaseDseAuthenticator.call(this, authenticatorName); - this.authenticatorId = utils.allocBufferFromString(authenticatorId); - this.password = utils.allocBufferFromString(password); - this.authorizationId = utils.allocBufferFromString(authorizationId || ''); -} - -util.inherits(PlainTextAuthenticator, BaseDseAuthenticator); +class PlainTextAuthenticator extends BaseDseAuthenticator { + /** + * @param {String} authenticatorName + * @param {String} authenticatorId + * @param {String} password + * @param {String} authorizationId + */ + constructor(authenticatorName, authenticatorId, password, authorizationId) { + super(authenticatorName); + this.authenticatorId = utils.allocBufferFromString(authenticatorId); + this.password = utils.allocBufferFromString(password); + this.authorizationId = utils.allocBufferFromString(authorizationId || ''); + } -/** @override */ -PlainTextAuthenticator.prototype.getMechanism = function () { - return mechanism; -}; + /** @override */ + getMechanism() { + return mechanism; + } -/** @override */ -PlainTextAuthenticator.prototype.getInitialServerChallenge = function () { - return utils.allocBufferFromString(initialServerChallenge); -}; + /** @override */ + getInitialServerChallenge() { + return utils.allocBufferFromString(initialServerChallenge); + } -/** @override */ -PlainTextAuthenticator.prototype.evaluateChallenge = function (challenge, callback) { - if (!challenge || challenge.toString() !== initialServerChallenge) { - return callback(new Error('Incorrect SASL challenge from server')); + /** @override */ + evaluateChallenge(challenge, callback) { + if (!challenge || challenge.toString() !== initialServerChallenge) { + return callback(new Error('Incorrect SASL challenge from server')); + } + // The SASL plain text format is authorizationId 0 username 0 password + callback(null, Buffer.concat([ + this.authorizationId, + separatorBuffer, + this.authenticatorId, + separatorBuffer, + this.password + ])); } - // The SASL plain text format is authorizationId 0 username 0 password - callback(null, Buffer.concat([ - this.authorizationId, - separatorBuffer, - this.authenticatorId, - separatorBuffer, - this.password - ])); -}; +} module.exports = DsePlainTextAuthProvider; \ No newline at end of file diff --git a/lib/auth/plain-text-auth-provider.js b/lib/auth/plain-text-auth-provider.js index f5241f7e4..aee4459dd 100644 --- a/lib/auth/plain-text-auth-provider.js +++ b/lib/auth/plain-text-auth-provider.js @@ -14,66 +14,82 @@ * limitations under the License. */ 'use strict'; -const util = require('util'); - -const provider = require('./provider.js'); +const { AuthProvider, Authenticator } = require('./provider'); const utils = require('../utils'); -const AuthProvider = provider.AuthProvider; -const Authenticator = provider.Authenticator; + /** - * Creates a new instance of the Authenticator provider + * @class * @classdesc Provides plain text [Authenticator]{@link module:auth~Authenticator} instances to be used when * connecting to a host. - * @extends module:auth~AuthProvider + * @extends AuthProvider + * @alias module:auth~PlainTextAuthProvider * @example - * var authProvider = new cassandra.auth.PlainTextAuthProvider('my_user', 'p@ssword1!'); - * //Set the auth provider in the clientOptions when creating the Client instance + * const authProvider = new cassandra.auth.PlainTextAuthProvider('my_user', 'p@ssword1!'); + * // Set the auth provider in the clientOptions when creating the Client instance * const client = new Client({ contactPoints: contactPoints, authProvider: authProvider }); - * @param {String} username User name in plain text - * @param {String} password Password in plain text - * @alias module:auth~PlainTextAuthProvider - * @constructor */ -function PlainTextAuthProvider(username, password) { - this.username = username; - this.password = password; -} - -util.inherits(PlainTextAuthProvider, AuthProvider); +class PlainTextAuthProvider extends AuthProvider { + /** + * @param {String} username User name in plain text + * @param {String} password Password in plain text + */ + constructor(username, password) { + super(); + this.username = username; + this.password = password; + } -/** - * Returns a new [Authenticator]{@link module:auth~Authenticator} instance to be used for plain text authentication. - * @override - * @returns {Authenticator} - */ -PlainTextAuthProvider.prototype.newAuthenticator = function () { - return new PlainTextAuthenticator(this.username, this.password); -}; + /** + * Returns a new [Authenticator]{@link module:auth~Authenticator} instance to be used for plain text authentication. + * @override + * @returns {Authenticator} + */ + newAuthenticator() { + return new PlainTextAuthenticator(this.username, this.password); + } +} /** + * @class + * @classdesc Authenticator for plain text authentication. + * @extends Authenticator * @ignore */ -function PlainTextAuthenticator(username, password) { - this.username = username; - this.password = password; -} +class PlainTextAuthenticator extends Authenticator { + /** + * @param {String} username + * @param {String} password + */ + constructor(username, password) { + super(); + this.username = username; + this.password = password; + } -util.inherits(PlainTextAuthenticator, Authenticator); + /** + * Obtain an initial response token for initializing the SASL handshake. + * @param {Function} callback + */ + initialResponse(callback) { + const initialToken = Buffer.concat([ + utils.allocBufferFromArray([0]), + utils.allocBufferFromString(this.username, 'utf8'), + utils.allocBufferFromArray([0]), + utils.allocBufferFromString(this.password, 'utf8') + ]); + callback(null, initialToken); + } -PlainTextAuthenticator.prototype.initialResponse = function (callback) { - const initialToken = Buffer.concat([ - utils.allocBufferFromArray([0]), - utils.allocBufferFromString(this.username, 'utf8'), - utils.allocBufferFromArray([0]), - utils.allocBufferFromString(this.password, 'utf8') - ]); - callback(null, initialToken); -}; - -PlainTextAuthenticator.prototype.evaluateChallenge = function (challenge, callback) { - //noop - callback(); -}; + /** + * Evaluates a challenge received from the Server. + * @param {Buffer} challenge + * @param {Function} callback + */ + evaluateChallenge(challenge, callback) { + // noop + callback(); + } +} module.exports = { PlainTextAuthenticator, diff --git a/lib/auth/provider.js b/lib/auth/provider.js index d4bf9ed10..624bce863 100644 --- a/lib/auth/provider.js +++ b/lib/auth/provider.js @@ -14,66 +14,66 @@ * limitations under the License. */ 'use strict'; + /** * @classdesc Provides [Authenticator]{@link module:auth~Authenticator} instances to be used when connecting to a host. - * @constructor * @abstract * @alias module:auth~AuthProvider */ -function AuthProvider() { +class AuthProvider { + constructor() { + if (new.target === AuthProvider) { + throw new Error('This is an abstract class, you must implement newAuthenticator method or use another auth provider that inherits from this class'); + } + } + /** + * Returns an [Authenticator]{@link module:auth~Authenticator} instance to be used when connecting to a host. + * @param {String} endpoint The ip address and port number in the format ip:port + * @param {String} name Authenticator name + * @abstract + * @returns {Authenticator} + */ + newAuthenticator(endpoint, name) { + throw new Error('This is an abstract class, you must implement newAuthenticator method or use another auth provider that inherits from this class'); + } } -/** - * Returns an [Authenticator]{@link module:auth~Authenticator} instance to be used when connecting to a host. - * @param {String} endpoint The ip address and port number in the format ip:port - * @param {String} name Authenticator name - * @abstract - * @returns {Authenticator} - */ -AuthProvider.prototype.newAuthenticator = function (endpoint, name) { - throw new Error('This is an abstract class, you must implement newAuthenticator method or ' + - 'use another auth provider that inherits from this class'); -}; - /** * @class * @classdesc Handles SASL authentication with Cassandra servers. * Each time a new connection is created and the server requires authentication, * a new instance of this class will be created by the corresponding. - * @constructor * @alias module:auth~Authenticator */ -function Authenticator() { +class Authenticator { + constructor() {} -} + /** + * Obtain an initial response token for initializing the SASL handshake. + * @param {Function} callback + */ + initialResponse(callback) { + callback(new Error('Not implemented')); + } -/** - * Obtain an initial response token for initializing the SASL handshake. - * @param {Function} callback - */ -Authenticator.prototype.initialResponse = function (callback) { - callback(new Error('Not implemented')); -}; + /** + * Evaluates a challenge received from the Server. Generally, this method should callback with + * no error and no additional params when authentication is complete from the client perspective. + * @param {Buffer} challenge + * @param {Function} callback + */ + evaluateChallenge(challenge, callback) { + callback(new Error('Not implemented')); + } -/** - * Evaluates a challenge received from the Server. Generally, this method should callback with - * no error and no additional params when authentication is complete from the client perspective. - * @param {Buffer} challenge - * @param {Function} callback - */ -Authenticator.prototype.evaluateChallenge = function (challenge, callback) { - callback(new Error('Not implemented')); -}; - -/** - * Called when authentication is successful with the last information - * optionally sent by the server. - * @param {Buffer} [token] - */ -Authenticator.prototype.onAuthenticationSuccess = function (token) { - -}; + /** + * Called when authentication is successful with the last information + * optionally sent by the server. + * @param {Buffer} [token] + */ + onAuthenticationSuccess(token) {} +} exports.AuthProvider = AuthProvider; exports.Authenticator = Authenticator; \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 71377dcdd..b98801200 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,7 +16,7 @@ "target": "es2015", "lib": ["es2015"], "module": "CommonJS", - "strict": true, + // "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, From 4b6f2cbd6c37a77e9a2cc7f70746c9cbb6844505 Mon Sep 17 00:00:00 2001 From: Jane He Date: Wed, 18 Dec 2024 21:39:10 +0800 Subject: [PATCH 3/5] resolve error of keyword "in" --- lib/datastax/graph/index.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/datastax/graph/index.js b/lib/datastax/graph/index.js index a0333a06e..3d44ee0a5 100644 --- a/lib/datastax/graph/index.js +++ b/lib/datastax/graph/index.js @@ -48,9 +48,11 @@ const t = { /** * Represents the edge direction. + * @type {{both: EnumValue, in_: EnumValue, out: EnumValue}} */ const direction = { 'both': new EnumValue('Direction', 'BOTH'), + // @ts-ignore 'in': new EnumValue('Direction', 'IN'), 'out': new EnumValue('Direction', 'OUT') }; @@ -58,6 +60,7 @@ const direction = { // `in` is a reserved keyword depending on the context // TinkerPop JavaScript GLV only exposes `in` but it can lead to issues for TypeScript users and others. // Expose an extra property to represent `Direction.IN`. +// @ts-ignore direction.in_ = direction.in; module.exports = { From e24e2009d330e4cc918e972030a7735cf5d9398b Mon Sep 17 00:00:00 2001 From: Jane He Date: Thu, 19 Dec 2024 16:40:58 +0800 Subject: [PATCH 4/5] revert dependencies changes --- package-lock.json | 12 +++++++++++- package.json | 5 +++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index d874f2382..e6cd28697 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,8 @@ "version": "4.7.2", "license": "Apache-2.0", "dependencies": { - "@types/node": "^18.19.68", + "@types/long": "~5.0.0", + "@types/node": "^18.11.18", "adm-zip": "~0.5.10", "long": "~5.2.3" }, @@ -70,6 +71,15 @@ "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==", "dev": true }, + "node_modules/@types/long": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/long/-/long-5.0.0.tgz", + "integrity": "sha512-eQs9RsucA/LNjnMoJvWG/nXa7Pot/RbBzilF/QRIU/xRl+0ApxrSUFsV5lmf01SvSlqMzJ7Zwxe440wmz2SJGA==", + "deprecated": "This is a stub types definition. long provides its own type definitions, so you do not need this installed.", + "dependencies": { + "long": "*" + } + }, "node_modules/@types/node": { "version": "18.19.68", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.68.tgz", diff --git a/package.json b/package.json index e2bc94322..53c35a046 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "main": "lib/index.js", "types": "dist/lib/index.d.ts", "dependencies": { - "@types/node": "^18.19.68", + "@types/long": "~5.0.0", + "@types/node": "^18.11.18", "adm-zip": "~0.5.10", "long": "~5.2.3" }, @@ -55,4 +56,4 @@ "engines": { "node": ">=16" } -} +} \ No newline at end of file From aec68d228e388ab8c5bc6563b560195cda3d9a38 Mon Sep 17 00:00:00 2001 From: Jane He Date: Thu, 19 Dec 2024 16:43:59 +0800 Subject: [PATCH 5/5] revert package-lock.json --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index e6cd28697..d35a5d25c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -81,9 +81,9 @@ } }, "node_modules/@types/node": { - "version": "18.19.68", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.68.tgz", - "integrity": "sha512-QGtpFH1vB99ZmTa63K4/FU8twThj4fuVSBkGddTp7uIL/cuoLWIUSL2RcOaigBhfR+hg5pgGkBnkoOxrTVBMKw==", + "version": "18.19.53", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.53.tgz", + "integrity": "sha512-GLxgUgHhDKO1Edw9Q0lvMbiO/IQXJwJlMaqxSGBXMpPy8uhkCs2iiPFaB2Q/gmobnFkckD3rqTBMVjXdwq+nKg==", "dependencies": { "undici-types": "~5.26.4" }