tedious
Version:
A TDS driver, for connecting to MS SQLServer databases.
1 lines • 218 kB
Source Map (JSON)
{"version":3,"file":"connection.js","names":["_crypto","_interopRequireDefault","require","_os","tls","_interopRequireWildcard","net","_dns","_constants","_stream","_identity","_coreAuth","_bulkLoad","_debug","_events","_instanceLookup","_transientErrorLookup","_packet","_preloginPayload","_login7Payload","_ntlmPayload","_request","_rpcrequestPayload","_sqlbatchPayload","_messageIo","_tokenStreamParser","_transaction","_errors","_connector","_library","_tdsVersions","_message","_ntlm","_dataType","_bulkLoadPayload","_specialStoredProcedure","_package","_url","_handler","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","obj","KEEP_ALIVE_INITIAL_DELAY","DEFAULT_CONNECT_TIMEOUT","DEFAULT_CLIENT_REQUEST_TIMEOUT","DEFAULT_CANCEL_TIMEOUT","DEFAULT_CONNECT_RETRY_INTERVAL","DEFAULT_PACKET_SIZE","DEFAULT_TEXTSIZE","DEFAULT_DATEFIRST","DEFAULT_PORT","DEFAULT_TDS_VERSION","DEFAULT_LANGUAGE","DEFAULT_DATEFORMAT","CLEANUP_TYPE","NORMAL","REDIRECT","RETRY","Connection","EventEmitter","_cancelAfterRequestSent","constructor","config","TypeError","server","fedAuthRequired","authentication","undefined","type","options","domain","userName","password","toUpperCase","isTokenCredential","credential","clientId","tenantId","token","clientSecret","abortTransactionOnError","appName","camelCaseColumns","cancelTimeout","columnEncryptionKeyCacheTTL","columnEncryptionSetting","columnNameReplacer","connectionRetryInterval","connectTimeout","connector","connectionIsolationLevel","ISOLATION_LEVEL","READ_COMMITTED","cryptoCredentialsDetails","database","datefirst","dateFormat","debug","data","packet","payload","enableAnsiNull","enableAnsiNullDefault","enableAnsiPadding","enableAnsiWarnings","enableArithAbort","enableConcatNullYieldsNull","enableCursorCloseOnCommit","enableImplicitTransactions","enableNumericRoundabort","enableQuotedIdentifier","encrypt","fallbackToDefaultDb","encryptionKeyStoreProviders","instanceName","isolationLevel","language","localAddress","maxRetriesOnTransientErrors","multiSubnetFailover","packetSize","port","readOnlyIntent","requestTimeout","rowCollectionOnDone","rowCollectionOnRequestCompletion","serverName","serverSupportsColumnEncryption","tdsVersion","textsize","trustedServerNameAE","trustServerCertificate","useColumnNames","useUTC","workstationId","lowerCaseGuids","Error","assertValidIsolationLevel","RangeError","secureContextOptions","secureOptions","create","value","constants","SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS","createDebug","inTransaction","transactionDescriptors","Buffer","from","transactionDepth","isSqlBatch","closed","messageBuffer","alloc","curTransientRetryCount","transientErrorLookup","TransientErrorLookup","state","STATE","INITIALIZED","messageIo","sendMessage","TYPE","ATTENTION","createCancelTimer","connect","connectListener","ConnectionError","name","onConnect","err","removeListener","onError","once","transitionTo","CONNECTING","on","event","listener","emit","args","close","FINAL","initialiseConnection","signal","createConnectTimer","connectOnPort","instanceLookup","timeout","then","process","nextTick","clearConnectTimer","aborted","message","cause","cleanupConnection","cleanupType","clearRequestTimer","clearRetryTimer","closeConnection","request","RequestError","callback","loginError","Debug","createTokenStreamParser","handler","TokenStreamParser","socketHandlingForSendPreLogin","socket","error","socketError","socketClose","socketEnd","setKeepAlive","MessageIO","cleartext","log","sendPreLogin","SENT_PRELOGIN","wrapWithTls","throwIfAborted","Promise","resolve","reject","secureContext","createSecureContext","isIP","encryptOptions","host","ALPNProtocols","servername","encryptsocket","onAbort","destroy","reason","removeEventListener","addEventListener","customConnector","connectOpts","routingData","connectInParallel","connectInSequence","dns","lookup","end","catch","controller","AbortController","connectTimer","setTimeout","abort","clearCancelTimer","cancelTimer","createRequestTimer","requestTimer","createRetryTimer","retryTimer","retryTimeout","hostPostfix","routingMessage","dispatchEvent","cancel","clearTimeout","newState","exit","enter","apply","getEventHandler","eventName","events","SENT_TLSSSLNEGOTIATION","code","REROUTING","TRANSIENT_FAILURE_RETRY","major","minor","build","exec","version","PreloginPayload","Number","subbuild","PRELOGIN","toString","sendLogin7Packet","Login7Payload","versions","clientProgVer","clientPid","pid","connectionId","clientTimeZone","Date","getTimezoneOffset","clientLcid","fedAuth","echo","workflow","fedAuthToken","sspi","createNTLMRequest","hostname","os","libraryName","initDbFatal","LOGIN7","toBuffer","sendFedAuthTokenMessage","accessTokenLen","byteLength","offset","writeUInt32LE","write","FEDAUTH_TOKEN","SENT_LOGIN7_WITH_STANDARD_LOGIN","sendInitialSql","SqlBatchPayload","getInitialSql","currentTransactionDescriptor","Message","SQL_BATCH","outgoingMessageStream","Readable","pipe","push","getIsolationLevelText","join","processedInitialSql","execSqlBatch","makeRequest","sqlTextOrProcedure","execSql","validateParameters","databaseCollation","parameters","TYPES","NVarChar","output","length","precision","scale","makeParamsParameter","RPC_REQUEST","RpcRequestPayload","Procedures","Sp_ExecuteSql","newBulkLoad","table","callbackOrOptions","BulkLoad","execBulkLoad","bulkLoad","rows","executionStarted","streamingMode","firstRowWritten","rowStream","rowToPacketTransform","onCancel","BulkLoadPayload","Request","getBulkInsertSql","BULK_LOAD","prepare","Int","preparing","handle","Sp_Prepare","unprepare","Sp_Unprepare","execute","executeParameters","len","parameter","validate","Sp_Execute","callProcedure","beginTransaction","transaction","Transaction","isolationLevelToTSQL","TRANSACTION_MANAGER","beginPayload","commitTransaction","commitPayload","rollbackTransaction","rollbackPayload","saveTransaction","savePayload","cb","useSavepoint","crypto","randomBytes","txDone","done","LOGGED_IN","txErr","packetType","canceled","connection","rowCount","rst","payloadStream","unpipe","ignore","paused","resume","resetConnection","resetConnectionOnNextRequest","SENT_CLIENT_REQUEST","reset","READ_UNCOMMITTED","REPEATABLE_READ","SERIALIZABLE","SNAPSHOT","isTransientError","AggregateError","errors","isTransient","_default","exports","module","readMessage","concat","preloginPayload","encryptionString","startTls","SENT_LOGIN7_WITH_FEDAUTH","SENT_LOGIN7_WITH_NTLM","reconnect","retry","Login7TokenHandler","tokenStreamParser","loginAckReceived","LOGGED_IN_SENDING_INITIAL_SQL","ntlmpacket","NTLMResponsePayload","NTLMAUTH_PKT","fedAuthInfoToken","stsurl","spn","tokenScope","URL","credentials","UsernamePasswordCredential","msiArgs","ManagedIdentityCredential","managedIdentityClientId","DefaultAzureCredential","ClientSecretCredential","tokenResponse","getToken","InitialSqlTokenHandler","RequestTokenHandler","SENT_ATTENTION","onResume","onPause","pause","onEndOfMessage","sqlRequest","nextState","AttentionTokenHandler","attentionReceived"],"sources":["../src/connection.ts"],"sourcesContent":["import crypto from 'crypto';\nimport os from 'os';\nimport * as tls from 'tls';\nimport * as net from 'net';\nimport dns from 'dns';\n\nimport constants from 'constants';\nimport { type SecureContextOptions } from 'tls';\n\nimport { Readable } from 'stream';\n\nimport {\n ClientSecretCredential,\n DefaultAzureCredential,\n ManagedIdentityCredential,\n UsernamePasswordCredential\n} from '@azure/identity';\nimport { type AccessToken, type TokenCredential, isTokenCredential } from '@azure/core-auth';\n\nimport BulkLoad, { type Options as BulkLoadOptions, type Callback as BulkLoadCallback } from './bulk-load';\nimport Debug from './debug';\nimport { EventEmitter, once } from 'events';\nimport { instanceLookup } from './instance-lookup';\nimport { TransientErrorLookup } from './transient-error-lookup';\nimport { TYPE } from './packet';\nimport PreloginPayload from './prelogin-payload';\nimport Login7Payload from './login7-payload';\nimport NTLMResponsePayload from './ntlm-payload';\nimport Request from './request';\nimport RpcRequestPayload from './rpcrequest-payload';\nimport SqlBatchPayload from './sqlbatch-payload';\nimport MessageIO from './message-io';\nimport { Parser as TokenStreamParser } from './token/token-stream-parser';\nimport { Transaction, ISOLATION_LEVEL, assertValidIsolationLevel } from './transaction';\nimport { ConnectionError, RequestError } from './errors';\nimport { connectInParallel, connectInSequence } from './connector';\nimport { name as libraryName } from './library';\nimport { versions } from './tds-versions';\nimport Message from './message';\nimport { type Metadata } from './metadata-parser';\nimport { createNTLMRequest } from './ntlm';\nimport { ColumnEncryptionAzureKeyVaultProvider } from './always-encrypted/keystore-provider-azure-key-vault';\n\nimport { type Parameter, TYPES } from './data-type';\nimport { BulkLoadPayload } from './bulk-load-payload';\nimport { Collation } from './collation';\nimport Procedures from './special-stored-procedure';\n\nimport { version } from '../package.json';\nimport { URL } from 'url';\nimport { AttentionTokenHandler, InitialSqlTokenHandler, Login7TokenHandler, RequestTokenHandler, TokenHandler } from './token/handler';\n\ntype BeginTransactionCallback =\n /**\n * The callback is called when the request to start the transaction has completed,\n * either successfully or with an error.\n * If an error occurred then `err` will describe the error.\n *\n * As only one request at a time may be executed on a connection, another request should not\n * be initiated until this callback is called.\n *\n * @param err If an error occurred, an [[Error]] object with details of the error.\n * @param transactionDescriptor A Buffer that describe the transaction\n */\n (err: Error | null | undefined, transactionDescriptor?: Buffer) => void\n\ntype SaveTransactionCallback =\n /**\n * The callback is called when the request to set a savepoint within the\n * transaction has completed, either successfully or with an error.\n * If an error occurred then `err` will describe the error.\n *\n * As only one request at a time may be executed on a connection, another request should not\n * be initiated until this callback is called.\n *\n * @param err If an error occurred, an [[Error]] object with details of the error.\n */\n (err: Error | null | undefined) => void;\n\ntype CommitTransactionCallback =\n /**\n * The callback is called when the request to commit the transaction has completed,\n * either successfully or with an error.\n * If an error occurred then `err` will describe the error.\n *\n * As only one request at a time may be executed on a connection, another request should not\n * be initiated until this callback is called.\n *\n * @param err If an error occurred, an [[Error]] object with details of the error.\n */\n (err: Error | null | undefined) => void;\n\ntype RollbackTransactionCallback =\n /**\n * The callback is called when the request to rollback the transaction has\n * completed, either successfully or with an error.\n * If an error occurred then err will describe the error.\n *\n * As only one request at a time may be executed on a connection, another request should not\n * be initiated until this callback is called.\n *\n * @param err If an error occurred, an [[Error]] object with details of the error.\n */\n (err: Error | null | undefined) => void;\n\ntype ResetCallback =\n /**\n * The callback is called when the connection reset has completed,\n * either successfully or with an error.\n *\n * If an error occurred then `err` will describe the error.\n *\n * As only one request at a time may be executed on a connection, another\n * request should not be initiated until this callback is called\n *\n * @param err If an error occurred, an [[Error]] object with details of the error.\n */\n (err: Error | null | undefined) => void;\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype TransactionCallback<T extends (err: Error | null | undefined, ...args: any[]) => void> =\n /**\n * The callback is called when the request to start a transaction (or create a savepoint, in\n * the case of a nested transaction) has completed, either successfully or with an error.\n * If an error occurred, then `err` will describe the error.\n * If no error occurred, the callback should perform its work and eventually call\n * `done` with an error or null (to trigger a transaction rollback or a\n * transaction commit) and an additional completion callback that will be called when the request\n * to rollback or commit the current transaction has completed, either successfully or with an error.\n * Additional arguments given to `done` will be passed through to this callback.\n *\n * As only one request at a time may be executed on a connection, another request should not\n * be initiated until the completion callback is called.\n *\n * @param err If an error occurred, an [[Error]] object with details of the error.\n * @param txDone If no error occurred, a function to be called to commit or rollback the transaction.\n */\n (err: Error | null | undefined, txDone?: TransactionDone<T>) => void;\n\ntype TransactionDoneCallback = (err: Error | null | undefined, ...args: any[]) => void;\ntype CallbackParameters<T extends (err: Error | null | undefined, ...args: any[]) => any> = T extends (err: Error | null | undefined, ...args: infer P) => any ? P : never;\n\ntype TransactionDone<T extends (err: Error | null | undefined, ...args: any[]) => void> =\n /**\n * If no error occurred, a function to be called to commit or rollback the transaction.\n *\n * @param err If an err occurred, a string with details of the error.\n */\n (err: Error | null | undefined, done: T, ...args: CallbackParameters<T>) => void;\n\n/**\n * @private\n */\nconst KEEP_ALIVE_INITIAL_DELAY = 30 * 1000;\n/**\n * @private\n */\nconst DEFAULT_CONNECT_TIMEOUT = 15 * 1000;\n/**\n * @private\n */\nconst DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000;\n/**\n * @private\n */\nconst DEFAULT_CANCEL_TIMEOUT = 5 * 1000;\n/**\n * @private\n */\nconst DEFAULT_CONNECT_RETRY_INTERVAL = 500;\n/**\n * @private\n */\nconst DEFAULT_PACKET_SIZE = 4 * 1024;\n/**\n * @private\n */\nconst DEFAULT_TEXTSIZE = 2147483647;\n/**\n * @private\n */\nconst DEFAULT_DATEFIRST = 7;\n/**\n * @private\n */\nconst DEFAULT_PORT = 1433;\n/**\n * @private\n */\nconst DEFAULT_TDS_VERSION = '7_4';\n/**\n * @private\n */\nconst DEFAULT_LANGUAGE = 'us_english';\n/**\n * @private\n */\nconst DEFAULT_DATEFORMAT = 'mdy';\n\ninterface AzureActiveDirectoryMsiAppServiceAuthentication {\n type: 'azure-active-directory-msi-app-service';\n options: {\n /**\n * If you user want to connect to an Azure app service using a specific client account\n * they need to provide `clientId` associate to their created identity.\n *\n * This is optional for retrieve token from azure web app service\n */\n clientId?: string;\n };\n}\n\ninterface AzureActiveDirectoryMsiVmAuthentication {\n type: 'azure-active-directory-msi-vm';\n options: {\n /**\n * If you want to connect using a specific client account\n * they need to provide `clientId` associated to their created identity.\n *\n * This is optional for retrieve a token\n */\n clientId?: string;\n };\n}\n\ninterface AzureActiveDirectoryDefaultAuthentication {\n type: 'azure-active-directory-default';\n options: {\n /**\n * If you want to connect using a specific client account\n * they need to provide `clientId` associated to their created identity.\n *\n * This is optional for retrieving a token\n */\n clientId?: string;\n };\n}\n\n\ninterface AzureActiveDirectoryAccessTokenAuthentication {\n type: 'azure-active-directory-access-token';\n options: {\n /**\n * A user need to provide `token` which they retrieved else where\n * to forming the connection.\n */\n token: string;\n };\n}\n\ninterface AzureActiveDirectoryPasswordAuthentication {\n type: 'azure-active-directory-password';\n options: {\n /**\n * A user need to provide `userName` associate to their account.\n */\n userName: string;\n\n /**\n * A user need to provide `password` associate to their account.\n */\n password: string;\n\n /**\n * A client id to use.\n */\n clientId: string;\n\n /**\n * Optional parameter for specific Azure tenant ID\n */\n tenantId: string;\n };\n}\n\ninterface AzureActiveDirectoryServicePrincipalSecret {\n type: 'azure-active-directory-service-principal-secret';\n options: {\n /**\n * Application (`client`) ID from your registered Azure application\n */\n clientId: string;\n /**\n * The created `client secret` for this registered Azure application\n */\n clientSecret: string;\n /**\n * Directory (`tenant`) ID from your registered Azure application\n */\n tenantId: string;\n };\n}\n\n/** Structure that defines the options that are necessary to authenticate the Tedious.JS instance with an `@azure/identity` token credential. */\ninterface TokenCredentialAuthentication {\n /** Unique designator for the type of authentication to be used. */\n type: 'token-credential';\n /** Set of configurations that are required or allowed with this authentication type. */\n options: {\n /** Credential object used to authenticate to the resource. */\n credential: TokenCredential;\n };\n}\n\ninterface NtlmAuthentication {\n type: 'ntlm';\n options: {\n /**\n * User name from your windows account.\n */\n userName: string;\n /**\n * Password from your windows account.\n */\n password: string;\n /**\n * Once you set domain for ntlm authentication type, driver will connect to SQL Server using domain login.\n *\n * This is necessary for forming a connection using ntlm type\n */\n domain: string;\n };\n}\n\ninterface DefaultAuthentication {\n type: 'default';\n options: {\n /**\n * User name to use for sql server login.\n */\n userName?: string | undefined;\n /**\n * Password to use for sql server login.\n */\n password?: string | undefined;\n };\n}\n\ninterface ErrorWithCode extends Error {\n code?: string;\n}\n\nexport type ConnectionAuthentication = DefaultAuthentication | NtlmAuthentication | TokenCredentialAuthentication | AzureActiveDirectoryPasswordAuthentication | AzureActiveDirectoryMsiAppServiceAuthentication | AzureActiveDirectoryMsiVmAuthentication | AzureActiveDirectoryAccessTokenAuthentication | AzureActiveDirectoryServicePrincipalSecret | AzureActiveDirectoryDefaultAuthentication;\n\ninterface InternalConnectionConfig {\n server: string;\n authentication: ConnectionAuthentication;\n options: InternalConnectionOptions;\n}\n\nexport interface InternalConnectionOptions {\n abortTransactionOnError: boolean;\n appName: undefined | string;\n camelCaseColumns: boolean;\n cancelTimeout: number;\n columnEncryptionKeyCacheTTL: number;\n columnEncryptionSetting: boolean;\n columnNameReplacer: undefined | ((colName: string, index: number, metadata: Metadata) => string);\n connectionRetryInterval: number;\n connector: undefined | (() => Promise<net.Socket>);\n connectTimeout: number;\n connectionIsolationLevel: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL];\n cryptoCredentialsDetails: SecureContextOptions;\n database: undefined | string;\n datefirst: number;\n dateFormat: string;\n debug: {\n data: boolean;\n packet: boolean;\n payload: boolean;\n token: boolean;\n };\n enableAnsiNull: null | boolean;\n enableAnsiNullDefault: null | boolean;\n enableAnsiPadding: null | boolean;\n enableAnsiWarnings: null | boolean;\n enableArithAbort: null | boolean;\n enableConcatNullYieldsNull: null | boolean;\n enableCursorCloseOnCommit: null | boolean;\n enableImplicitTransactions: null | boolean;\n enableNumericRoundabort: null | boolean;\n enableQuotedIdentifier: null | boolean;\n encrypt: string | boolean;\n encryptionKeyStoreProviders: KeyStoreProviderMap | undefined;\n fallbackToDefaultDb: boolean;\n instanceName: undefined | string;\n isolationLevel: typeof ISOLATION_LEVEL[keyof typeof ISOLATION_LEVEL];\n language: string;\n localAddress: undefined | string;\n maxRetriesOnTransientErrors: number;\n multiSubnetFailover: boolean;\n packetSize: number;\n port: undefined | number;\n readOnlyIntent: boolean;\n requestTimeout: number;\n rowCollectionOnDone: boolean;\n rowCollectionOnRequestCompletion: boolean;\n serverName: undefined | string;\n serverSupportsColumnEncryption: boolean;\n tdsVersion: string;\n textsize: number;\n trustedServerNameAE: string | undefined;\n trustServerCertificate: boolean;\n useColumnNames: boolean;\n useUTC: boolean;\n workstationId: undefined | string;\n lowerCaseGuids: boolean;\n}\n\ninterface KeyStoreProviderMap {\n [key: string]: ColumnEncryptionAzureKeyVaultProvider;\n}\n\n/**\n * @private\n */\ninterface State {\n name: string;\n enter?(this: Connection): void;\n exit?(this: Connection, newState: State): void;\n events: {\n socketError?(this: Connection, err: Error): void;\n connectTimeout?(this: Connection): void;\n message?(this: Connection, message: Message): void;\n retry?(this: Connection): void;\n reconnect?(this: Connection): void;\n };\n}\n\ntype Authentication = DefaultAuthentication |\n NtlmAuthentication |\n TokenCredentialAuthentication |\n AzureActiveDirectoryPasswordAuthentication |\n AzureActiveDirectoryMsiAppServiceAuthentication |\n AzureActiveDirectoryMsiVmAuthentication |\n AzureActiveDirectoryAccessTokenAuthentication |\n AzureActiveDirectoryServicePrincipalSecret |\n AzureActiveDirectoryDefaultAuthentication;\n\ntype AuthenticationType = Authentication['type'];\n\nexport interface ConnectionConfiguration {\n /**\n * Hostname to connect to.\n */\n server: string;\n /**\n * Configuration options for forming the connection.\n */\n options?: ConnectionOptions;\n /**\n * Authentication related options for connection.\n */\n authentication?: AuthenticationOptions;\n}\n\ninterface DebugOptions {\n /**\n * A boolean, controlling whether [[debug]] events will be emitted with text describing packet data details\n *\n * (default: `false`)\n */\n data: boolean;\n /**\n * A boolean, controlling whether [[debug]] events will be emitted with text describing packet details\n *\n * (default: `false`)\n */\n packet: boolean;\n /**\n * A boolean, controlling whether [[debug]] events will be emitted with text describing packet payload details\n *\n * (default: `false`)\n */\n payload: boolean;\n /**\n * A boolean, controlling whether [[debug]] events will be emitted with text describing token stream tokens\n *\n * (default: `false`)\n */\n token: boolean;\n}\n\ninterface AuthenticationOptions {\n /**\n * Type of the authentication method, valid types are `default`, `ntlm`,\n * `azure-active-directory-password`, `azure-active-directory-access-token`,\n * `azure-active-directory-msi-vm`, `azure-active-directory-msi-app-service`,\n * `azure-active-directory-default`\n * or `azure-active-directory-service-principal-secret`\n */\n type?: AuthenticationType;\n /**\n * Different options for authentication types:\n *\n * * `default`: [[DefaultAuthentication.options]]\n * * `ntlm` :[[NtlmAuthentication]]\n * * `token-credential`: [[CredentialChainAuthentication.options]]\n * * `azure-active-directory-password` : [[AzureActiveDirectoryPasswordAuthentication.options]]\n * * `azure-active-directory-access-token` : [[AzureActiveDirectoryAccessTokenAuthentication.options]]\n * * `azure-active-directory-msi-vm` : [[AzureActiveDirectoryMsiVmAuthentication.options]]\n * * `azure-active-directory-msi-app-service` : [[AzureActiveDirectoryMsiAppServiceAuthentication.options]]\n * * `azure-active-directory-service-principal-secret` : [[AzureActiveDirectoryServicePrincipalSecret.options]]\n * * `azure-active-directory-default` : [[AzureActiveDirectoryDefaultAuthentication.options]]\n */\n options?: any;\n}\n\nexport interface ConnectionOptions {\n /**\n * A boolean determining whether to rollback a transaction automatically if any error is encountered\n * during the given transaction's execution. This sets the value for `SET XACT_ABORT` during the\n * initial SQL phase of a connection [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql).\n */\n abortTransactionOnError?: boolean | undefined;\n\n /**\n * Application name used for identifying a specific application in profiling, logging or tracing tools of SQLServer.\n *\n * (default: `Tedious`)\n */\n appName?: string | undefined;\n\n /**\n * A boolean, controlling whether the column names returned will have the first letter converted to lower case\n * (`true`) or not. This value is ignored if you provide a [[columnNameReplacer]].\n *\n * (default: `false`).\n */\n camelCaseColumns?: boolean;\n\n /**\n * The number of milliseconds before the [[Request.cancel]] (abort) of a request is considered failed\n *\n * (default: `5000`).\n */\n cancelTimeout?: number;\n\n /**\n * A function with parameters `(columnName, index, columnMetaData)` and returning a string. If provided,\n * this will be called once per column per result-set. The returned value will be used instead of the SQL-provided\n * column name on row and meta data objects. This allows you to dynamically convert between naming conventions.\n *\n * (default: `null`)\n */\n columnNameReplacer?: (colName: string, index: number, metadata: Metadata) => string;\n\n /**\n * Number of milliseconds before retrying to establish connection, in case of transient failure.\n *\n * (default:`500`)\n */\n connectionRetryInterval?: number;\n\n /**\n * Custom connector factory method.\n *\n * (default: `undefined`)\n */\n connector?: () => Promise<net.Socket>;\n\n /**\n * The number of milliseconds before the attempt to connect is considered failed\n *\n * (default: `15000`).\n */\n connectTimeout?: number;\n\n /**\n * The default isolation level for new connections. All out-of-transaction queries are executed with this setting.\n *\n * The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.\n * * `READ_UNCOMMITTED`\n * * `READ_COMMITTED`\n * * `REPEATABLE_READ`\n * * `SERIALIZABLE`\n * * `SNAPSHOT`\n *\n * (default: `READ_COMMITED`).\n */\n connectionIsolationLevel?: number;\n\n /**\n * When encryption is used, an object may be supplied that will be used\n * for the first argument when calling [`tls.createSecurePair`](http://nodejs.org/docs/latest/api/tls.html#tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized)\n *\n * (default: `{}`)\n */\n cryptoCredentialsDetails?: SecureContextOptions;\n\n /**\n * Database to connect to (default: dependent on server configuration).\n */\n database?: string | undefined;\n\n /**\n * Sets the first day of the week to a number from 1 through 7.\n */\n datefirst?: number;\n\n /**\n * A string representing position of month, day and year in temporal datatypes.\n *\n * (default: `mdy`)\n */\n dateFormat?: string;\n\n debug?: DebugOptions;\n\n /**\n * A boolean, controls the way null values should be used during comparison operation.\n *\n * (default: `true`)\n */\n enableAnsiNull?: boolean;\n\n /**\n * If true, `SET ANSI_NULL_DFLT_ON ON` will be set in the initial sql. This means new columns will be\n * nullable by default. See the [T-SQL documentation](https://msdn.microsoft.com/en-us/library/ms187375.aspx)\n *\n * (default: `true`).\n */\n enableAnsiNullDefault?: boolean;\n\n /**\n * A boolean, controls if padding should be applied for values shorter than the size of defined column.\n *\n * (default: `true`)\n */\n enableAnsiPadding?: boolean;\n\n /**\n * If true, SQL Server will follow ISO standard behavior during various error conditions. For details,\n * see [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-warnings-transact-sql)\n *\n * (default: `true`)\n */\n enableAnsiWarnings?: boolean;\n\n /**\n * Ends a query when an overflow or divide-by-zero error occurs during query execution.\n * See [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-arithabort-transact-sql?view=sql-server-2017)\n * for more details.\n *\n * (default: `true`)\n */\n enableArithAbort?: boolean;\n\n /**\n * A boolean, determines if concatenation with NULL should result in NULL or empty string value, more details in\n * [documentation](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-concat-null-yields-null-transact-sql)\n *\n * (default: `true`)\n */\n enableConcatNullYieldsNull?: boolean;\n\n /**\n * A boolean, controls whether cursor should be closed, if the transaction opening it gets committed or rolled\n * back.\n *\n * (default: `null`)\n */\n enableCursorCloseOnCommit?: boolean | null;\n\n /**\n * A boolean, sets the connection to either implicit or autocommit transaction mode.\n *\n * (default: `false`)\n */\n enableImplicitTransactions?: boolean;\n\n /**\n * If false, error is not generated during loss of precession.\n *\n * (default: `false`)\n */\n enableNumericRoundabort?: boolean;\n\n /**\n * If true, characters enclosed in single quotes are treated as literals and those enclosed double quotes are treated as identifiers.\n *\n * (default: `true`)\n */\n enableQuotedIdentifier?: boolean;\n\n /**\n * A string value that can be only set to 'strict', which indicates the usage TDS 8.0 protocol. Otherwise,\n * a boolean determining whether or not the connection will be encrypted.\n *\n * (default: `true`)\n */\n encrypt?: string | boolean;\n\n /**\n * By default, if the database requested by [[database]] cannot be accessed,\n * the connection will fail with an error. However, if [[fallbackToDefaultDb]] is\n * set to `true`, then the user's default database will be used instead\n *\n * (default: `false`)\n */\n fallbackToDefaultDb?: boolean;\n\n /**\n * The instance name to connect to.\n * The SQL Server Browser service must be running on the database server,\n * and UDP port 1434 on the database server must be reachable.\n *\n * (no default)\n *\n * Mutually exclusive with [[port]].\n */\n instanceName?: string | undefined;\n\n /**\n * The default isolation level that transactions will be run with.\n *\n * The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.\n * * `READ_UNCOMMITTED`\n * * `READ_COMMITTED`\n * * `REPEATABLE_READ`\n * * `SERIALIZABLE`\n * * `SNAPSHOT`\n *\n * (default: `READ_COMMITED`).\n */\n isolationLevel?: number;\n\n /**\n * Specifies the language environment for the session. The session language determines the datetime formats and system messages.\n *\n * (default: `us_english`).\n */\n language?: string;\n\n /**\n * A string indicating which network interface (ip address) to use when connecting to SQL Server.\n */\n localAddress?: string | undefined;\n\n /**\n * A boolean determining whether to parse unique identifier type with lowercase case characters.\n *\n * (default: `false`).\n */\n lowerCaseGuids?: boolean;\n\n /**\n * The maximum number of connection retries for transient errors.、\n *\n * (default: `3`).\n */\n maxRetriesOnTransientErrors?: number;\n\n /**\n * Sets the MultiSubnetFailover = True parameter, which can help minimize the client recovery latency when failovers occur.\n *\n * (default: `false`).\n */\n multiSubnetFailover?: boolean;\n\n /**\n * The size of TDS packets (subject to negotiation with the server).\n * Should be a power of 2.\n *\n * (default: `4096`).\n */\n packetSize?: number;\n\n /**\n * Port to connect to (default: `1433`).\n *\n * Mutually exclusive with [[instanceName]]\n */\n port?: number | undefined;\n\n /**\n * A boolean, determining whether the connection will request read only access from a SQL Server Availability\n * Group. For more information, see [here](http://msdn.microsoft.com/en-us/library/hh710054.aspx \"Microsoft: Configure Read-Only Routing for an Availability Group (SQL Server)\")\n *\n * (default: `false`).\n */\n readOnlyIntent?: boolean;\n\n /**\n * The number of milliseconds before a request is considered failed, or `0` for no timeout.\n *\n * As soon as a response is received, the timeout is cleared. This means that queries that immediately return a response have ability to run longer than this timeout.\n *\n * (default: `15000`).\n */\n requestTimeout?: number;\n\n /**\n * A boolean, that when true will expose received rows in Requests done related events:\n * * [[Request.Event_doneInProc]]\n * * [[Request.Event_doneProc]]\n * * [[Request.Event_done]]\n *\n * (default: `false`)\n *\n * Caution: If many row are received, enabling this option could result in\n * excessive memory usage.\n */\n rowCollectionOnDone?: boolean;\n\n /**\n * A boolean, that when true will expose received rows in Requests' completion callback.See [[Request.constructor]].\n *\n * (default: `false`)\n *\n * Caution: If many row are received, enabling this option could result in\n * excessive memory usage.\n */\n rowCollectionOnRequestCompletion?: boolean;\n\n /**\n * The version of TDS to use. If server doesn't support specified version, negotiated version is used instead.\n *\n * The versions are available from `require('tedious').TDS_VERSION`.\n * * `7_1`\n * * `7_2`\n * * `7_3_A`\n * * `7_3_B`\n * * `7_4`\n *\n * (default: `7_4`)\n */\n tdsVersion?: string | undefined;\n\n /**\n * Specifies the size of varchar(max), nvarchar(max), varbinary(max), text, ntext, and image data returned by a SELECT statement.\n *\n * (default: `2147483647`)\n */\n textsize?: number;\n\n /**\n * If \"true\", the SQL Server SSL certificate is automatically trusted when the communication layer is encrypted using SSL.\n *\n * If \"false\", the SQL Server validates the server SSL certificate. If the server certificate validation fails,\n * the driver raises an error and terminates the connection. Make sure the value passed to serverName exactly\n * matches the Common Name (CN) or DNS name in the Subject Alternate Name in the server certificate for an SSL connection to succeed.\n *\n * (default: `true`)\n */\n trustServerCertificate?: boolean;\n\n /**\n *\n */\n serverName?: string;\n /**\n * A boolean determining whether to return rows as arrays or key-value collections.\n *\n * (default: `false`).\n */\n useColumnNames?: boolean;\n\n /**\n * A boolean determining whether to pass time values in UTC or local time.\n *\n * (default: `true`).\n */\n useUTC?: boolean;\n\n /**\n * The workstation ID (WSID) of the client, default os.hostname().\n * Used for identifying a specific client in profiling, logging or\n * tracing client activity in SQLServer.\n *\n * The value is reported by the TSQL function HOST_NAME().\n */\n workstationId?: string | undefined;\n}\n\n/**\n * @private\n */\nconst CLEANUP_TYPE = {\n NORMAL: 0,\n REDIRECT: 1,\n RETRY: 2\n};\n\ninterface RoutingData {\n server: string;\n port: number;\n}\n\n/**\n * A [[Connection]] instance represents a single connection to a database server.\n *\n * ```js\n * var Connection = require('tedious').Connection;\n * var config = {\n * \"authentication\": {\n * ...,\n * \"options\": {...}\n * },\n * \"options\": {...}\n * };\n * var connection = new Connection(config);\n * ```\n *\n * Only one request at a time may be executed on a connection. Once a [[Request]]\n * has been initiated (with [[Connection.callProcedure]], [[Connection.execSql]],\n * or [[Connection.execSqlBatch]]), another should not be initiated until the\n * [[Request]]'s completion callback is called.\n */\nclass Connection extends EventEmitter {\n /**\n * @private\n */\n declare fedAuthRequired: boolean;\n /**\n * @private\n */\n declare config: InternalConnectionConfig;\n /**\n * @private\n */\n declare secureContextOptions: SecureContextOptions;\n /**\n * @private\n */\n declare inTransaction: boolean;\n /**\n * @private\n */\n declare transactionDescriptors: Buffer[];\n /**\n * @private\n */\n declare transactionDepth: number;\n /**\n * @private\n */\n declare isSqlBatch: boolean;\n /**\n * @private\n */\n declare curTransientRetryCount: number;\n /**\n * @private\n */\n declare transientErrorLookup: TransientErrorLookup;\n /**\n * @private\n */\n declare closed: boolean;\n /**\n * @private\n */\n declare loginError: undefined | AggregateError | ConnectionError;\n /**\n * @private\n */\n declare debug: Debug;\n /**\n * @private\n */\n declare ntlmpacket: undefined | any;\n /**\n * @private\n */\n declare ntlmpacketBuffer: undefined | Buffer;\n\n /**\n * @private\n */\n declare STATE: {\n INITIALIZED: State;\n CONNECTING: State;\n SENT_PRELOGIN: State;\n REROUTING: State;\n TRANSIENT_FAILURE_RETRY: State;\n SENT_TLSSSLNEGOTIATION: State;\n SENT_LOGIN7_WITH_STANDARD_LOGIN: State;\n SENT_LOGIN7_WITH_NTLM: State;\n SENT_LOGIN7_WITH_FEDAUTH: State;\n LOGGED_IN_SENDING_INITIAL_SQL: State;\n LOGGED_IN: State;\n SENT_CLIENT_REQUEST: State;\n SENT_ATTENTION: State;\n FINAL: State;\n };\n\n /**\n * @private\n */\n declare routingData: undefined | RoutingData;\n\n /**\n * @private\n */\n declare messageIo: MessageIO;\n /**\n * @private\n */\n declare state: State;\n /**\n * @private\n */\n declare resetConnectionOnNextRequest: undefined | boolean;\n\n /**\n * @private\n */\n declare request: undefined | Request | BulkLoad;\n /**\n * @private\n */\n declare procReturnStatusValue: undefined | any;\n /**\n * @private\n */\n declare socket: undefined | net.Socket;\n /**\n * @private\n */\n declare messageBuffer: Buffer;\n\n /**\n * @private\n */\n declare connectTimer: undefined | NodeJS.Timeout;\n /**\n * @private\n */\n declare cancelTimer: undefined | NodeJS.Timeout;\n /**\n * @private\n */\n declare requestTimer: undefined | NodeJS.Timeout;\n /**\n * @private\n */\n declare retryTimer: undefined | NodeJS.Timeout;\n\n /**\n * @private\n */\n _cancelAfterRequestSent: () => void;\n\n /**\n * @private\n */\n declare databaseCollation: Collation | undefined;\n\n /**\n * Note: be aware of the different options field:\n * 1. config.authentication.options\n * 2. config.options\n *\n * ```js\n * const { Connection } = require('tedious');\n *\n * const config = {\n * \"authentication\": {\n * ...,\n * \"options\": {...}\n * },\n * \"options\": {...}\n * };\n *\n * const connection = new Connection(config);\n * ```\n *\n * @param config\n */\n constructor(config: ConnectionConfiguration) {\n super();\n\n if (typeof config !== 'object' || config === null) {\n throw new TypeError('The \"config\" argument is required and must be of type Object.');\n }\n\n if (typeof config.server !== 'string') {\n throw new TypeError('The \"config.server\" property is required and must be of type string.');\n }\n\n this.fedAuthRequired = false;\n\n let authentication: ConnectionAuthentication;\n if (config.authentication !== undefined) {\n if (typeof config.authentication !== 'object' || config.authentication === null) {\n throw new TypeError('The \"config.authentication\" property must be of type Object.');\n }\n\n const type = config.authentication.type;\n const options = config.authentication.options === undefined ? {} : config.authentication.options;\n\n if (typeof type !== 'string') {\n throw new TypeError('The \"config.authentication.type\" property must be of type string.');\n }\n\n if (type !== 'default' && type !== 'ntlm' && type !== 'token-credential' && type !== 'azure-active-directory-password' && type !== 'azure-active-directory-access-token' && type !== 'azure-active-directory-msi-vm' && type !== 'azure-active-directory-msi-app-service' && type !== 'azure-active-directory-service-principal-secret' && type !== 'azure-active-directory-default') {\n throw new TypeError('The \"type\" property must one of \"default\", \"ntlm\", \"token-credential\", \"azure-active-directory-password\", \"azure-active-directory-access-token\", \"azure-active-directory-default\", \"azure-active-directory-msi-vm\" or \"azure-active-directory-msi-app-service\" or \"azure-active-directory-service-principal-secret\".');\n }\n\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('The \"config.authentication.options\" property must be of type object.');\n }\n\n if (type === 'ntlm') {\n if (typeof options.domain !== 'string') {\n throw new TypeError('The \"config.authentication.options.domain\" property must be of type string.');\n }\n\n if (options.userName !== undefined && typeof options.userName !== 'string') {\n throw new TypeError('The \"config.authentication.options.userName\" property must be of type string.');\n }\n\n if (options.password !== undefined && typeof options.password !== 'string') {\n throw new TypeError('The \"config.authentication.options.password\" property must be of type string.');\n }\n\n authentication = {\n type: 'ntlm',\n options: {\n userName: options.userName,\n password: options.password,\n domain: options.domain && options.domain.toUpperCase()\n }\n };\n } else if (type === 'token-credential') {\n if (!isTokenCredential(options.credential)) {\n throw new TypeError('The \"config.authentication.options.credential\" property must be an instance of the token credential class.');\n }\n\n authentication = {\n type: 'token-credential',\n options: {\n credential: options.credential\n }\n };\n } else if (type === 'azure-active-directory-password') {\n if (typeof options.clientId !== 'string') {\n throw new TypeError('The \"config.authentication.options.clientId\" property must be of type string.');\n }\n\n if (options.userName !== undefined && typeof options.userName !== 'string') {\n throw new TypeError('The \"config.authentication.options.userName\" property must be of type string.');\n }\n\n if (options.password !== undefined && typeof options.password !== 'string') {\n throw new TypeError('The \"config.authentication.options.password\" property must be of type string.');\n }\n\n if (options.tenantId !== undefined && typeof options.tenantId !== 'string') {\n throw new TypeError('The \"config.authentication.options.tenantId\" property must be of type string.');\n }\n\n authentication = {\n type: 'azure-active-directory-password',\n options: {\n userName: options.userName,\n password: options.password,\n tenantId: options.tenantId,\n clientId: options.clientId\n }\n };\n } else if (type === 'azure-active-directory-access-token') {\n if (typeof options.token !== 'string') {\n throw new TypeError('The \"config.authentication.options.token\" property must be of type string.');\n }\n\n authentication = {\n type: 'azure-active-directory-access-token',\n options: {\n token: options.token\n }\n };\n } else if (type === 'azure-active-directory-msi-vm') {\n if (options.clientId !== undefined && typeof options.clientId !== 'string') {\n throw new TypeError('The \"config.authentication.options.clientId\" property must be of type string.');\n }\n\n authentication = {\n type: 'azure-active-directory-msi-vm',\n options: {\n clientId: options.clientId\n }\n };\n } else if (type === 'azure-active-directory-default') {\n if (options.clientId !== undefined && typeof options.clientId !== 'string') {\n throw new TypeError('The \"config.authentication.options.clientId\" property must be of type string.');\n }\n authentication = {\n type: 'azure-active-directory-default',\n options: {\n clientId: options.clientId\n }\n };\n } else if (type === 'azure-active-directory-msi-app-service') {\n if (options.clientId !== undefined && typeof options.clientId !== 'string') {\n throw new TypeError('The \"config.authentication.options.clientId\" property must be of type string.');\n }\n\n authentication = {\n type: 'azure-active-directory-msi-app-service',\n options: {\n clientId: options.clientId\n }\n };\n } else if (type === 'azure-active-directory-service-principal-secret') {\n if (typeof options.clientId !== 'string') {\n throw new TypeError('The \"config.authentication.options.clientId\" property must be of type string.');\n }\n\n if (typeof options.clientSecret !== 'string') {\n throw new TypeError('The \"config.authentication.options.clientSecret\" property must be of type string.');\n }\n\n if (typeof options.tenantId !== 'string') {\n throw new TypeError('The \"config.authentication.options.tenantId\" property must be of type string.');\n }\n\n authentication = {\n type: 'azure-active-directory-service-principal-secret',\n options: {\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n tenantId: options.tenantId\n }\n };\n } else {\n if (options.userName !== undefined && typeof options.userName !== 'string') {\n throw new TypeError('The \"config.authentication.options.userName\" property must be of type string.');\n }\n\n if (options.password !== undefined && typeof options.password !== 'string') {\n throw new TypeError('The \"config.authentication.options.password\" property must be of type string.');\n }\n\n authentication = {\n type: 'default',\n options: {\n userName: options.userName,\n password: options.password\n }\n };\n }\n } else {\n authentication = {\n type: 'default',\n options: {\n userName: undefined,\n password: undefined\n }\n };\n }\n\n this.config = {\n server: config.server,\n authentication: authentication,\n options: {\n abortTransactionOnError: false,\n appName: undefined,\n camelCaseColumns: false,\n cancelTimeout: DEFAULT_CANCEL_TIMEOUT,\n columnEncryptionKeyCacheTTL: 2 * 60 * 60 * 1000, // Units: milliseconds\n columnEncryptionSetting: false,\n columnNameReplacer: undefined,\n connectionRetryInterval: DEFAULT_CONNECT_RETRY_INTERVAL,\n connectTimeout: DEFAULT_CONNECT_TIMEOUT,\n connector: undefined,\n connectionIsolationLevel: ISOLATION_LEVEL.READ_COMMITTED,\n cryptoCredentialsDetails: {},\n database: undefined,\n datefirst: DEFAULT_DATEFIRST,\n dateFormat: DEFAULT_DATEFORMAT,\n debug: {\n data: false,\n packet: false,\n payload: false,\n token: false\n },\n enableAnsiNull: true,\n enableAnsiNullDefault: true,\n enableAnsiPadding: true,\n enableAnsiWarnings: true,\n enableArithAbort: true,\n enableConcatNullYieldsNull: true,\n enableCursorCloseOnCommit: null,\n enableImplicitTransactions: false,\n enableNumericRoundabort: false,\n enableQuotedIdentifier: true,\n encrypt: true,\n fallbackToDefaultDb: false,\n encryptionKeyStoreProviders: undefined,\n instanceName: undefined,\n isolationLevel: ISOLATION_LEVEL.READ_COMMITTED,\n language: DEFAULT_LANGUAGE,\n localAddress: undefined,\n maxRetriesOnTransientErrors: 3,\n multiSubnetFailover: false,\n packetSize: DEFAULT_PACKET_SIZE,\n port: DEFAULT_PORT,\n readOnlyIntent: false,\n requestTimeout: DEFAULT_CLIENT_REQUEST_TIMEOUT,\n rowCollectionOnDone: false,\n rowCollectionOnRequestCompletion: false,\n serverName: undefined,\n serverSupportsColumnEncryption: false,\n tdsVersion: DEFAULT_TDS_VERSION,\n textsize: DEFAULT_TEXTSIZE,\n trustedServerNameAE: undefined,\n trustServerCertificate: false,\n useColumnNames: false,\n useUTC: true,\n workstationId: undefined,\n lowerCaseGuids: false\n }\n };\n\n if (config.options) {\n if (config.options.port && config.options.instanceName) {\n throw new Error('Port and instanceName are mu