diff --git a/eslint.config.js b/eslint.config.js index 4618b64f..041e8fb3 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -35,6 +35,10 @@ module.exports = [ "no-unused-vars": "error", "no-undef": "error", + // ES6+ modernization - GO TIME! 🚀 + "prefer-const": "error", // Use const for variables never reassigned + "no-var": "error", // Disallow var, use let/const instead + // Spacing rules (disabled for initial setup - TODO: Fix in separate PR) "arrow-spacing": "off", "space-before-blocks": "off", diff --git a/lib/documents.js b/lib/documents.js index be280c32..ebe1ec2b 100644 --- a/lib/documents.js +++ b/lib/documents.js @@ -3,12 +3,12 @@ */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); -var qb = require('./query-builder.js').lib; -var pathModule = require('path'); -var fs = require('fs'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); +const qb = require('./query-builder.js').lib; +const pathModule = require('path'); +const fs = require('fs'); const stream = require('stream'); const bldrbase = require('./plan-builder-base.js'); const duplexify = require('duplexify'); @@ -16,7 +16,7 @@ const duplexify = require('duplexify'); /** @ignore */ function addDocumentUri(documents, document) { if (document != null) { - var uri = document.uri; + const uri = document.uri; if ((typeof uri === 'string' || uri instanceof String) && uri.length > 0) { documents.push(uri); } @@ -35,36 +35,36 @@ function getDocumentUris(documents) { function compareDocuments(firstDoc, secondDoc) { const hasFirstDoc = (firstDoc !== null); const hasSecondDoc = (secondDoc !== null); - if (!hasFirstDoc && !hasSecondDoc) return 0; - if (!hasFirstDoc && hasSecondDoc) return -1; - if (hasFirstDoc && !hasSecondDoc) return 1; + if (!hasFirstDoc && !hasSecondDoc) {return 0;} + if (!hasFirstDoc && hasSecondDoc) {return -1;} + if (hasFirstDoc && !hasSecondDoc) {return 1;} const firstUri = firstDoc.uri; const secondUri = secondDoc.uri; const hasFirstUri = ((typeof firstUri === 'string' || firstUri instanceof String) && firstUri.length > 0); const hasSecondUri = ((typeof secondUri === 'string' || secondUri instanceof String) && secondUri.length > 0); - if (!hasFirstUri && !hasSecondUri) return 0; - if (!hasFirstUri && hasSecondUri) return -1; - if (hasFirstUri && !hasSecondUri) return 1; - if (firstUri < secondUri) return -1; - if (firstUri > secondUri) return 1; + if (!hasFirstUri && !hasSecondUri) {return 0;} + if (!hasFirstUri && hasSecondUri) {return -1;} + if (hasFirstUri && !hasSecondUri) {return 1;} + if (firstUri < secondUri) {return -1;} + if (firstUri > secondUri) {return 1;} return 0; } /** @ignore */ function uriErrorTransform(message) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var uri = operation.uri; + const uri = operation.uri; return (uri == null) ? message : (message+' (on '+uri+')'); } /** @ignore */ function uriListErrorTransform(message) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var uris = operation.uris; + const uris = operation.uris; return ((!Array.isArray(uris)) || uris.length === 0) ? message : (message+' (on '+uris.join(', ')+')'); } @@ -89,15 +89,15 @@ function Documents(client) { /** @ignore */ function probeOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var statusCode = operation.responseStatusCode; - var exists = (statusCode === 200) ? true : false; + const statusCode = operation.responseStatusCode; + const exists = (statusCode === 200) ? true : false; if (operation.contentOnly === true) { return exists; } - var output = exists ? operation.responseHeaders : {}; + const output = exists ? operation.responseHeaders : {}; output.uri = operation.uri; output.exists = exists; @@ -106,9 +106,9 @@ function probeOutputTransform(/*headers, data*/) { function protectOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var output = { + const output = { uri: operation.uri, temporalCollection: operation.temporalCollection, level: operation.level @@ -119,9 +119,9 @@ function protectOutputTransform(/*headers, data*/) { function wipeOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var output = { + const output = { uri: operation.uri, temporalCollection: operation.temporalCollection, wiped: true @@ -133,7 +133,7 @@ function wipeOutputTransform(/*headers, data*/) { function advanceLsqtOutputTransform(headers) { /*jshint validthis:true */ - var output = { + const output = { lsqt: headers.lsqt }; @@ -227,11 +227,11 @@ function probeDocumentsImpl(contentOnly, args) { throw new Error('must supply uri for document check()'); } - var params = (args.length === 1 && typeof args[0] !== 'string' && !(args[0] instanceof String)) ? args[0] : null; + const params = (args.length === 1 && typeof args[0] !== 'string' && !(args[0] instanceof String)) ? args[0] : null; - var uri = null; - var txid = null; - var path = '/v1/documents?format=json'; + let uri = null; + let txid = null; + let path = '/v1/documents?format=json'; // params as list if (params === null) { uri = args[0]; @@ -257,7 +257,7 @@ function probeDocumentsImpl(contentOnly, args) { const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'HEAD'); mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'probe document', this.client, requestOptions, 'empty', 'empty' ); operation.uri = uri; @@ -296,19 +296,19 @@ function probeDocumentsImpl(contentOnly, args) { */ Documents.prototype.protect = function protectDocument() { /*jshint validthis:true */ - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; - var uri = null; - var tempColl = null; - var duration = null; - var expireTime = null; - var level = 'noDelete'; - var archivePath = null; + let uri = null; + let tempColl = null; + let duration = null; + let expireTime = null; + let level = 'noDelete'; + let archivePath = null; // Params as single object if (argLen === 1) { - var obj = args[0]; + const obj = args[0]; if (obj.uri === void 0) { throw new Error('must specify uri'); } else { @@ -346,7 +346,7 @@ Documents.prototype.protect = function protectDocument() { } else { expireTime = args[2]; } - var levels = ['noWipe', 'noDelete', 'noUpdate']; + const levels = ['noWipe', 'noDelete', 'noUpdate']; if (levels.indexOf(args[3]) !== -1) { level = args[3]; } else { @@ -365,7 +365,7 @@ Documents.prototype.protect = function protectDocument() { } } - var path = '/v1/documents/protection?uri=' + encodeURIComponent(uri); + let path = '/v1/documents/protection?uri=' + encodeURIComponent(uri); path += '&temporal-collection=' + encodeURIComponent(tempColl); if (duration !== null) { path += '&duration=' + encodeURIComponent(duration); @@ -379,7 +379,7 @@ Documents.prototype.protect = function protectDocument() { const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'POST'); - var operation = new Operation( + const operation = new Operation( 'protect document', this.client, requestOptions, 'empty', 'empty' ); operation.uri = uri; @@ -411,15 +411,15 @@ Documents.prototype.protect = function protectDocument() { */ Documents.prototype.wipe = function wipeDocument() { /*jshint validthis:true */ - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; - var uri = null; - var tempColl = null; + let uri = null; + let tempColl = null; // Params as single object if (argLen === 1) { - var obj = args[0]; + const obj = args[0]; if (obj.uri === void 0) { throw new Error('must specify uri'); } else { @@ -440,13 +440,13 @@ Documents.prototype.wipe = function wipeDocument() { tempColl = args[1]; } - var path = '/v1/documents?uri=' + encodeURIComponent(uri); + let path = '/v1/documents?uri=' + encodeURIComponent(uri); path += '&temporal-collection=' + encodeURIComponent(tempColl); path += '&result=wiped'; const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'DELETE'); - var operation = new Operation( + const operation = new Operation( 'wipe document', this.client, requestOptions, 'empty', 'empty' ); operation.uri = uri; @@ -471,10 +471,10 @@ Documents.prototype.wipe = function wipeDocument() { */ Documents.prototype.advanceLsqt = function temporalAdvanceLsqt() { /*jshint validthis:true */ - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); - var tempColl = null; - var lag = null; + let tempColl = null; + let lag = null; // Positional case if (typeof args[0] === 'string' || args[0] instanceof String) { @@ -489,7 +489,7 @@ Documents.prototype.advanceLsqt = function temporalAdvanceLsqt() { } // Object case else { - var obj = args[0]; + const obj = args[0]; if (obj.temporalCollection === void 0) { throw new Error('must specify temporalCollection'); } else { @@ -504,7 +504,7 @@ Documents.prototype.advanceLsqt = function temporalAdvanceLsqt() { } } - var path = '/v1/temporal/collections/' + encodeURIComponent(tempColl); + let path = '/v1/temporal/collections/' + encodeURIComponent(tempColl); path += '?result=advance-lsqt'; if (lag !== null) { path += '&lag=' + encodeURIComponent(lag); @@ -512,7 +512,7 @@ Documents.prototype.advanceLsqt = function temporalAdvanceLsqt() { const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'POST'); - var operation = new Operation( + const operation = new Operation( 'advance LSQT', this.client, requestOptions, 'empty', 'empty' ); // operation.temporalCollection = tempColl; @@ -531,9 +531,9 @@ function readStatusValidator(statusCode) { /** @ignore */ function singleReadOutputTransform(headers, data) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var hasData = (data != null); + const hasData = (data != null); if (hasData && (data.errorResponse != null) && data.errorResponse.statusCode === 404 @@ -541,15 +541,15 @@ function singleReadOutputTransform(headers, data) { return []; } - var content = hasData ? data : null; + const content = hasData ? data : null; if (operation.contentOnly === true) { return [content]; } - var categories = operation.categories; + const categories = operation.categories; - var document = (categories.length === 1 && categories[0] === 'content') ? + const document = (categories.length === 1 && categories[0] === 'content') ? {content: content} : collectMetadata(content); if(operation.uris){ @@ -557,21 +557,21 @@ function singleReadOutputTransform(headers, data) { } document.category = categories; - var format = headers.format; + const format = headers.format; if (typeof format === 'string' || format instanceof String) { document.format = format; if (format !== 'json') { - var contentLength = headers.contentLength; + const contentLength = headers.contentLength; if (contentLength != null) { document.contentLength = contentLength; } } } - var headerList = ['contentType', 'versionId']; - var headerKey = null; - var headerValue = null; - var i = 0; + const headerList = ['contentType', 'versionId']; + let headerKey = null; + let headerValue = null; + let i = 0; for (i = 0; i < headerList.length; i++) { headerKey = headerList[i]; headerValue = headers[headerKey]; @@ -625,15 +625,15 @@ function readDocumentsImpl(contentOnly, args) { throw new Error('must specify at least one document to read'); } - var uris = null; - var categories = null; - var txid = null; - var transform = null; - var contentType = null; - var range = null; - var timestamp = null; + let uris = null; + let categories = null; + let txid = null; + let transform = null; + let contentType = null; + let range = null; + let timestamp = null; - var arg = args[0]; + const arg = args[0]; if (Array.isArray(arg)) { uris = arg; } else if (typeof arg === 'string' || arg instanceof String) { @@ -661,7 +661,7 @@ function readDocumentsImpl(contentOnly, args) { } if (categories != null) { - var i = 0; + let i = 0; for (i = 0; i < categories.length; i++) { if(categories[i] === 'rawContent'){ if(categories.length>1) { @@ -675,7 +675,7 @@ function readDocumentsImpl(contentOnly, args) { } } - var path = '/v1/documents?format=json&uri='+ + let path = '/v1/documents?format=json&uri='+ uris.map(encodeURIComponent).join('&uri='); path += '&category=' + categories.join('&category='); if (txid != null) { @@ -691,7 +691,7 @@ function readDocumentsImpl(contentOnly, args) { } } - var isSinglePayload = ( + const isSinglePayload = ( uris.length === 1 && ( (categories.length === 1 && categories[0] === 'content') || categories.indexOf('content') === -1 @@ -703,7 +703,7 @@ function readDocumentsImpl(contentOnly, args) { Accept: 'multipart/mixed; boundary='+mlutil.multipartBoundary }; } else { - var hasContentType = false; + let hasContentType = false; if (contentType != null) { if (typeof contentType === 'string' || contentType instanceof String) { hasContentType = true; @@ -716,7 +716,7 @@ function readDocumentsImpl(contentOnly, args) { if (!Array.isArray(range)) { throw new Error('byte range parameter for reading binary document is not an array: '+range); } - var bytes = null; + let bytes = null; switch (range.length) { case 0: throw new Error('no start length for byte range parameter for reading binary document'); @@ -762,7 +762,7 @@ function readDocumentsImpl(contentOnly, args) { } mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'read documents', this.client, requestOptions, 'empty', (isSinglePayload ? 'single' : 'multipart') ); @@ -815,8 +815,8 @@ Documents.prototype.createWriteStream = function createWriteStream(document) { throw new Error('must write to stream to supply document content'); } - var categories = document.categories; - var hasCategories = Array.isArray(categories) && categories.length > 0; + let categories = document.categories; + const hasCategories = Array.isArray(categories) && categories.length > 0; if (!hasCategories && (typeof categories === 'string' || categories instanceof String)) { categories = [categories]; } @@ -830,16 +830,16 @@ Documents.prototype.createWriteStream = function createWriteStream(document) { /** @ignore */ function writeStreamImpl(document, categories) { /*jshint validthis:true */ - var endpoint = '/v1/documents'; + let endpoint = '/v1/documents'; - var txid = getTxid(document); + const txid = getTxid(document); - var writeParams = addWriteParams(document, categories, txid); + const writeParams = addWriteParams(document, categories, txid); if (writeParams.length > 0) { endpoint += writeParams; } - var multipartBoundary = mlutil.multipartBoundary; + const multipartBoundary = mlutil.multipartBoundary; const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), endpoint, 'POST'); requestOptions.headers = { 'Content-Type': 'multipart/mixed; boundary='+multipartBoundary, @@ -847,14 +847,14 @@ function writeStreamImpl(document, categories) { }; mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'write document stream', this.client, requestOptions, 'chunkedMultipart', 'single' ); operation.isReplayable = false; operation.uri = document.uri; // TODO: treat as chunked single document if no properties - var requestPartList = []; + const requestPartList = []; addDocumentParts(operation, requestPartList, document, true); operation.requestDocument = requestPartList; @@ -867,14 +867,14 @@ function writeStreamImpl(document, categories) { /** @ignore */ function singleWriteOutputTransform(headers, data) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var uri = operation.uri; + let uri = operation.uri; if (uri == null) { - var location = headers.location; + const location = headers.location; if (location != null) { - var startsWith = '/v1/documents?uri='; + const startsWith = '/v1/documents?uri='; if (location.length > startsWith.length && location.substr(0, startsWith.length) === startsWith) { uri = location.substr(startsWith.length); @@ -886,21 +886,21 @@ function singleWriteOutputTransform(headers, data) { return [uri]; } - var document = {uri: uri}; + const document = {uri: uri}; - var categories = operation.categories; + const categories = operation.categories; if (categories == null) { document.categories = categories; } - var contentType = (data == null) ? null : data['mime-type']; + const contentType = (data == null) ? null : data['mime-type']; if (contentType == null) { document.contentType = contentType; } - var wrapper = {documents: [document]}; + const wrapper = {documents: [document]}; - var systemTime = headers.systemTime; + const systemTime = headers.systemTime; if (systemTime != null) { wrapper.systemTime = systemTime; } @@ -911,7 +911,7 @@ function singleWriteOutputTransform(headers, data) { function writeListOutputTransform(headers, data) { // var operation = this; - var systemTime = headers.systemTime; + const systemTime = headers.systemTime; if (systemTime == null) { return data; } @@ -968,10 +968,10 @@ function writeDocumentsImpl(contentOnly, args) { throw new Error('must provide uris for document write()'); } - var arg = args[0]; + const arg = args[0]; - var documents = arg.documents; - var params = (documents == null) ? null : arg; + let documents = arg.documents; + const params = (documents == null) ? null : arg; if (params !== null) { if (!Array.isArray(documents)) { documents = [documents]; @@ -982,24 +982,24 @@ function writeDocumentsImpl(contentOnly, args) { documents = args; } - var isSingleDoc = (documents.length === 1); + const isSingleDoc = (documents.length === 1); - var document = isSingleDoc ? documents[0] : null; - var hasDocument = (document != null); - var hasContent = hasDocument && (document.content != null); + const document = isSingleDoc ? documents[0] : null; + const hasDocument = (document != null); + const hasContent = hasDocument && (document.content != null); - var requestParams = + const requestParams = (params !== null) ? params : (hasDocument) ? document : null; - var categories = (requestParams == null) ? null : requestParams.categories; + let categories = (requestParams == null) ? null : requestParams.categories; if (typeof categories === 'string' || categories instanceof String) { categories = [categories]; } if (categories != null) { - for (var i = 0; i < categories.length; i++) { + for (let i = 0; i < categories.length; i++) { categories[i] = categories[i] === 'metadataValues' ? 'metadata-values' : categories[i]; } } @@ -1017,19 +1017,19 @@ function writeDocumentsImpl(contentOnly, args) { /** @ignore */ function writeMetadata(document, categories) { /*jshint validthis:true */ - var uri = document.uri; + const uri = document.uri; - var endpoint = '/v1/documents?uri='+encodeURIComponent(uri); + let endpoint = '/v1/documents?uri='+encodeURIComponent(uri); if (!Array.isArray(categories)) { categories = []; } - var hasCategories = (categories.length > 0); + let hasCategories = (categories.length > 0); if (!hasCategories) { - var categoryCheck = ['collections', 'permissions', 'quality', 'properties', 'metadataValues']; - var category = null; - var i = 0; + const categoryCheck = ['collections', 'permissions', 'quality', 'properties', 'metadataValues']; + let category = null; + let i = 0; for (i = 0; i < categoryCheck.length; i++) { category = categoryCheck[i]; if (document[category] != null) { @@ -1046,12 +1046,12 @@ function writeMetadata(document, categories) { endpoint += '&category='+categories.join('&category='); } - var txid = mlutil.convertTransaction(document.txid); + const txid = mlutil.convertTransaction(document.txid); if (txid != null) { endpoint += '&txid='+mlutil.getTxidParam(txid); } - var requestHeaders = { + const requestHeaders = { 'Accept': 'application/json', 'Content-Type': 'application/json' }; @@ -1060,7 +1060,7 @@ function writeMetadata(document, categories) { requestOptions.headers = requestHeaders; mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'write single metadata', this.client, requestOptions, 'single', 'empty' ); operation.uri = uri; @@ -1075,32 +1075,32 @@ function writeMetadata(document, categories) { /** @ignore */ function writeContent(contentOnly, document, requestParams, categories, requestType) { /*jshint validthis:true */ - var content = document.content; - var hasContent = (content != null); + const content = document.content; + const hasContent = (content != null); - var endpoint = '/v1/documents'; + let endpoint = '/v1/documents'; - var sep = '?'; + let sep = '?'; - var txid = getTxid(requestParams); + const txid = getTxid(requestParams); - var writeParams = addWriteParams(requestParams, categories, txid); + const writeParams = addWriteParams(requestParams, categories, txid); if (writeParams.length > 0) { endpoint += writeParams; sep = '&'; } - var uri = document.uri; - var hasUri = (uri != null); + const uri = document.uri; + const hasUri = (uri != null); if (hasUri) { endpoint += sep+'uri='+encodeURIComponent(uri); if (sep === '?') { sep = '&'; } } - var i = 0; + let i = 0; - var collections = document.collections; + const collections = document.collections; if (collections != null) { if (Array.isArray(collections)) { for (i=0; i < collections.length; i++) { @@ -1113,12 +1113,12 @@ function writeContent(contentOnly, document, requestParams, categories, requestT } } - var permissions = document.permissions; + const permissions = document.permissions; if (permissions != null) { - var permission = null; - var roleName = null; - var capabilities = null; - var j = 0; + let permission = null; + let roleName = null; + let capabilities = null; + let j = 0; if (Array.isArray(permissions)) { for (i=0; i < permissions.length; i++) { permission = permissions[i]; @@ -1149,28 +1149,28 @@ function writeContent(contentOnly, document, requestParams, categories, requestT } } - var quality = document.quality; + const quality = document.quality; if (quality != null) { endpoint += sep+'quality='+quality; if (sep === '?') { sep = '&'; } } - var metadataValues = document.metadataValues; - for (var key in metadataValues) { + const metadataValues = document.metadataValues; + for (const key in metadataValues) { endpoint += sep+'value:'+key+'='+encodeURIComponent(metadataValues[key]); } - var temporalDocument = document.temporalDocument; + const temporalDocument = document.temporalDocument; if (temporalDocument != null) { endpoint += sep+'temporal-document='+temporalDocument; if (sep === '?') { sep = '&'; } } - var requestHeaders = { + const requestHeaders = { 'Accept': 'application/json' }; - var writeConfig = addWriteConfig(document, hasUri, content, requestHeaders, sep); + const writeConfig = addWriteConfig(document, hasUri, content, requestHeaders, sep); if (writeConfig.length > 0) { endpoint += writeConfig; if (sep === '?') { sep = '&'; } @@ -1179,7 +1179,7 @@ function writeContent(contentOnly, document, requestParams, categories, requestT const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), endpoint, hasUri ? 'PUT' : 'POST'); requestOptions.headers = requestHeaders; mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'write single document', this.client, requestOptions, requestType, 'empty' ); if (hasUri) { @@ -1205,18 +1205,18 @@ function writeDocumentList(contentOnly, documents, requestParams, categories) { documents = documents.sort(compareDocuments); } - var endpoint = '/v1/documents'; + let endpoint = '/v1/documents'; - var txid = getTxid(requestParams); + const txid = getTxid(requestParams); - var writeParams = addWriteParams(requestParams, categories, txid); + const writeParams = addWriteParams(requestParams, categories, txid); if (writeParams.length > 0) { endpoint += writeParams; } - var multipartBoundary = mlutil.multipartBoundary; + const multipartBoundary = mlutil.multipartBoundary; - var requestHeaders = { + const requestHeaders = { 'Accept': 'application/json', 'Content-Type': 'multipart/mixed; boundary='+multipartBoundary }; @@ -1225,7 +1225,7 @@ function writeDocumentList(contentOnly, documents, requestParams, categories) { requestOptions.headers = requestHeaders; mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'write document list', this.client, requestOptions, 'multipart', 'single' ); operation.uris = getDocumentUris(documents); @@ -1235,8 +1235,8 @@ function writeDocumentList(contentOnly, documents, requestParams, categories) { operation.multipartBoundary = multipartBoundary; - var requestPartList = []; - for (var i=0; i < documents.length; i++) { + const requestPartList = []; + for (let i=0; i < documents.length; i++) { addDocumentParts(operation, requestPartList, documents[i], false); } operation.requestPartList = requestPartList; @@ -1256,9 +1256,9 @@ function getTxid(requestParams) { } /** @ignore */ function addWriteParams(requestParams, categories, txidRaw) { - var writeParams = ''; - var txid = mlutil.convertTransaction(txidRaw); - var sep = '?'; + let writeParams = ''; + const txid = mlutil.convertTransaction(txidRaw); + let sep = '?'; if (requestParams != null) { if (Array.isArray(categories) && categories.length > 0) { writeParams += sep+'category='+categories.join('&category='); @@ -1268,21 +1268,21 @@ function addWriteParams(requestParams, categories, txidRaw) { writeParams += sep+'txid='+mlutil.getTxidParam(txid); if (sep !== '&') { sep = '&'; } } - var transform = mlutil.endpointTransform(requestParams.transform); + const transform = mlutil.endpointTransform(requestParams.transform); if (transform != null) { writeParams += sep+transform; if (sep !== '&') { sep = '&'; } } - var forestName = requestParams.forestName; + const forestName = requestParams.forestName; if (forestName != null) { writeParams += sep+'forest-name='+encodeURIComponent(forestName); if (sep !== '&') { sep = '&'; } } - var temporalCollection = requestParams.temporalCollection; + const temporalCollection = requestParams.temporalCollection; if (temporalCollection != null) { writeParams += sep+'temporal-collection='+encodeURIComponent(temporalCollection); if (sep !== '&') { sep = '&'; } - var systemTime = requestParams.systemTime; + const systemTime = requestParams.systemTime; if (typeof systemTime === 'string' || systemTime instanceof String) { writeParams += '&system-time='+encodeURIComponent(systemTime); } else if (Object.prototype.toString.call(systemTime) === '[object Date]') { @@ -1295,16 +1295,16 @@ function addWriteParams(requestParams, categories, txidRaw) { } /** @ignore */ function addWriteConfig(document, hasUri, content, headers, sep) { - var writeConfig = ''; + let writeConfig = ''; - var isBody = (sep !== '; '); + const isBody = (sep !== '; '); if (!hasUri) { - var extension = document.extension; + const extension = document.extension; if (extension != null) { writeConfig += sep+'extension='+extension; if (isBody && sep === '?') { sep = '&'; } - var directory = document.directory; + const directory = document.directory; if (directory != null) { writeConfig += sep+'directory='+ (isBody ? encodeURIComponent(directory) : directory); @@ -1312,7 +1312,7 @@ function addWriteConfig(document, hasUri, content, headers, sep) { } } - var versionId = document.versionId; + const versionId = document.versionId; if (versionId != null) { if (isBody) { headers['If-Match'] = versionId; @@ -1321,10 +1321,10 @@ function addWriteConfig(document, hasUri, content, headers, sep) { } } - var contentType = document.contentType; - var hasContentType = (contentType != null); - var format = document.format; - var hasFormat = (format != null); + let contentType = document.contentType; + let hasContentType = (contentType != null); + let format = document.format; + let hasFormat = (format != null); if (hasContentType) { if (!hasFormat) { @@ -1399,10 +1399,10 @@ function addWriteConfig(document, hasUri, content, headers, sep) { } /** @ignore */ function addDocumentParts(operation, partList, document, isContentOptional) { - var uri = document.uri; - var hasUri = (uri != null); + const uri = document.uri; + const hasUri = (uri != null); - var disposition = ''; + let disposition = ''; if (hasUri) { disposition = 'attachment; filename="'+uri+'"'; if (document.temporalDocument != null) { @@ -1412,7 +1412,7 @@ function addDocumentParts(operation, partList, document, isContentOptional) { disposition = 'inline'; } - var metadata = collectMetadata(document); + const metadata = collectMetadata(document); if (metadata != null) { partList.push({ headers:{ @@ -1423,13 +1423,13 @@ function addDocumentParts(operation, partList, document, isContentOptional) { }); } - var content = document.content; - var hasContent = (content != null); + const content = document.content; + const hasContent = (content != null); if (hasContent || isContentOptional) { - var headers = {}; - var part = {headers: headers}; + const headers = {}; + const part = {headers: headers}; - var writeConfig = addWriteConfig(document, hasUri, content, headers, '; '); + const writeConfig = addWriteConfig(document, hasUri, content, headers, '; '); if (writeConfig.length > 0) { disposition += writeConfig; } @@ -1446,11 +1446,11 @@ function addDocumentParts(operation, partList, document, isContentOptional) { /** @ignore */ function collectMetadata(document) { - var metadata = null; + let metadata = null; // TODO: create array wrapper for collections, capabilities - var metadataCategories = ['collections', 'permissions', 'quality', 'properties', 'metadataValues']; - for (var i = 0; i < metadataCategories.length; i++) { - var category = metadataCategories[i]; + const metadataCategories = ['collections', 'permissions', 'quality', 'properties', 'metadataValues']; + for (let i = 0; i < metadataCategories.length; i++) { + const category = metadataCategories[i]; if (document !== null) { if (document[category] != null) { if (metadata === null) { @@ -1466,18 +1466,18 @@ function collectMetadata(document) { /** @ignore */ function removeOutputTransform(headers/*, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; if (operation.contentOnly === true) { return operation.uris; } - var wrapper = { + const wrapper = { uris: operation.uris, removed: true }; - var systemTime = headers.systemTime; + const systemTime = headers.systemTime; if (systemTime != null) { wrapper.systemTime = systemTime; } @@ -1524,13 +1524,13 @@ function removeDocumentImpl(contentOnly, args) { throw new Error('must provide uris for document remove()'); } - var uris = null; - var txid = null; - var temporalCollection = null; - var systemTime = null; - var versionId = null; + let uris = null; + let txid = null; + let temporalCollection = null; + let systemTime = null; + let versionId = null; - var arg = args[0]; + const arg = args[0]; if (Array.isArray(arg)) { uris = arg; } else if (typeof arg === 'string' || arg instanceof String) { @@ -1550,7 +1550,7 @@ function removeDocumentImpl(contentOnly, args) { versionId = arg.versionId; } - var path = '/v1/documents?uri='+ + let path = '/v1/documents?uri='+ uris.map(encodeURIComponent).join('&uri='); if (txid != null) { path += '&txid='+mlutil.getTxidParam(txid); @@ -1572,7 +1572,7 @@ function removeDocumentImpl(contentOnly, args) { } mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'remove document', this.client, requestOptions, 'empty', 'empty' ); operation.uris = uris; @@ -1586,22 +1586,22 @@ function removeDocumentImpl(contentOnly, args) { function removeAllOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; if (operation.contentOnly === true) { return operation.collection; } - var output = { + const output = { exists: false }; - var collection = operation.collection; + const collection = operation.collection; if (collection != null) { output.collection = collection; } - var directory = operation.directory; + const directory = operation.directory; if (directory != null) { output.directory = directory; } @@ -1637,18 +1637,18 @@ function removeAllDocumentsImpl(contentOnly, params) { throw new Error('No parameters specifying directory or collection to delete'); } - var deleteAll = (params.all === true); + const deleteAll = (params.all === true); - var collection = params.collection; - var hasCollection = (collection != null); + const collection = params.collection; + const hasCollection = (collection != null); - var directory = params.directory; - var hasDirectory = (directory != null); + const directory = params.directory; + const hasDirectory = (directory != null); - var txid = mlutil.convertTransaction(params.txid); + const txid = mlutil.convertTransaction(params.txid); - var endpoint = '/v1/search'; - var sep = '?'; + let endpoint = '/v1/search'; + let sep = '?'; if (hasCollection || hasDirectory) { if (deleteAll) { @@ -1680,7 +1680,7 @@ function removeAllDocumentsImpl(contentOnly, params) { const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), endpoint, 'DELETE'); mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'remove all documents', this.client, requestOptions, 'empty', 'empty' ); if (hasCollection) { @@ -1752,47 +1752,47 @@ Documents.prototype.query = function queryDocuments(builtQuery, timestamp, resul }; function queryDocumentsImpl(collectionParam, contentOnly, builtQuery, timestamp, resultEstimateCallback) { /*jshint validthis:true */ - var wrapper = qb.makeSearchBody(builtQuery); - - var categories = wrapper.categories; - var optionsName = wrapper.optionsName; - var pageStart = wrapper.pageStart; - var pageLength = wrapper.pageLength; - var txid = mlutil.convertTransaction(wrapper.txid); - var transform = wrapper.transform; - var view = wrapper.view; - var searchBody = wrapper.searchBody; - - var returnDocuments = (pageLength !== 0); + const wrapper = qb.makeSearchBody(builtQuery); + + const categories = wrapper.categories; + const optionsName = wrapper.optionsName; + const pageStart = wrapper.pageStart; + const pageLength = wrapper.pageLength; + const txid = mlutil.convertTransaction(wrapper.txid); + const transform = wrapper.transform; + const view = wrapper.view; + const searchBody = wrapper.searchBody; + + let returnDocuments = (pageLength !== 0); if (!returnDocuments && builtQuery.queryType !== 'qbe') { - var searchOptions = searchBody.search.options; + const searchOptions = searchBody.search.options; if (searchOptions !== void 0) { - var transformResults = searchOptions['transform-results']; + const transformResults = searchOptions['transform-results']; if (transformResults !== null && transformResults !== void 0 && transformResults.apply !== 'empty-snippet') { throw new Error('cannot snippet with page length of zero'); } - var extractResults = searchOptions['extract-document-data']; + const extractResults = searchOptions['extract-document-data']; if (extractResults !== null && extractResults !== void 0) { throw new Error('cannot extract document data with page length of zero'); } } } - var requestPartList = null; + let requestPartList = null; - var isMultipart = false; + let isMultipart = false; - var endpoint = null; + let endpoint = null; if (builtQuery.queryFormat === void 0) { endpoint = '/v1/search?format=json'; } else if (builtQuery.queryType === 'qbe') { - var qbeQuery = searchBody.search.$query; + const qbeQuery = searchBody.search.$query; if (typeof qbeQuery === 'string' || qbeQuery instanceof String) { - var options = searchBody.search.options; - var part = { + const options = searchBody.search.options; + const part = { headers: {'Content-Type': 'application/xml'}, content: qbeQuery }; @@ -1811,7 +1811,7 @@ function queryDocumentsImpl(collectionParam, contentOnly, builtQuery, timestamp, endpoint = '/v1/search?format='+builtQuery.queryFormat; } - var multipartBoundary = + const multipartBoundary = (isMultipart || returnDocuments) ? mlutil.multipartBoundary : null; if (categories != null) { @@ -1867,7 +1867,7 @@ function queryDocumentsImpl(collectionParam, contentOnly, builtQuery, timestamp, }; mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'query documents', this.client, requestOptions, (isMultipart ? 'multipart' : 'single'), (returnDocuments ? 'multipart' : 'single') @@ -1897,7 +1897,7 @@ function queryDocumentsImpl(collectionParam, contentOnly, builtQuery, timestamp, /** @ignore */ function patchOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; return { uri: operation.uri @@ -1940,26 +1940,26 @@ function patchOutputTransform(/*headers, data*/) { * a {@link documents#patchResult} success callback. */ Documents.prototype.patch = function patchDocuments() { - var argLen = arguments.length; + const argLen = arguments.length; - var arg = arguments[0]; + let arg = arguments[0]; - var params = (argLen === 1) ? arg : null; + const params = (argLen === 1) ? arg : null; // TODO: allow for raw JSON or XML patch - var uri = null; - var documentOperations = null; - var categories = null; - var temporalCollection = null; - var temporalDocument = null; - var sourceDocument = null; - var txid = null; - var versionId = null; - var pathlang = null; - var format = null; - var isRawPatch = false; - var i = 0; + let uri = null; + let documentOperations = null; + let categories = null; + let temporalCollection = null; + let temporalDocument = null; + let sourceDocument = null; + let txid = null; + let versionId = null; + let pathlang = null; + let format = null; + let isRawPatch = false; + let i = 0; if (params !== null) { uri = params.uri; arg = params.operations; @@ -2022,7 +2022,7 @@ Documents.prototype.patch = function patchDocuments() { } } - var endpoint = '/v1/documents?uri='+encodeURIComponent(uri); + let endpoint = '/v1/documents?uri='+encodeURIComponent(uri); if (categories != null) { if (!Array.isArray(categories)) { categories = [categories]; @@ -2048,7 +2048,7 @@ Documents.prototype.patch = function patchDocuments() { endpoint += '&txid=' + mlutil.getTxidParam(txid); } - var patchBody = isRawPatch ? documentOperations : {patch: documentOperations}; + const patchBody = isRawPatch ? documentOperations : {patch: documentOperations}; if (!isRawPatch && (pathlang != null)) { patchBody.pathlang = pathlang; } @@ -2065,7 +2065,7 @@ Documents.prototype.patch = function patchDocuments() { } mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'patch document', this.client, requestOptions, 'single', 'single' ); operation.uri = uri; @@ -2099,16 +2099,16 @@ Documents.prototype.patch = function patchDocuments() { * strings. */ Documents.prototype.suggest = function suggestDocuments() { - var argLen = arguments.length; + const argLen = arguments.length; if (argLen < 1) { throw new Error('no partial query text or query with bindings'); } - var params = null; - var partial = null; - var query = null; - var bindings = null; - var limit = null; + let params = null; + let partial = null; + let query = null; + let bindings = null; + let limit = null; switch (argLen) { case 1: params = arguments[0]; @@ -2135,10 +2135,10 @@ Documents.prototype.suggest = function suggestDocuments() { throw new Error('no query with bindings for document suggestion'); } - var wrapper = qb.makeSearchBody(query); + const wrapper = qb.makeSearchBody(query); - var searchBody = wrapper.searchBody; - var search = searchBody.search; + const searchBody = wrapper.searchBody; + const search = searchBody.search; if (search == null) { throw new Error('cannot get document suggestions for empty search'); } @@ -2146,35 +2146,35 @@ Documents.prototype.suggest = function suggestDocuments() { throw new Error('cannot get document suggestions for Query By Example (QBE)'); } - var searchOptions = search.options; + let searchOptions = search.options; if (searchOptions == null) { searchOptions = {}; search.options = searchOptions; } - var searchConstraints = searchOptions.constraint; + const searchConstraints = searchOptions.constraint; - var hasBindings = (bindings != null); + const hasBindings = (bindings != null); - var suggestConstraints = hasBindings ? bindings.constraint : null; - var sources = copyConstraints(suggestConstraints, searchConstraints); + const suggestConstraints = hasBindings ? bindings.constraint : null; + const sources = copyConstraints(suggestConstraints, searchConstraints); if (sources.length > 0) { searchOptions['suggestion-source'] = sources; } - var term = hasBindings ? bindings.term : null; + let term = hasBindings ? bindings.term : null; if (term == null) { term = searchOptions.term; } - var termDefault = null; + let termDefault = null; if (term != null) { - termDefault = term['default']; + termDefault = term.default; if (termDefault != null) { searchOptions['default-suggestion-source'] = termDefault; } } - var endpoint = '/v1/suggest?partial-q='+encodeURIComponent(partial); + let endpoint = '/v1/suggest?partial-q='+encodeURIComponent(partial); if (limit != null) { endpoint += '&limit=' + limit; } @@ -2186,7 +2186,7 @@ Documents.prototype.suggest = function suggestDocuments() { }; mlutil.addTxidHeaders(requestOptions, wrapper.txid); - var operation = new Operation( + const operation = new Operation( 'search suggest', this.client, requestOptions, 'single', 'single' ); operation.input = partial; @@ -2225,19 +2225,19 @@ Documents.prototype.writeAll = function writeAllDocuments(stream,options) { }; function writeAllDocumentsImpl(inputStream,jobOptions) { - let path = '/v1/internal/forestinfo'; - let connectionParams = this.client.getConnectionParams(); + const path = '/v1/internal/forestinfo'; + const connectionParams = this.client.getConnectionParams(); const requestOptions = mlutil.newRequestOptions(connectionParams, path, 'GET'); requestOptions.headers = { 'Accept': 'application/json', }; - let operation = new Operation( + const operation = new Operation( 'read forestInfo', this.client, requestOptions, 'empty', 'single' ); - let jobState = { + const jobState = { docInstance : this, stream: inputStream, requesterCount: 0, @@ -2477,20 +2477,20 @@ function queryAllDocumentsImpl(query, jobOptions) { throw new Error('Query needs to be a cts query.'); } - let path = '/v1/internal/forestinfo'; + const path = '/v1/internal/forestinfo'; const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'POST'); - let wrapper = {ctsast: bldrbase.exportArg(query.whereClause)}; + const wrapper = {ctsast: bldrbase.exportArg(query.whereClause)}; requestOptions.headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }; - let operation = new Operation( + const operation = new Operation( 'read forestInfo', this.client, requestOptions, 'single', 'single' ); operation.requestBody = mlutil.marshal(wrapper, operation); - let jobState = { + const jobState = { docInstance : this, jobOptions: (jobOptions)? mlutil.copyProperties(jobOptions):{}, urisReadSoFar: 0, @@ -2542,7 +2542,7 @@ function queryAllDocumentsImpl(query, jobOptions) { function onQueryUrisRequest(output) { const jobState = this; const pageLength = (jobState.jobOptions.batchSize * jobState.jobOptions.queryBatchMultiple); - let endpoint = '/v1/internal/uris?filtered=false&start=1&pageLength='+pageLength; + const endpoint = '/v1/internal/uris?filtered=false&start=1&pageLength='+pageLength; jobState.query = output.query; jobState.forests = output.forests; jobState.requesterCount = output.forests.length; @@ -2574,8 +2574,8 @@ function spinForestRequests(jobState, initialization){ } function onDocUrisCollected(output) { - let jobValues= this; - let jobState = jobValues.jobState; + const jobValues= this; + const jobState = jobValues.jobState; if(output) { const uriArr = output.uriArr; @@ -2586,7 +2586,7 @@ function onDocUrisCollected(output) { const writeSize = jobState.jobOptions.batchSize; let i=0; while(i 0) { overrides = {}; for (i=0; i < bindLen; i++) { @@ -3237,7 +3237,7 @@ function copyConstraints(suggestConstraints, searchConstraints) { copy = null; } - var isCopyKey = null; + let isCopyKey = null; if (Array.isArray(searchConstraints)) { isCopyKey = { collection: true, @@ -3319,18 +3319,18 @@ Documents.prototype.transformAll = function transformAllDocuments(stream, option }; function transformAllDocumentsImpl(inputStream, jobOptions){ - let path = '/v1/internal/forestinfo'; + const path = '/v1/internal/forestinfo'; const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'GET'); requestOptions.headers = { 'Accept': 'application/json', }; - let operation = new Operation( + const operation = new Operation( 'read forestInfo', this.client, requestOptions, 'empty', 'single' ); - let jobState = { + const jobState = { docInstance : this, requesterCount: 0, docsTransformedSuccessfully:0, @@ -3416,7 +3416,7 @@ function onTransformAllInit(output) { '&transform='+jobState.jobOptions.transform[0]; if(jobState.jobOptions.transform.length >1){ const transformParams = jobState.jobOptions.transform[1]; - for(let paramName of Object.keys(transformParams)){ + for(const paramName of Object.keys(transformParams)){ const paramValue = transformParams[paramName]; endpoint+= '&'+encodeURIComponent('trans:'+paramName)+'='+encodeURIComponent(paramValue); } @@ -3494,7 +3494,7 @@ function onTransformAllDocs(jobState, writerId) { function transformDocs(jobState, transformBatchArray, writerId){ - let operation = new Operation( + const operation = new Operation( 'transform docs', jobState.docInstance.client, jobState.requestOptions, 'single', 'single' ); operation.validStatusCodes = [200, 201]; @@ -3639,8 +3639,8 @@ Documents.prototype.queryToTransformAll = function queryToTransformAllDocuments( }; function queryToTransformAllDocumentsImpl(query, jobOptions){ - let queryAllJobOptions = {}; - let transformAllJobOptions = {}; + const queryAllJobOptions = {}; + const transformAllJobOptions = {}; if(!jobOptions){ jobOptions = {}; @@ -3687,7 +3687,7 @@ function queryToTransformAllDocumentsImpl(query, jobOptions){ queryAllJobOptions.queryToOptions = transformAllJobOptions; const docInstance = this; - let queryAllStream = queryAllDocumentsImpl.call(docInstance, query, queryAllJobOptions); + const queryAllStream = queryAllDocumentsImpl.call(docInstance, query, queryAllJobOptions); let pipelined = false; queryAllStream.on('data', function(item){ @@ -3731,18 +3731,18 @@ Documents.prototype.removeAllUris = function removeAllUrisDocuments(stream, opti }; function removeAllUrisDocumentsImpl(inputStream, jobOptions){ - let path = '/v1/internal/forestinfo'; + const path = '/v1/internal/forestinfo'; const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'GET'); requestOptions.headers = { 'Accept': 'application/json', }; - let operation = new Operation( + const operation = new Operation( 'read forestInfo', this.client, requestOptions, 'empty', 'single' ); - let jobState = { + const jobState = { docInstance : this, requesterCount: 0, docsRemovedSuccessfully:0, @@ -4003,8 +4003,8 @@ Documents.prototype.queryToRemoveAll = function queryToRemoveAllDocuments(query, }; function queryToRemoveAllDocumentsImpl(query, jobOptions){ - let queryAllJobOptions = {}; - let removeAllJobOptions = {}; + const queryAllJobOptions = {}; + const removeAllJobOptions = {}; if(!jobOptions){ jobOptions = {}; @@ -4046,7 +4046,7 @@ function queryToRemoveAllDocumentsImpl(query, jobOptions){ queryAllJobOptions.queryToOptions = removeAllJobOptions; const docInstance = this; - let queryAllStream = queryAllDocumentsImpl.call(docInstance, query, queryAllJobOptions); + const queryAllStream = queryAllDocumentsImpl.call(docInstance, query, queryAllJobOptions); let pipelined = false; queryAllStream.on('data', function(item){ diff --git a/lib/extlibs.js b/lib/extlibs.js index a3f03385..656fe487 100644 --- a/lib/extlibs.js +++ b/lib/extlibs.js @@ -2,16 +2,16 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); /** @ignore */ function pathErrorTransform(message) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var path = operation.path; + const path = operation.path; return (path == null) ? message : (message+' (on '+path+' extension library)'); } @@ -26,7 +26,7 @@ function pathErrorTransform(message) { /** @ignore */ function emptyOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; return { path: operation.path @@ -54,7 +54,7 @@ ExtLibs.prototype.read = function readExtensionLibrary(path) { throw new Error('must specify path when reading the extension library resource'); } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'GET'; requestOptions.path = encodeURI( (path.substr(0,5) === '/ext/') ? ('/v1'+path) : @@ -62,7 +62,7 @@ ExtLibs.prototype.read = function readExtensionLibrary(path) { ('/v1/ext/'+path) ); - var operation = new Operation( + const operation = new Operation( 'read extension library', this.client, requestOptions, 'empty', 'single' ); operation.path = path; @@ -82,20 +82,20 @@ ExtLibs.prototype.read = function readExtensionLibrary(path) { * @param {object|string} source - the library resource */ ExtLibs.prototype.write = function writeExtensionLibrary() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen === 0) { throw new Error('no arguments for writing an extension library'); } - var path = null; - var permissions = null; - var contentType = null; - var source = null; - var i = 0; - var arg = null; + let path = null; + let permissions = null; + let contentType = null; + let source = null; + let i = 0; + let arg = null; - var params = null; + let params = null; if (argLen === 1) { params = args[0]; path = params.path; @@ -103,7 +103,7 @@ ExtLibs.prototype.write = function writeExtensionLibrary() { contentType = params.contentType; source = params.source; } else { - var argMax = Math.min(argLen,4); + const argMax = Math.min(argLen,4); for (;i < argMax; i++) { arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { @@ -127,15 +127,15 @@ ExtLibs.prototype.write = function writeExtensionLibrary() { throw new Error('must specify the path, content type, and source when writing a extension library'); } - var endpoint = + let endpoint = (path.substr(0,5) === '/ext/') ? ('/v1'+path) : (path.substr(0,1) === '/') ? ('/v1/ext'+path) : ('/v1/ext/'+path); if (Array.isArray(permissions)) { - var role = null; - var capabilities = null; - var j=null; + let role = null; + let capabilities = null; + let j=null; for (i=0; i < permissions.length; i++) { arg = permissions[i]; role = arg['role-name']; @@ -149,14 +149,14 @@ ExtLibs.prototype.write = function writeExtensionLibrary() { } } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'PUT'; requestOptions.headers = { 'Content-Type': contentType }; requestOptions.path = encodeURI(endpoint); - var operation = new Operation( + const operation = new Operation( 'write extension library', this.client, requestOptions, 'single', 'empty' ); operation.path = path; @@ -178,7 +178,7 @@ ExtLibs.prototype.remove = function removeExtensionLibrary(path) { throw new Error('must specify path when deleting the extension library resource'); } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'DELETE'; requestOptions.path = encodeURI( (path.substr(0,5) === '/ext/') ? ('/v1'+path) : @@ -186,7 +186,7 @@ ExtLibs.prototype.remove = function removeExtensionLibrary(path) { ('/v1/ext/'+path) ); - var operation = new Operation( + const operation = new Operation( 'remove extension library', this.client, requestOptions, 'empty', 'empty' ); operation.path = path; @@ -207,7 +207,7 @@ ExtLibs.prototype.remove = function removeExtensionLibrary(path) { * in the directory */ ExtLibs.prototype.list = function listExtensionLibraries(directory) { - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'GET'; requestOptions.headers = { 'Accept': 'application/json' @@ -222,8 +222,8 @@ ExtLibs.prototype.list = function listExtensionLibraries(directory) { requestOptions.path = encodeURI(directory+'/'); } } else { - var hasInitialSlash = (directory.substr(0,1) === '/'); - var hasTrailingSlash = (directory.substr(-1,1) === '/'); + const hasInitialSlash = (directory.substr(0,1) === '/'); + const hasTrailingSlash = (directory.substr(-1,1) === '/'); if (hasInitialSlash && hasTrailingSlash) { requestOptions.path = encodeURI('/v1/ext' + directory); } else if (hasTrailingSlash) { @@ -235,7 +235,7 @@ ExtLibs.prototype.list = function listExtensionLibraries(directory) { } } - var operation = new Operation( + const operation = new Operation( 'list extension libraries', this.client, requestOptions, 'empty', 'single' ); diff --git a/lib/graphs.js b/lib/graphs.js index 2c5489d3..b64660e3 100644 --- a/lib/graphs.js +++ b/lib/graphs.js @@ -3,15 +3,15 @@ */ 'use strict'; -var requester = require('./requester.js'); +const requester = require('./requester.js'); var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); -var qb = require('./query-builder.js'); +const Operation = require('./operation.js'); +const qb = require('./query-builder.js'); var mlutil = require('./mlutil.js'); function uriErrorTransform(message) { /*jshint validthis:true */ - var operation = this; + const operation = this; switch(operation.graphType) { case 'default': return message+' (on default graph)'; @@ -19,7 +19,7 @@ function uriErrorTransform(message) { case 'managed': return message+' (on managed graphs)'; } - var uri = operation.uri; + const uri = operation.uri; if (typeof uri === 'string' || uri instanceof String) { return message+' (on graph '+uri+')'; } @@ -28,12 +28,12 @@ function uriErrorTransform(message) { } function checkOutputTransform(headers, data) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var statusCode = operation.responseStatusCode; - var exists = (statusCode === 200) ? true : false; + const statusCode = operation.responseStatusCode; + const exists = (statusCode === 200) ? true : false; - var output = exists ? operation.responseHeaders : {}; + const output = exists ? operation.responseHeaders : {}; output.exists = exists; return identifyOutput.call(operation, data, output); @@ -44,9 +44,9 @@ function emptyOutputTransform(headers, data) { } function identifyOutput(data, output) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var graphType = operation.graphType; + const graphType = operation.graphType; switch(graphType) { case 'named': output.defaultGraph = false; @@ -71,7 +71,7 @@ function identifyOutput(data, output) { } function listOutputTransform(headers, data) { /*jshint validthis:true */ - var operation = this; + const operation = this; if (data == null) { return data; @@ -123,19 +123,19 @@ function Graphs(client) { * that receives the triples for the graph in the requested format */ Graphs.prototype.read = function readGraph() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen === 0) { throw new Error('must specify the content type when reading a graph'); } - var contentType = null; - var uri = null; - var category = null; - var txid = null; - var timestamp = null; + let contentType = null; + let uri = null; + let category = null; + let txid = null; + let timestamp = null; - var testArg = args[0]; + const testArg = args[0]; if (typeof testArg === 'string' || testArg instanceof String) { if (argLen > 1) { uri = testArg; @@ -144,7 +144,7 @@ Graphs.prototype.read = function readGraph() { contentType = testArg; } } else { - var params = testArg; + const params = testArg; contentType = params.contentType; uri = params.uri; category = params.category; @@ -155,7 +155,7 @@ Graphs.prototype.read = function readGraph() { } } - var endpoint = (uri == null) ? + let endpoint = (uri == null) ? '/v1/graphs?default' : ('/v1/graphs?graph='+encodeURIComponent(uri)); if (category !== null && category !== void 0) { if (typeof category === 'string' || category instanceof String) { @@ -178,7 +178,7 @@ Graphs.prototype.read = function readGraph() { 'Accept': contentType }; - var operation = new Operation( + const operation = new Operation( 'read graph', this.client, requestOptions, 'empty', 'single' ); if (uri === null) { @@ -270,7 +270,7 @@ Graphs.prototype.createMergeStream = function createGraphMergeStream() { /** @ignore */ function changeGraph(action, isStreaming, args) { /*jshint validthis:true */ - var argLen = args.length; + const argLen = args.length; if (argLen === 0) { throw new Error( isStreaming ? @@ -279,16 +279,16 @@ function changeGraph(action, isStreaming, args) { ); } - var uri = null; - var contentType = null; - var repair = false; - var permissions = null; - var data = null; - var txid = null; + let uri = null; + let contentType = null; + let repair = false; + let permissions = null; + let data = null; + let txid = null; if (argLen > 1 || (typeof args[0] === 'string' || args[0] instanceof String)) { - var arg = null; - var i = argLen - 1; + let arg = null; + let i = argLen - 1; for (; i >= 0; i--) { arg = args[i]; if (typeof arg === 'boolean') { @@ -312,14 +312,14 @@ function changeGraph(action, isStreaming, args) { throw new Error('unknown positional parameter for graphs write: '+arg); } } else { - var params = args[0]; + const params = args[0]; contentType = params.contentType; uri = params.uri; repair = params.repair || false; permissions = params.permissions; data = params.data; txid = mlutil.convertTransaction(params.txid); - var noContentType = (contentType == null); + const noContentType = (contentType == null); if (isStreaming) { if (noContentType) { throw new Error('named parameters must specify the content type for '+action); @@ -331,7 +331,7 @@ function changeGraph(action, isStreaming, args) { } } - var graphType = null; + let graphType = null; if (uri === null || uri === void 0) { graphType = 'default'; } else if (uri instanceof InlineGraphUrisDef) { @@ -340,9 +340,9 @@ function changeGraph(action, isStreaming, args) { graphType = 'named'; } - var sep = '?'; + let sep = '?'; - var endpoint = null; + let endpoint = null; switch(graphType) { case 'named': endpoint = '/v1/graphs?graph='+encodeURIComponent(uri); sep = '&'; break; case 'default': endpoint = '/v1/graphs?default'; sep = '&'; break; @@ -359,7 +359,7 @@ function changeGraph(action, isStreaming, args) { if (sep === '?') { sep = '&'; } } - var permissionsParams = makePermissionsParams(permissions, sep); + const permissionsParams = makePermissionsParams(permissions, sep); if (permissionsParams !== null) { endpoint += permissionsParams; if (sep === '?') { sep = '&'; } @@ -370,7 +370,7 @@ function changeGraph(action, isStreaming, args) { 'Content-Type': contentType }; - var operation = new Operation( + const operation = new Operation( action+' graph', this.client, requestOptions, (isStreaming ? 'chunked' : 'single'), 'empty' ); operation.graphType = graphType; @@ -400,7 +400,7 @@ function changeGraph(action, isStreaming, args) { * called when the triples are removed */ Graphs.prototype.remove = function removeGraph() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); return applyGraph.call(this, 'remove', args); }; @@ -416,15 +416,15 @@ Graphs.prototype.remove = function removeGraph() { * that receives an object with an exists boolean for the graph */ Graphs.prototype.probe = function probeGraph() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); return applyGraph.call(this, 'probe', args); }; /** @ignore */ function applyGraph(action, args) { /*jshint validthis:true */ - var uri = null; - var txid = null; + let uri = null; + let txid = null; switch(args.length) { case 0: break; @@ -444,9 +444,9 @@ function applyGraph(action, args) { break; } - var endpoint = null; - var graphType = null; - var sep = null; + let endpoint = null; + let graphType = null; + let sep = null; if (uri === null || uri === void 0) { endpoint = '/v1/graphs?default'; graphType = 'default'; @@ -471,7 +471,7 @@ function applyGraph(action, args) { const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), endpoint, ((action === 'remove') ? 'DELETE' : 'HEAD')); - var operation = new Operation( + const operation = new Operation( action+' graph', this.client, requestOptions, 'empty', 'empty' ); operation.graphType = graphType; @@ -504,14 +504,14 @@ function applyGraph(action, args) { * on the server */ Graphs.prototype.list = function listGraphs() { - var argLen = arguments.length; + const argLen = arguments.length; - var contentType = null; - var txid = null; - var timestamp = null; + let contentType = null; + let txid = null; + let timestamp = null; if (argLen > 0) { - var arg = null; - var i = argLen - 1; + let arg = null; + let i = argLen - 1; for (; i >= 0; i--) { arg = arguments[i]; if (typeof arg === 'string' || arg instanceof String) { @@ -536,10 +536,10 @@ Graphs.prototype.list = function listGraphs() { } } - var noContentType = (contentType === null || contentType === void 0); + const noContentType = (contentType === null || contentType === void 0); - var endpoint = '/v1/graphs'; - var sep = '?'; + let endpoint = '/v1/graphs'; + let sep = '?'; if (txid !== null && txid !== void 0) { endpoint += sep+'txid='+mlutil.getTxidParam(txid); @@ -560,7 +560,7 @@ Graphs.prototype.list = function listGraphs() { }; } - var operation = new Operation( + const operation = new Operation( 'list graphs', this.client, requestOptions, 'empty', 'single' ); if (!noContentType) { @@ -611,34 +611,34 @@ Graphs.prototype.list = function listGraphs() { * that receives the query response */ Graphs.prototype.sparql = function queryGraphSPARQL() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen === 0) { throw new Error('must specify content type and query for SPARQL query on graphs'); } - var defaultGraphs = null; - var namedGraphs = null; - var acceptType = null; - var query = null; + let defaultGraphs = null; + let namedGraphs = null; + let acceptType = null; + let query = null; - var docQuery = null; - var begin = null; - var end = null; - var base = null; - var txid = null; - var rulesets = null; - var defaultRulesets = null; - var optimizeLevel = null; - var bindings = null; - var timestamp = null; + let docQuery = null; + let begin = null; + let end = null; + let base = null; + let txid = null; + let rulesets = null; + let defaultRulesets = null; + let optimizeLevel = null; + let bindings = null; + let timestamp = null; // TODO: collection, directory? // Single configuration object if (argLen === 1) { - var params = args[0]; + const params = args[0]; acceptType = params.contentType; defaultGraphs = params.defaultGraphs; namedGraphs = params.namedGraphs; @@ -667,10 +667,10 @@ Graphs.prototype.sparql = function queryGraphSPARQL() { query = args[argLen - 1]; } - var endpoint = '/v1/graphs/sparql'; - var sep = '?'; + let endpoint = '/v1/graphs/sparql'; + let sep = '?'; - var hasDefaultGraphs = (defaultGraphs !== null && defaultGraphs !== void 0); + let hasDefaultGraphs = (defaultGraphs !== null && defaultGraphs !== void 0); if (hasDefaultGraphs) { defaultGraphs = mlutil.asArray(defaultGraphs); if (defaultGraphs.length > 0) { @@ -681,7 +681,7 @@ Graphs.prototype.sparql = function queryGraphSPARQL() { } } - var hasNamedGraphs = (namedGraphs !== null && namedGraphs !== void 0); + let hasNamedGraphs = (namedGraphs !== null && namedGraphs !== void 0); if (hasNamedGraphs) { namedGraphs = mlutil.asArray(namedGraphs); if (namedGraphs.length > 0) { @@ -692,7 +692,7 @@ Graphs.prototype.sparql = function queryGraphSPARQL() { } } - var hasBegin = (begin !== null && begin !== void 0); + const hasBegin = (begin !== null && begin !== void 0); if (hasBegin) { if (begin >= 0) { endpoint += sep+'start='+(begin + 1); @@ -717,7 +717,7 @@ Graphs.prototype.sparql = function queryGraphSPARQL() { } } - var commonParams = makeCommonSPARQLParams( + const commonParams = makeCommonSPARQLParams( base, txid, rulesets, defaultRulesets, optimizeLevel, bindings, sep ); if (commonParams !== null) { @@ -725,14 +725,14 @@ Graphs.prototype.sparql = function queryGraphSPARQL() { if (sep === '?') { sep = '&'; } } - var contentType = null; - var queryBody = null; + let contentType = null; + let queryBody = null; if (docQuery === null || docQuery === void 0) { contentType = 'application/sparql-query'; queryBody = query; } else { contentType = 'application/json'; - var builtQuery = + const builtQuery = (docQuery instanceof qb.lib.QueryBuilder || docQuery.search !== void 0) ? docQuery : qb.builder.where(docQuery); if (builtQuery.queryType === 'qbe') { @@ -750,7 +750,7 @@ Graphs.prototype.sparql = function queryGraphSPARQL() { 'Accept': acceptType }; - var operation = new Operation( + const operation = new Operation( 'SPARQL graph query', this.client, requestOptions, 'single', 'single' ); if (hasDefaultGraphs) { @@ -795,25 +795,25 @@ Graphs.prototype.sparql = function queryGraphSPARQL() { * called when the triples are updated */ Graphs.prototype.sparqlUpdate = function updateGraphSPARQL() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen === 0) { throw new Error('must specify data for SPARQL update on graphs'); } - var permissions = null; - var usingDefaultGraphs = null; - var usingNamedGraphs = null; - var base = null; - var txid = null; - var rulesets = null; - var defaultRulesets = null; - var optimizeLevel = null; - var bindings = null; + let permissions = null; + let usingDefaultGraphs = null; + let usingNamedGraphs = null; + let base = null; + let txid = null; + let rulesets = null; + let defaultRulesets = null; + let optimizeLevel = null; + let bindings = null; - var arg = args[0]; - var data = (argLen === 1) ? arg.data : null; + const arg = args[0]; + let data = (argLen === 1) ? arg.data : null; if (data !== null && data !== void 0) { permissions = arg.permissions; usingDefaultGraphs = arg.usingDefaultGraphs; @@ -831,10 +831,10 @@ Graphs.prototype.sparqlUpdate = function updateGraphSPARQL() { data = args[0]; } - var endpoint = '/v1/graphs/sparql'; - var sep = '?'; + let endpoint = '/v1/graphs/sparql'; + let sep = '?'; - var hasUsingDefaultGraphs = (usingDefaultGraphs !== null && usingDefaultGraphs !== void 0); + let hasUsingDefaultGraphs = (usingDefaultGraphs !== null && usingDefaultGraphs !== void 0); if (hasUsingDefaultGraphs) { usingDefaultGraphs = mlutil.asArray(usingDefaultGraphs); if (usingDefaultGraphs.length > 0) { @@ -845,7 +845,7 @@ Graphs.prototype.sparqlUpdate = function updateGraphSPARQL() { } } - var hasUsingNamedGraphs = (usingNamedGraphs !== null && usingNamedGraphs !== void 0); + let hasUsingNamedGraphs = (usingNamedGraphs !== null && usingNamedGraphs !== void 0); if (hasUsingNamedGraphs) { usingNamedGraphs = mlutil.asArray(usingNamedGraphs); if (usingNamedGraphs.length > 0) { @@ -856,13 +856,13 @@ Graphs.prototype.sparqlUpdate = function updateGraphSPARQL() { } } - var permissionsParams = makePermissionsParams(permissions, sep); + const permissionsParams = makePermissionsParams(permissions, sep); if (permissionsParams !== null) { endpoint += permissionsParams; if (sep === '?') { sep = '&'; } } - var commonParams = makeCommonSPARQLParams( + const commonParams = makeCommonSPARQLParams( base, txid, rulesets, defaultRulesets, optimizeLevel, bindings, sep ); if (commonParams !== null) { @@ -875,7 +875,7 @@ Graphs.prototype.sparqlUpdate = function updateGraphSPARQL() { 'Content-Type': 'application/sparql-update' }; - var operation = new Operation( + const operation = new Operation( 'SPARQL graph update', this.client, requestOptions, 'single', 'empty' ); @@ -895,15 +895,15 @@ function makePermissionsParams(permissions, sep) { return null; } - var endpoint = ''; + let endpoint = ''; - var permLen = permissions.length; - var permdef = null; - var roleName = null; - var capabilities = null; - var capLen = 0; - var j = 0; - for (var i = 0; i < permLen; i++) { + const permLen = permissions.length; + let permdef = null; + let roleName = null; + let capabilities = null; + let capLen = 0; + let j = 0; + for (let i = 0; i < permLen; i++) { permdef = permissions[i]; roleName = permdef['role-name']; capabilities = permdef.capabilities; @@ -919,8 +919,8 @@ function makePermissionsParams(permissions, sep) { function makeCommonSPARQLParams( base, txidRaw, rulesets, defaultRulesets, optimizeLevel, bindings, sep ) { - var endpoint = ''; - var txid = mlutil.convertTransaction(txidRaw); + let endpoint = ''; + const txid = mlutil.convertTransaction(txidRaw); if (base !== null && base !== void 0) { endpoint += sep+'base='+encodeURIComponent(base); if (sep === '?') { sep = '&'; } @@ -949,9 +949,9 @@ function makeCommonSPARQLParams( } function encodeParamValues(name, values) { if (Array.isArray(values)) { - var result = null; - var max = values.length; - for (var i=0; i < max; i++) { + let result = null; + const max = values.length; + for (let i=0; i < max; i++) { if (i === 0) { result = encodeURIComponent(name)+'='+encodeURIComponent(values[i]); } else { diff --git a/lib/internal.js b/lib/internal.js index fbe8edb6..bcfbeeff 100644 --- a/lib/internal.js +++ b/lib/internal.js @@ -14,7 +14,7 @@ class InternalClass { if(!path){ throw new Error('Path is needed to send request.'); } - let requestOptions = mlutil.newRequestOptions(this.clientObject.getConnectionParams(), path); + const requestOptions = mlutil.newRequestOptions(this.clientObject.getConnectionParams(), path); if (requestOptionsCallback) { requestOptionsCallback(requestOptions); } diff --git a/lib/marklogic.js b/lib/marklogic.js index 83ad0639..be579a34 100644 --- a/lib/marklogic.js +++ b/lib/marklogic.js @@ -2,32 +2,32 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var http = require('http'); -var https = require('https'); - -var mlutil = require('./mlutil.js'); -var mllog = require('./mllog.js'); - -var documents = require('./documents.js'); -var Graphs = require('./graphs.js'); -var Rows = require('./rows.js'); -var Values = require('./values.js'); -var ExtLibs = require('./extlibs.js'); -var RESTServerProperties = require('./rest-server-properties.js'); -var Transactions = require('./transactions.js'); -var Transforms = require('./transforms.js'); -var ResourcesConfig = require('./resources-config.js'); -var ResourcesExec = require('./resources-exec.js'); -var serverExec = require('./server-exec.js'); - -var queryBuilder = require('./query-builder.js'); -var patchBuilder = require('./patch-builder.js'); -var valuesBuilder = require('./values-builder.js'); -var planBuilder = require('./plan-builder.js'); -var ctsQueryBuilder = require('./ctsquery-builder'); -var Operation = require('./operation.js'); -var requester = require('./requester.js'); -let internal = require('./internal.js'); +const http = require('http'); +const https = require('https'); + +const mlutil = require('./mlutil.js'); +const mllog = require('./mllog.js'); + +const documents = require('./documents.js'); +const Graphs = require('./graphs.js'); +const Rows = require('./rows.js'); +const Values = require('./values.js'); +const ExtLibs = require('./extlibs.js'); +const RESTServerProperties = require('./rest-server-properties.js'); +const Transactions = require('./transactions.js'); +const Transforms = require('./transforms.js'); +const ResourcesConfig = require('./resources-config.js'); +const ResourcesExec = require('./resources-exec.js'); +const serverExec = require('./server-exec.js'); + +const queryBuilder = require('./query-builder.js'); +const patchBuilder = require('./patch-builder.js'); +const valuesBuilder = require('./values-builder.js'); +const planBuilder = require('./plan-builder.js'); +const ctsQueryBuilder = require('./ctsquery-builder'); +const Operation = require('./operation.js'); +const requester = require('./requester.js'); +const internal = require('./internal.js'); const proxy = require('./endpoint-proxy.js'); const dns = require('dns'); @@ -181,9 +181,9 @@ ExtlibsWrapper.prototype.remove = function removeExtlibsWrapper() { ); }; ExtlibsWrapper.prototype.write = function writeExtlibsWrapper() { - var args = expandExtlibsWrapper.call(this, 'writing', mlutil.asArray.apply(null, arguments)); - var module = args[0]; - var ext = mlutil.extension(module); + const args = expandExtlibsWrapper.call(this, 'writing', mlutil.asArray.apply(null, arguments)); + const module = args[0]; + const ext = mlutil.extension(module); if (ext === null) { throw new Error(module+' module for '+this.name+' library must have an extension of .mjs, .sjs, or .xqy'); } @@ -205,7 +205,7 @@ ExtlibsWrapper.prototype.write = function writeExtlibsWrapper() { }; function expandExtlibsWrapper(action, args) { /*jshint validthis:true */ - var module = (args.length > 0) ? args[0] : null; + const module = (args.length > 0) ? args[0] : null; if (typeof module !== 'string' && !(module instanceof String)) { throw new Error('no module name for '+action+' '+this.name+' library'); } @@ -321,7 +321,7 @@ function MarkLogicClient(connectionParams) { */ this.values = new Values(this); - var configExtlibs = new ExtLibs(this); + const configExtlibs = new ExtLibs(this); /** * Provides access to namespaces that configure the REST server for the client. @@ -381,7 +381,7 @@ MarkLogicClient.prototype.getConnectionParams = function getConnectionParams() { */ MarkLogicClient.prototype.checkConnection = function checkConnection() { const requestOptions = mlutil.newRequestOptions(this.connectionParams, '/v1/ping', 'HEAD'); - var operation = new Operation( + const operation = new Operation( 'test operation', this, requestOptions, 'empty', 'empty' ); operation.statusCodeValidator = function testStatusCodes(statusCode, response){ @@ -391,7 +391,7 @@ MarkLogicClient.prototype.checkConnection = function checkConnection() { return null; }; operation.outputTransform = function addOutputTransform() { - var content = null; + let content = null; if(this.responseStatusCode <300) { content = {connected: true}; } else { @@ -426,24 +426,24 @@ MarkLogicClient.prototype.invoke = serverExec.serverInvoke; * a success callback receiving an array of uri strings for the created documents. */ MarkLogicClient.prototype.createCollection = function createCollection() { - var argLen = arguments.length; + const argLen = arguments.length; if (argLen < 2) { throw new Error('must specify both a collection and content objects for document create'); } - var collection = arguments[0]; + const collection = arguments[0]; if (typeof collection !== 'string' && !(collection instanceof String)) { throw new Error('must specify at least one collection for document create'); } - var contentArray = arguments[1]; - var i = 0; + let contentArray = arguments[1]; + let i = 0; if (!Array.isArray(contentArray)) { i = 1; contentArray = arguments; } - var documentList = []; + const documentList = []; for (; i < contentArray.length; i++) { documentList.push({ collections: collection, @@ -567,25 +567,25 @@ MarkLogicClient.prototype.removeCollection = function removeCollectionClient(col * a success callback receiving an array of uri strings for the written documents. */ MarkLogicClient.prototype.writeCollection = function writeClient() { - var argLen = arguments.length; + const argLen = arguments.length; if (argLen < 2) { throw new Error('must specify both a collection and mapping object for quick document write'); } - var collection = arguments[0]; + const collection = arguments[0]; if (typeof collection !== 'string' && !(collection instanceof String)) { throw new Error('must specify at least one collection for quick document write'); } - var map = arguments[1]; - var uris = Object.keys(map); + const map = arguments[1]; + const uris = Object.keys(map); if (uris.length === 0) { throw new Error('must map at least one document uri to content for quick document write'); } - var documentList = []; - var uri = null; - var i = 0; + const documentList = []; + let uri = null; + let i = 0; for (; i < uris.length; i++) { uri = uris[i]; documentList.push({ @@ -616,14 +616,14 @@ MarkLogicClient.prototype.release = function releaseMarkLogicClient() { * must be provided as true for Bunyan (but not for Winston); defaults to false */ MarkLogicClient.prototype.setLogger = function setClientLogger() { - var argLen = arguments.length; + const argLen = arguments.length; if (argLen < 1) { throw new Error('must provide a logger as the first argument'); } - var arg = arguments[0]; + const arg = arguments[0]; if (typeof arg === 'string' || arg instanceof String) { - var logger = (argLen === 1) ? this.getLogger() : null; + const logger = (argLen === 1) ? this.getLogger() : null; if (logger instanceof mllog.ConsoleLogger) { logger.setLevel(arg); } else { @@ -639,7 +639,7 @@ MarkLogicClient.prototype.setLogger = function setClientLogger() { /** @ignore */ MarkLogicClient.prototype.getLogger = function getClientLogger() { - var logger = this.logger; + let logger = this.logger; if (logger == null) { logger = new mllog.ConsoleLogger(); @@ -663,7 +663,7 @@ MarkLogicClient.prototype.getLogger = function getClientLogger() { * @returns {Timestamp} - a Timestamp object. */ MarkLogicClient.prototype.createTimestamp = function databaseCreateTimestamp(value) { - let ts = new mlutil.Timestamp(value ? value : null); + const ts = new mlutil.Timestamp(value ? value : null); return ts; }; @@ -711,20 +711,20 @@ MarkLogicClient.prototype.endpointCaller =function endpointCaller(endpointDeclar }; function initClient(client, inputParams) { - var connectionParams = {}; - var isSSL = (inputParams.ssl == null) ? false : inputParams.ssl; + const connectionParams = {}; + let isSSL = (inputParams.ssl == null) ? false : inputParams.ssl; if(inputParams.authType && inputParams.authType.toString().toLowerCase() === 'cloud' && !isSSL){ isSSL = true; } - var keys = ['host', 'port', 'database', 'user', 'password', 'authType', 'token', 'basePath','apiKey','accessTokenDuration', + const keys = ['host', 'port', 'database', 'user', 'password', 'authType', 'token', 'basePath','apiKey','accessTokenDuration', 'enableGzippedResponses', 'oauthToken']; if(isSSL) { keys.push('ca', 'cert', 'ciphers', 'clientCertEngine', 'crl', 'dhparam', 'ecdhCurve', 'honorCipherOrder', 'key', 'passphrase', 'pfx', 'rejectUnauthorized', 'secureOptions', 'secureProtocol', 'servername', 'sessionIdContext', 'highWaterMark'); } - for (var i=0; i < keys.length; i++) { - var key = keys[i]; - var value = inputParams[key]; + for (let i=0; i < keys.length; i++) { + const key = keys[i]; + const value = inputParams[key]; if (value != null) { connectionParams[key] = value; } else if (key === 'host') { @@ -771,8 +771,8 @@ function initClient(client, inputParams) { connectionParams.user+':'+connectionParams.password; } - var noAgent = (inputParams.agent == null); - var agentOptions = noAgent ? { + const noAgent = (inputParams.agent == null); + const agentOptions = noAgent ? { keepAlive: true } : null; if (isSSL) { @@ -799,7 +799,7 @@ function initClient(client, inputParams) { client.internal = new internal.InternalClass(client); } function releaseClient(client) { - var agent = client.connectionParams.agent; + const agent = client.connectionParams.agent; if (agent == null){ return; } diff --git a/lib/mllog.js b/lib/mllog.js index e1fd65f1..6e013356 100644 --- a/lib/mllog.js +++ b/lib/mllog.js @@ -2,7 +2,7 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var util = require('util'); +const util = require('util'); diff --git a/lib/mlutil.js b/lib/mlutil.js index 46d1b03f..e5b453be 100644 --- a/lib/mlutil.js +++ b/lib/mlutil.js @@ -2,13 +2,13 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var util = require('util'); +const util = require('util'); -var multipartBoundary = 'MLBOUND_' + Date.UTC(2014,12,31); +const multipartBoundary = 'MLBOUND_' + Date.UTC(2014,12,31); // Normalize arguments by returning them as an array. function asArray() { - var argLen = arguments.length; + const argLen = arguments.length; switch(argLen) { // No arguments returns an empty array case 0: @@ -24,22 +24,22 @@ function asArray() { // List of arguments returns an array with arguments as elements default: var args = new Array(argLen); - for(var i=0; i < argLen; ++i) { + for(let i=0; i < argLen; ++i) { args[i] = arguments[i]; } return args; } } function copyProperties(source, target, srcKeys) { - var dest = (arguments.length > 1) ? target : {}; - var isNamed = Array.isArray(srcKeys); - var keys = isNamed ? srcKeys : Object.keys(source); + const dest = (arguments.length > 1) ? target : {}; + const isNamed = Array.isArray(srcKeys); + const keys = isNamed ? srcKeys : Object.keys(source); // for...in not currently optimized by v8 - var keyLen = keys.length; - for (var i=0; i < keyLen; i++) { - var key = keys[i]; - var val = source[key]; + const keyLen = keys.length; + for (let i=0; i < keyLen; i++) { + const key = keys[i]; + const val = source[key]; if (!isNamed || (val !== void 0 && val !== null)) { dest[key] = val; } @@ -64,7 +64,7 @@ function appendItem(object, key, value) { return; } - var array = object[key]; + const array = object[key]; if (array === void 0) { object[key] = [value]; } else { @@ -86,8 +86,8 @@ function MarkLogicError(firstArg, secondArg) { return new MarkLogicError(firstArg, secondArg); } - var name = null; - var message = null; + let name = null; + let message = null; if (firstArg == null) { message = 'unknown error'; } else if (secondArg == null) { @@ -108,8 +108,8 @@ function MarkLogicError(firstArg, secondArg) { util.inherits(MarkLogicError, Error); function callbackOn(object, method) { - var self = object; - var func = method; + const self = object; + const func = method; return function callBackMethod() { return func.apply(self, arguments); }; @@ -127,8 +127,8 @@ function endpointTransform(transform) { var endpointParam = 'transform='+encodeURIComponent(transform[0]); var transformParams = transform[1]; var transformKeys = Object.keys(transformParams); - for (var i=0; i < transformKeys.length; i++) { - var transformKey = transformKeys[i]; + for (let i=0; i < transformKeys.length; i++) { + const transformKey = transformKeys[i]; endpointParam += '&trans:'+encodeURIComponent(transformKey)+'='+ encodeURIComponent(transformParams[transformKey]); } @@ -142,7 +142,7 @@ function endpointTransform(transform) { function newRequestOptions(connectionParams, endpoint, method) { const requestOptions = copyProperties(connectionParams); - let database = connectionParams.database; + const database = connectionParams.database; if(connectionParams.basePath) { const basePath = connectionParams.basePath.toString(); let fixedBasePath = (connectionParams.host.toString().endsWith('/') && basePath.startsWith('/')) ? basePath.substring(1):basePath; @@ -166,14 +166,14 @@ function newRequestOptions(connectionParams, endpoint, method) { } function extension(filename) { - var extStart = filename.lastIndexOf('.') + 1; + const extStart = filename.lastIndexOf('.') + 1; if (extStart === 0 || extStart === filename.length) { return null; } return filename.substring(extStart); } function rootname(filename) { - var extStart = filename.lastIndexOf('.'); + const extStart = filename.lastIndexOf('.'); if (extStart === 0 || extStart === filename.length) { return null; } @@ -187,7 +187,7 @@ function identify(arg, withValues) { if (arg === null) { return 'null'; } - var typed = typeof arg; + const typed = typeof arg; switch(typed) { case 'boolean' : return withValues ? typed+' '+arg : typed; case 'function' : return typed; @@ -296,7 +296,7 @@ function Transaction(id, cookies) { this.txid = id; if (Array.isArray(cookies) && cookies.length > 0) { - for (var i=0; i < cookies.length; i++) { + for (let i=0; i < cookies.length; i++) { cookies[i] = cookies[i].replace(/;\s*expires\s*=[^;]+(;|$)/i, '$1'); } this.cookies = cookies; @@ -329,9 +329,9 @@ function getTxidParam(txid, action) { } function addTxidHeaders(requestOptions, txid) { if (txid instanceof Transaction) { - var cookies = txid.cookies; + const cookies = txid.cookies; if (cookies != null) { - var headers = requestOptions.headers; + const headers = requestOptions.headers; if (headers != null) { headers.cookie = cookies; } else { @@ -358,22 +358,22 @@ function Timestamp(value) { } // Slice mode can be 'array' or 'legacy' -var sliceMode = 'array'; +let sliceMode = 'array'; function setSliceMode(mode) { sliceMode = mode; } function makeSliceClause(variant, args) { - var argLen = args.length; + const argLen = args.length; - var sliceClause = {}; + const sliceClause = {}; - var firstArg = null; - var secondArg = null; + let firstArg = null; + let secondArg = null; - var argMax = Math.min(argLen, ((variant === 'query') ? 5 : 3)); - var arg = null; - for (var i=0; i < argMax; i++) { + const argMax = Math.min(argLen, ((variant === 'query') ? 5 : 3)); + let arg = null; + for (let i=0; i < argMax; i++) { arg = args[i]; if (typeof arg === 'number' || arg instanceof Number) { switch(i) { @@ -410,7 +410,7 @@ function makeSliceClause(variant, args) { } if (firstArg !== null && secondArg !== 0) { - var pageStart = (sliceMode === 'legacy') ? firstArg : firstArg + 1; + const pageStart = (sliceMode === 'legacy') ? firstArg : firstArg + 1; if (pageStart === 0 && secondArg === null) { sliceClause['page-length'] = 0; } else { diff --git a/lib/operation.js b/lib/operation.js index 68ab3066..9f439202 100644 --- a/lib/operation.js +++ b/lib/operation.js @@ -3,7 +3,7 @@ */ 'use strict'; -var mlutil = require('./mlutil.js'); +const mlutil = require('./mlutil.js'); function Operation(name, client, options, requestType, responseType) { if (!(this instanceof Operation)) { @@ -48,11 +48,11 @@ Operation.prototype.STREAM_MODES_CHUNKED_OBJECT_SEQUENCE = Operation.prototype.emptyHeaderData = function emptyHeaderData( response ) { - var operation = this; + const operation = this; - var outputTransform = operation.outputTransform; + const outputTransform = operation.outputTransform; if (outputTransform != null) { - var responseHeaders = operation.responseHeaders; + let responseHeaders = operation.responseHeaders; if (responseHeaders == null) { operation.copyResponseHeaders(response); responseHeaders = operation.responseHeaders; @@ -66,16 +66,16 @@ Operation.prototype.emptyHeaderData = function emptyHeaderData( return null; }; Operation.prototype.collectBodyObject = function collectBodyObject(data) { - var operation = this; + const operation = this; - var outputTransform = operation.outputTransform; - var hasOutputTransform = (outputTransform != null); + const outputTransform = operation.outputTransform; + const hasOutputTransform = (outputTransform != null); - var headers = operation.responseHeaders; + const headers = operation.responseHeaders; - var bodyObject = mlutil.unmarshal(headers.format, data); + let bodyObject = mlutil.unmarshal(headers.format, data); if (bodyObject !== null) { - var subdata = operation.subdata; + const subdata = operation.subdata; if (Array.isArray(subdata)) { bodyObject = projectData(bodyObject, subdata, 0); } @@ -98,25 +98,25 @@ Operation.prototype.collectBodyObject = function collectBodyObject(data) { Operation.prototype.makeObject = function makeObject( data, rawHeaderQueue ) { - var operation = this; + const operation = this; - var outputTransform = operation.outputTransform; - var partObject = null; + const outputTransform = operation.outputTransform; + let partObject = null; // Get corresponding multipart header for part - var partRawHeaders = rawHeaderQueue.pollFirst(); - var partHeaders = parsePartHeaders(partRawHeaders); - var partUri = partHeaders.uri; + const partRawHeaders = rawHeaderQueue.pollFirst(); + const partHeaders = parsePartHeaders(partRawHeaders); + const partUri = partHeaders.uri; - var isInline = (partUri == null && !partHeaders.kind); - var isMetadata = ( + const isInline = (partUri == null && !partHeaders.kind); + const isMetadata = ( !isInline && (partHeaders.category != null) && partHeaders.category !== 'content' ); // Convert buffer data to object - var partData = mlutil.unmarshal(partHeaders.format, data); + const partData = mlutil.unmarshal(partHeaders.format, data); // Inline case if (isInline) { @@ -135,7 +135,7 @@ Operation.prototype.makeObject = function makeObject( else if (isMetadata) { operation.logger.debug('parsed metadata for %s', partUri); if (this.nextMetadataBuffer !== null) { - var metadataHeaders = this.nextMetadataBuffer[0]; + const metadataHeaders = this.nextMetadataBuffer[0]; mlutil.copyProperties(this.nextMetadataBuffer[1], metadataHeaders); partObject = metadataHeaders; } @@ -156,7 +156,7 @@ Operation.prototype.makeObject = function makeObject( if (partObject !== null) { // Subdata processing (poor man's XPath) - var subdata = operation.subdata; + const subdata = operation.subdata; if (Array.isArray(subdata)) { partObject = projectData(partObject, subdata, 0); } @@ -171,16 +171,16 @@ Operation.prototype.makeObject = function makeObject( return partObject; }; Operation.prototype.dispatchError = function dispatchError(error) { - var operation = this; + const operation = this; - var input = + const input = (error == null) ? operation.makeError('unknown error') : (typeof error === 'string' || error instanceof String) ? operation.makeError(error) : error; - var outputStream = operation.outputStream; + const outputStream = operation.outputStream; if (outputStream != null) { - var errorListeners = outputStream.listeners('error'); + const errorListeners = outputStream.listeners('error'); if (Array.isArray(errorListeners) && errorListeners.length > 0) { outputStream.emit('error', input); } else { @@ -193,7 +193,7 @@ Operation.prototype.dispatchError = function dispatchError(error) { } }; Operation.prototype.logError = function logError(error) { - var operation = this; + const operation = this; if (error.body == null) { operation.logger.error(error.message); @@ -204,13 +204,13 @@ Operation.prototype.logError = function logError(error) { } }; Operation.prototype.makeError = function makeError(message) { - var operation = this; + const operation = this; - var operationName = operation.name; - var operationMsg = (operationName === void 0) ? message : + const operationName = operation.name; + let operationMsg = (operationName === void 0) ? message : (operationName+': '+message); - var errorTransform = operation.errorTransform; + const errorTransform = operation.errorTransform; const responsePath = operation.options.path; const subMsg = (responsePath && responsePath.toString().includes('?'))? responsePath.toString().substring(0,responsePath.toString().indexOf('?') ): @@ -222,13 +222,13 @@ Operation.prototype.makeError = function makeError(message) { ); }; Operation.prototype.copyResponseHeaders = function copyResponseHeaders(response) { - var operation = this; + const operation = this; - var responseHeaders = response.headers; + const responseHeaders = response.headers; - var contentType = trimContentType(responseHeaders['content-type']); + const contentType = trimContentType(responseHeaders['content-type']); - var format = responseHeaders['vnd.marklogic.document-format']; + let format = responseHeaders['vnd.marklogic.document-format']; if ((format == null) && contentType !== null) { format = contentTypeToFormat(contentType); } @@ -267,8 +267,8 @@ function OperationHeaders( if (versionId == null) { this.versionId = null; } else { - var firstChar = versionId.charAt(0); - var lastChar = versionId.charAt(versionId.length - 1); + const firstChar = versionId.charAt(0); + const lastChar = versionId.charAt(versionId.length - 1); this.versionId = ( (firstChar === '"' && lastChar === '"') || (firstChar === '\'' && lastChar === '\'') @@ -283,7 +283,7 @@ function trimContentType(contentType) { if (contentType == null) { return null; } - var semicolonPos = contentType.indexOf(';'); + const semicolonPos = contentType.indexOf(';'); return (semicolonPos > 0) ? contentType.substring(0, semicolonPos) : contentType; } @@ -292,7 +292,7 @@ function contentTypeToFormat(contentType) { return null; } - var fields = contentType.split(/[\/+]/); + const fields = contentType.split(/[\/+]/); switch(fields[0]) { case 'application': switch(fields[fields.length - 1]) { @@ -326,21 +326,21 @@ function contentTypeToFormat(contentType) { } function parsePartHeaders(headers) { - var partHeaders = {}; + const partHeaders = {}; - var contentDispositionArray = headers['content-disposition']; + const contentDispositionArray = headers['content-disposition']; if (Array.isArray(contentDispositionArray) && contentDispositionArray.length > 0) { - var contentDisposition = contentDispositionArray[0]; + let contentDisposition = contentDispositionArray[0]; if (contentDisposition.substring(contentDisposition.length) !== ';') { contentDisposition += ';'; } - var tokens = contentDisposition.match(/"[^"]*"|;|=|[^";=\s]+/g); - var key = null; - var value = null; - for (var i=0; i < tokens.length; i++) { - var token = tokens[i]; + const tokens = contentDisposition.match(/"[^"]*"|;|=|[^";=\s]+/g); + let key = null; + let value = null; + for (let i=0; i < tokens.length; i++) { + const token = tokens[i]; switch(token) { case ';': if (key) { @@ -350,7 +350,7 @@ function parsePartHeaders(headers) { value = value.substring(1,value.length - 1); } - var currentValue = partHeaders[key]; + const currentValue = partHeaders[key]; if (!currentValue) { partHeaders[key] = value; } else if (currentValue instanceof Array) { @@ -378,8 +378,8 @@ function parsePartHeaders(headers) { } } - var contentTypeArray = headers['content-type']; - var contentType = null; + const contentTypeArray = headers['content-type']; + let contentType = null; if (Array.isArray(contentTypeArray) && contentTypeArray.length > 0) { contentType = trimContentType(contentTypeArray[0]); partHeaders.contentType = contentType; @@ -389,12 +389,12 @@ function parsePartHeaders(headers) { partHeaders.format = contentTypeToFormat(contentType); } - var contentLengthArray = headers['content-length']; + const contentLengthArray = headers['content-length']; if (Array.isArray(contentLengthArray) && contentLengthArray.length > 0) { partHeaders.contentLength = contentLengthArray[0]; } - var contentIdArray = headers['content-id']; + const contentIdArray = headers['content-id']; if (Array.isArray(contentIdArray) && contentIdArray.length > 0) { partHeaders.contentId = contentIdArray[0].slice(1, -1); } @@ -407,19 +407,19 @@ function projectData(data, subdata, i) { return data; } - var key = subdata[i]; + const key = subdata[i]; if (!Array.isArray(data)) { - var nextData = data[key]; + const nextData = data[key]; if (nextData == null) { return data; } return projectData(nextData, subdata, i + 1); } - var newData = []; - for (var j=0; j < data.length; j++) { - var currItem = data[j]; - var nextValue = currItem[key]; + const newData = []; + for (let j=0; j < data.length; j++) { + const currItem = data[j]; + const nextValue = currItem[key]; newData.push( (nextValue == null) ? currItem : projectData(nextValue, subdata, i + 1) diff --git a/lib/optional.js b/lib/optional.js index 2c66000e..228c9234 100644 --- a/lib/optional.js +++ b/lib/optional.js @@ -14,7 +14,7 @@ function library(libname) { } } function libraryProperty(libname, propertyName) { - var lib = library(libname); + const lib = library(libname); if (lib == null) { return null; } diff --git a/lib/patch-builder.js b/lib/patch-builder.js index 673ef102..f70b78a1 100644 --- a/lib/patch-builder.js +++ b/lib/patch-builder.js @@ -4,9 +4,9 @@ 'use strict'; -var mlutil = require('./mlutil.js'); +const mlutil = require('./mlutil.js'); -var qb = require('./query-builder.js'); +const qb = require('./query-builder.js'); /** * A helper for building the definition of a document patch. The helper is @@ -33,12 +33,12 @@ var qb = require('./query-builder.js'); * @returns {patchBuilder.PatchOperation} a patch operation */ function remove() { - var select = null; - var cardinality = null; + let select = null; + let cardinality = null; - var argLen = arguments.length; - for (var i=0; i < argLen; i++) { - var arg = arguments[i]; + const argLen = arguments.length; + for (let i=0; i < argLen; i++) { + const arg = arguments[i]; if (i === 0) { select = arg; continue; @@ -54,7 +54,7 @@ function remove() { throw new Error('remove takes select and optional cardinality'); } - var operation = { + const operation = { select: select }; if (cardinality !== null) { @@ -80,14 +80,14 @@ function remove() { * @returns {patchBuilder.PatchOperation} a patch operation */ function insert() { - var context = null; - var position = null; - var content = void 0; - var cardinality = null; - - var argLen = arguments.length; - for (var i=0; i < argLen; i++) { - var arg = arguments[i]; + let context = null; + let position = null; + let content = void 0; + let cardinality = null; + + const argLen = arguments.length; + for (let i=0; i < argLen; i++) { + const arg = arguments[i]; if (i === 0) { context = arg; continue; @@ -96,7 +96,7 @@ function insert() { content = arg; continue; } - var isString = (typeof arg === 'string' || arg instanceof String); + const isString = (typeof arg === 'string' || arg instanceof String); if (isString) { if (position === null && /^(before|after|last-child)$/.test(arg)) { position = arg; @@ -120,7 +120,7 @@ function insert() { ); } - var operation = { + const operation = { context: context, position: position, content: content @@ -158,11 +158,11 @@ function library(module) { ); } - var rootname = mlutil.rootname(module); + const rootname = mlutil.rootname(module); if (rootname === null) { throw new Error('library must have an extension of .sjs or .xqy'); } - var extension = module.substring((module.lastIndexOf('.')+1), module.length); + const extension = module.substring((module.lastIndexOf('.')+1), module.length); if(extension === 'sjs') { return {'replace-library':{ @@ -195,9 +195,9 @@ function library(module) { * @returns {patchBuilder.ApplyDefinition} the specification for applying a function */ function apply() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const argLen = args.length; switch(argLen) { case 0: throw new Error('no name for function to apply'); @@ -412,14 +412,14 @@ function replaceRegex(match, replace, flags) { * @returns {patchBuilder.PatchOperation} a patch operation */ function replace() { - var select = null; - var content = void 0; - var cardinality = null; - var apply = null; - - var argLen = arguments.length; - for (var i=0; i < argLen; i++) { - var arg = arguments[i]; + let select = null; + let content = void 0; + let cardinality = null; + let apply = null; + + const argLen = arguments.length; + for (let i=0; i < argLen; i++) { + const arg = arguments[i]; if (i === 0) { select = arg; continue; @@ -428,7 +428,7 @@ function replace() { content = arg; continue; } - var isString = (typeof arg === 'string' || arg instanceof String); + const isString = (typeof arg === 'string' || arg instanceof String); if (isString && cardinality === null && /^[?.*+]$/.test(arg)) { cardinality = arg; continue; @@ -455,7 +455,7 @@ function replace() { ); } - var operation = { + const operation = { select: select, content: content }; @@ -493,16 +493,16 @@ function replace() { * @returns {patchBuilder.PatchOperation} a patch operation */ function replaceInsert() { - var select = null; - var context = null; - var position = null; - var content = void 0; - var cardinality = null; - var apply = null; - - var argLen = arguments.length; - for (var i=0; i < argLen; i++) { - var arg = arguments[i]; + let select = null; + let context = null; + let position = null; + let content = void 0; + let cardinality = null; + let apply = null; + + const argLen = arguments.length; + for (let i=0; i < argLen; i++) { + const arg = arguments[i]; if (i === 0) { select = arg; continue; @@ -515,7 +515,7 @@ function replaceInsert() { content = arg; continue; } - var isString = (typeof arg === 'string' || arg instanceof String); + const isString = (typeof arg === 'string' || arg instanceof String); if (isString) { if (position === null && /^(before|after|last-child)$/.test(arg)) { position = arg; @@ -547,7 +547,7 @@ function replaceInsert() { ); } - var operation = { + const operation = { select: select, context: context, position: position, @@ -583,7 +583,7 @@ function replaceInsert() { * @returns {patchBuilder.PathLanguageParam} the specification for the path language */ function pathLanguage() { - var pathlang = (arguments.length < 1) ? null : arguments[0]; + const pathlang = (arguments.length < 1) ? null : arguments[0]; if (pathlang !== 'jsonpath' && pathlang !== 'xpath') { throw new Error( 'pathLanguage takes a path language of xpath or jsonpath' @@ -642,7 +642,7 @@ function removeCollection(collection) { * @returns {patchBuilder.PatchOperation} a patch operation */ function addPermission() { - var permission = getPermission( + const permission = getPermission( mlutil.asArray.apply(null, arguments) ); if (permission === null) { @@ -662,7 +662,7 @@ function addPermission() { * capabilities from the insert|update|read|execute enumeration */ function replacePermission() { - var permission = getPermission( + const permission = getPermission( mlutil.asArray.apply(null, arguments) ); if (permission === null) { @@ -688,13 +688,13 @@ function removePermission(roleName) { } /** @ignore */ function getPermission(args) { - var argLen = args.length; + const argLen = args.length; - var roleName = null; - var capabilities = null; - var isObject = false; + let roleName = null; + let capabilities = null; + let isObject = false; - var first = (argLen === 0) ? null : args[0]; + const first = (argLen === 0) ? null : args[0]; if (first !== null) { if (args.length > 1 && typeof first === 'string') { roleName = first; @@ -713,10 +713,10 @@ function getPermission(args) { return null; } - var check = {execute:true, insert:true, read:true, update:true}; + const check = {execute:true, insert:true, read:true, update:true}; if (Array.isArray(capabilities)) { - var max = capabilities.length; - for (var i=0; i < max; i++) { + const max = capabilities.length; + for (let i=0; i < max; i++) { if (!check[capabilities[i]]) { return null; } @@ -754,7 +754,7 @@ function addProperty(name, value) { if (typeof name !== 'string' || value == null) { throw new Error('properties.add() takes a string name and a value'); } - var prop = {}; + const prop = {}; prop[name] = value; return insert('/object-node("properties")', 'last-child', prop); } @@ -822,7 +822,7 @@ function addMetadataValue(name, value) { if (typeof name !== 'string' || typeof value !== 'string' ) { throw new Error('metadataValues.add() takes a string name and string value'); } - var metaVal = {}; + const metaVal = {}; metaVal[name] = value; return insert('/object-node("metadataValues")', 'last-child', metaVal); } diff --git a/lib/plan-builder-base.js b/lib/plan-builder-base.js index 70e3a791..cbeb9149 100644 --- a/lib/plan-builder-base.js +++ b/lib/plan-builder-base.js @@ -261,11 +261,11 @@ function castArg(arg, funcName, paramName, argPos, paramTypes) { ); } if(key === 'permissions'){ - let permissionValue = []; + const permissionValue = []; for(let i=0; i' : 'GT', @@ -17,7 +17,7 @@ var comparisons = { '=' : 'EQ', '!=' : 'NE' }; -var datatypes = { +const datatypes = { 'xs:anyURI': 'xs:anyURI', 'xs:date': 'xs:date', 'xs:dateTime': 'xs:dateTime', @@ -44,7 +44,7 @@ function asIndex(index) { } /** @ignore */ function addIndex(query, index, isContainer) { - var containerOnly = (isContainer || false); + const containerOnly = (isContainer || false); if (index instanceof JSONPropertyDef) { query['json-property'] = index['json-property']; } else if (index instanceof ElementDef) { @@ -111,12 +111,12 @@ function checkQueryArray(queryArray) { return queryArray; } - var max = queryArray.length; + const max = queryArray.length; if (max === 0) { return queryArray; } - var i = 0; + let i = 0; for (; i < max; i++) { checkQuery(queryArray[i]); } @@ -170,11 +170,11 @@ function ConstraintDef() { * @returns {queryBuilder.Query} a composable query */ function and() { - var args = mlutil.asArray.apply(null, arguments); - var queries = []; - var ordered = null; - var arg = null; - for (var i=0; i < args.length; i++) { + const args = mlutil.asArray.apply(null, arguments); + const queries = []; + let ordered = null; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (ordered === null) { if (arg instanceof OrderedDef) { @@ -260,7 +260,7 @@ function QueryListDef(queries, ordered, weight, distance) { * @returns {queryBuilder.Query} a composable query */ function andNot() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing positive and negative queries'); @@ -316,7 +316,7 @@ function PositiveNegativeDef(positive, negative) { * @returns {queryBuilder.IndexedName} an indexed name for specifying a query */ function attribute() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing element and attribute'); @@ -393,7 +393,7 @@ function AttributeDef(elemQName, attrQName) { * @returns {queryBuilder.Query} a composable query */ function boost() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing matching and boosting queries'); @@ -451,7 +451,7 @@ function MatchingBoostingDef(matching, boosting) { * @returns {queryBuilder.Region} the region criteria for a geospatial query */ function box() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing four corners for box'); @@ -497,8 +497,8 @@ function BoxRegionDef(box) { * @returns {queryBuilder.Region} the region criteria for a geospatial query */ function circle() { - var args = mlutil.asArray.apply(null, arguments); - var arg = null; + const args = mlutil.asArray.apply(null, arguments); + let arg = null; switch(args.length) { case 0: throw new Error('missing radius and center for circle'); @@ -582,18 +582,18 @@ function CircleDef(radius, center) { * @returns {queryBuilder.Query} a composable query */ function collection() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen === 0) { return new CollectionConstraintDef(null, null, null); } - var constraintName = null; - var suggestOptions = null; - var prefix = null; - var arg = null; - var i = 0; + let constraintName = null; + let suggestOptions = null; + let prefix = null; + let arg = null; + let i = 0; for (; i < argLen; i++) { arg = args[i]; if (constraintName === null && arg instanceof BindDef) { @@ -699,18 +699,18 @@ util.inherits(CollectionQueryDef, QueryDef); * @returns {queryBuilder.Query} a composable query */ function lsqtQuery() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 1) { throw new Error('no temporal collection for lsqt query'); } - var temporalCollection = null; - var weight = null; - var timestamp = null; - var temporalOptions = null; - var arg = null; - for (var i=0; i < args.length; i++) { + let temporalCollection = null; + let weight = null; + let timestamp = null; + let temporalOptions = null; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (i === 0) { if (typeof arg !== 'string' && !(arg instanceof String)) { @@ -810,17 +810,17 @@ function LSQTQueryDef(temporalCollection, weight, timestamp, temporalOptions) { * @returns {queryBuilder.Query} a composable query */ function scope() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 1) { throw new Error('element or property scope not specified'); } - var index = null; - var constraintName = null; - var fragmentScope = null; - var query = null; - var arg = null; - for (var i=0; i < args.length; i++) { + let index = null; + let constraintName = null; + let fragmentScope = null; + let query = null; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (i === 0) { index = asIndex(arg); @@ -918,9 +918,9 @@ function ContainedDef(index, fragmentScope, query) { this['fragment-scope'] = fragmentScope; } if (query != null) { - var queryKeys = Object.keys(query); - var queryKey = null; - for (var i=0; i < queryKeys.length; i++) { + const queryKeys = Object.keys(query); + let queryKey = null; + for (let i=0; i < queryKeys.length; i++) { queryKey = queryKeys[i]; this[queryKey] = query[queryKey]; } @@ -943,7 +943,7 @@ function ContainedDef(index, fragmentScope, query) { * @returns {queryBuilder.DatatypeParam} a datatype specification */ function datatype() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing datatype'); @@ -987,12 +987,12 @@ function DatatypeDef(datatype, collation) { * @returns {queryBuilder.Query} a composable query */ function directory() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); - var uris = []; - var infinite = null; - var arg = null; - for (var i=0; i < args.length; i++) { + const uris = []; + let infinite = null; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (infinite === null && (typeof arg === 'boolean')) { infinite = arg; @@ -1105,7 +1105,7 @@ util.inherits(DocumentFragmentDef, QueryDef); * @returns {queryBuilder.IndexedName} an indexed name for specifying a query */ function element() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing element name'); @@ -1144,7 +1144,7 @@ function ElementDef(qname) { * @returns {queryBuilder.IndexedName} an indexed name for specifying a query */ function field() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing field name'); @@ -1239,18 +1239,18 @@ function FragmentScopeDef(scope) { * @returns {queryBuilder.GeoLocation} the specification for the geospatial locations */ function geoAttributePair() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 2) { throw new Error('need at least two parameters for geospatial attribute pair query'); } - var location = {}; + const location = {}; - var keys = ['parent', 'lat', 'lon']; - var iArg=0; - for (var i=0; i < keys.length; i++) { - var key = keys[i]; - var arg = args[iArg++]; + const keys = ['parent', 'lat', 'lon']; + let iArg=0; + for (let i=0; i < keys.length; i++) { + const key = keys[i]; + const arg = args[iArg++]; if (arg instanceof QNameDef) { location[key] = arg; } else if (typeof arg === 'string' || arg instanceof String) { @@ -1284,19 +1284,19 @@ function geoAttributePair() { * @returns {queryBuilder.GeoLocation} the specification for the geospatial locations */ function geoElement() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 1) { throw new Error('need at least one parameter for geospatial element query'); } - var location = {}; + const location = {}; // TODO: elementName - var maxIndex = Math.min(argLen, 2); - var elemName = null; - var arg = null; - var i=0; + const maxIndex = Math.min(argLen, 2); + let elemName = null; + let arg = null; + let i=0; while (i < maxIndex) { arg = args[i]; if (arg instanceof QNameDef) { @@ -1336,17 +1336,17 @@ function geoElement() { * @returns {queryBuilder.GeoLocation} the specification for the geospatial locations */ function geoElementPair() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 2) { throw new Error('need at least two parameters for geospatial element pair query'); } - var location = {}; + const location = {}; - var keys = ['parent', 'lat', 'lon']; - var key = null; - var arg = null; - for (var i=0; i < keys.length; i++) { + const keys = ['parent', 'lat', 'lon']; + let key = null; + let arg = null; + for (let i=0; i < keys.length; i++) { key = keys[i]; arg = args[i]; if (arg instanceof QNameDef) { @@ -1375,18 +1375,18 @@ function geoElementPair() { * @returns {queryBuilder.GeoLocation} the specification for the geospatial locations */ function geoProperty() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 1) { throw new Error('need at least one parameters for geospatial property query'); } - var location = {}; + const location = {}; - var maxIndex = Math.min(argLen, 2); - var propName = null; - var arg = null; - var i=0; + const maxIndex = Math.min(argLen, 2); + let propName = null; + let arg = null; + let i=0; while (i < maxIndex) { arg = args[i]; if (arg instanceof JSONPropertyDef) { @@ -1420,17 +1420,17 @@ function geoProperty() { * @returns {queryBuilder.GeoLocation} the specification for the geospatial locations */ function geoPropertyPair() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 2) { throw new Error('need at least two parameters for geospatial property pair query'); } - var location = {}; + const location = {}; - var keys = ['parent-property', 'lat-property', 'lon-property']; - var key = null; - var arg = null; - for (var i=0; i < keys.length; i++) { + const keys = ['parent-property', 'lat-property', 'lon-property']; + let key = null; + let arg = null; + for (let i=0; i < keys.length; i++) { key = keys[i]; arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { @@ -1459,17 +1459,17 @@ function geoPropertyPair() { * @returns {queryBuilder.GeoLocation} the specification for the geospatial locations */ function geoPath() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 1) { throw new Error('need at least one parameter for geospatial path query'); } - var location = {}; + const location = {}; - var seekingPathIndex = true; - var firstArg = null; - var arg = null; - var i=0; + let seekingPathIndex = true; + let firstArg = null; + let arg = null; + let i=0; for (; i < args.length; i++) { arg = args[i]; if (i === 0) { @@ -1581,7 +1581,7 @@ function geospatialImpl(hasOperator, args) { throw new Error('need at least one parameter for geospatial query'); } - var isGeoLocationIndex = { + const isGeoLocationIndex = { 'geo-attr-pair': true, 'geo-elem': true, 'geo-elem-pair': true, @@ -1590,18 +1590,18 @@ function geospatialImpl(hasOperator, args) { 'geo-path': true }; - var query = null; - var variant = null; - var constraintName = null; - var suggestOptions = null; - var seekingWeight = true; - var seekingFragmentScope = true; - var seekingGeoOption = true; - var seekingRegion = true; - var seekingGeoOperator = true; - var firstKey = null; - var arg = null; - var i=0; + let query = null; + let variant = null; + let constraintName = null; + let suggestOptions = null; + let seekingWeight = true; + let seekingFragmentScope = true; + let seekingGeoOption = true; + let seekingRegion = true; + let seekingGeoOperator = true; + let firstKey = null; + let arg = null; + let i=0; for (; i < args.length; i++) { arg = args[i]; if (i === 0) { @@ -1742,13 +1742,13 @@ util.inherits(GeospatialConstraintDef, ConstraintDef); * @returns {queryBuilder.HeatMapParam} the buckets for a geospatial facet */ function heatmap() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 1) { throw new Error('no region or divisions for heat map'); } - var hmap = {}; + const hmap = {}; switch(argLen) { case 3: var first = args[0]; @@ -1768,14 +1768,14 @@ function heatmap() { } var keys = ['s', 'w', 'n', 'e']; - for (var i=0; i < keys.length; i++) { - var key = keys[i]; - var value = region[key]; + for (let i=0; i < keys.length; i++) { + const key = keys[i]; + let value = region[key]; if (value != null) { hmap[key] = value; continue; } else { - var altKey = null; + let altKey = null; switch(key) { case 's': altKey = 'south'; @@ -1857,7 +1857,7 @@ function GeoOptionsDef(options) { * @returns {queryBuilder.LatLon} a coordinate for a {queryBuilder.Region} */ function latlon() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing latitude and longitude for latlon coordinate'); @@ -1971,7 +1971,7 @@ function MinDistanceDef(distance) { * @returns {queryBuilder.Query} a composable query */ function near() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 1) { throw new Error('need at least a subquery for near query'); } @@ -1983,14 +1983,14 @@ function NearDef(args) { return new NearDef(args); } - var query = {}; - var subquery = []; - var seekingOrdered = true; - var seekingWeight = true; - var seekingDistance = true; - var seekingMinDistance = true; - var arg = null; - for (var i=0; i < args.length; i++) { + const query = {}; + const subquery = []; + let seekingOrdered = true; + let seekingWeight = true; + let seekingDistance = true; + let seekingMinDistance = true; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (seekingOrdered) { if (arg instanceof OrderedDef) { @@ -2069,7 +2069,7 @@ util.inherits(NotDef, QueryDef); * @returns {queryBuilder.Query} a composable query */ function notIn() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing positive and negative queries'); @@ -2163,7 +2163,7 @@ function OrderedDef(on) { * @returns {queryBuilder.IndexedName} an indexed name for specifying a query */ function pathIndex() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing path for path index identifier'); @@ -2214,7 +2214,7 @@ function PathDef(pathExpression, namespaces) { * @returns {queryBuilder.CoordSystem} a coordinate system identifier */ function coordSystem() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing identifier for coordinate system'); @@ -2249,7 +2249,7 @@ function CoordSystemDef(coordSystem) { * @returns {queryBuilder.Region} the region criteria for a geospatial query */ function point() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing latitude and longitude for point'); @@ -2287,11 +2287,11 @@ function PointRegionDef(point) { * @returns {queryBuilder.Region} the region criteria for a geospatial query */ function polygon() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); - var points = []; - var arg = null; - var i=0; + const points = []; + let arg = null; + let i=0; for (; i < args.length; i++) { arg = args[i]; if (arg instanceof PointRegionDef) { @@ -2357,7 +2357,7 @@ util.inherits(PropertiesFragmentDef, QueryDef); * @returns {queryBuilder.IndexedName} an indexed name for specifying a query */ function property() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing JSON property name'); @@ -2399,7 +2399,7 @@ function JSONPropertyDef(name) { * an element or attribute */ function qname() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('missing name for QName identifier'); @@ -2450,8 +2450,8 @@ function QNameDef(ns, name) { * for a {@link queryBuilder#periodRange} temporal query */ function period() { - var startDate = null; - var endDate = null; + let startDate = null; + let endDate = null; switch(arguments.length) { case 0: @@ -2512,15 +2512,15 @@ function PeriodDef(startDate, endDate) { * @returns {queryBuilder.Query} a composable query */ function periodCompare() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; - - var compareAxis1 = null; - var compareOperator = null; - var compareAxis2 = null; - var temporalOptions = null; - var arg = null; - for (var i=0; i < argLen; i++) { + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; + + let compareAxis1 = null; + let compareOperator = null; + let compareAxis2 = null; + let temporalOptions = null; + let arg = null; + for (let i=0; i < argLen; i++) { arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { if (compareAxis1 === null) { @@ -2612,15 +2612,15 @@ function PeriodCompareQueryDef( * @returns {queryBuilder.Query} a composable query */ function periodRange() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; - - var rangeAxis = null; - var rangeOperator = null; - var rangePeriod = null; - var temporalOptions = null; - var arg = null; - for (var i=0; i < argLen; i++) { + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; + + let rangeAxis = null; + let rangeOperator = null; + let rangePeriod = null; + let temporalOptions = null; + let arg = null; + for (let i=0; i < argLen; i++) { arg = args[i]; if (Array.isArray(arg) && arg.length > 0) { if (rangeAxis === null && (typeof arg[0] === 'string' || arg[0] instanceof String)) { @@ -2829,21 +2829,21 @@ function TemporalOptionsDef(options) { * @returns {queryBuilder.Query} a composable query */ function range() { - var args = mlutil.asArray.apply(null, arguments); - - var index = null; - var datatype = null; - var collation = null; - var weight = null; - var fragmentScope = null; - var rangeOptions = null; - var values = null; - var operator = null; - var suggestOptions = null; - var constraintName = null; - var defaultConstraint = null; - var arg = null; - for (var i=0; i < args.length; i++) { + const args = mlutil.asArray.apply(null, arguments); + + let index = null; + let datatype = null; + let collation = null; + let weight = null; + let fragmentScope = null; + let rangeOptions = null; + let values = null; + let operator = null; + let suggestOptions = null; + let constraintName = null; + let defaultConstraint = null; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (i === 0) { index = asIndex(arg); @@ -2887,11 +2887,11 @@ function range() { continue; } if ((datatype === null || operator === null) && (typeof arg === 'string' || arg instanceof String)) { - var testType = (datatype === null) ? datatypes[arg.trim()] : null; + const testType = (datatype === null) ? datatypes[arg.trim()] : null; if (testType != null) { datatype = testType; } else { - var testComp = (operator === null) ? comparisons[arg.trim()] : null; + const testComp = (operator === null) ? comparisons[arg.trim()] : null; if (testComp != null) { operator = testComp; } else if (values === null) { @@ -2909,7 +2909,7 @@ function range() { } } - var rangeDef = new RangeDef( + const rangeDef = new RangeDef( index, datatype, collation, operator, values, weight, rangeOptions, fragmentScope ); @@ -2933,7 +2933,7 @@ function range() { } } - var constraint = new RangeConstraintDef(constraintName, rangeDef, suggestOptions); + const constraint = new RangeConstraintDef(constraintName, rangeDef, suggestOptions); return (defaultConstraint !== true) ? constraint : new DefaultConstraintDef(constraint); @@ -2976,7 +2976,7 @@ function RangeDef( ); } - var hasOperator = (operator != null); + const hasOperator = (operator != null); if (index != null) { addIndex(this, index, false); @@ -3060,8 +3060,8 @@ function RangeOptionsDef(options) { * @returns {object} the coordinates for the box */ function southWestNorthEast() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen !== 4) { throw new Error('box must have four parameters: '+argLen); } @@ -3119,12 +3119,12 @@ function BoxDef(south, west, north, east) { * @returns {queryBuilder.Query} a composable query */ function term() { - var args = mlutil.asArray.apply(null, arguments); - var text = []; - var weight = null; - var termOptions = null; - var arg = null; - for (var i=0; i < args.length; i++) { + const args = mlutil.asArray.apply(null, arguments); + const text = []; + let weight = null; + let termOptions = null; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (weight === null && arg instanceof WeightDef) { weight = arg.weight; @@ -3165,7 +3165,7 @@ util.inherits(TermDef, QueryDef); * @returns {queryBuilder.Query} a composable query */ function before() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length === 0 || args[0] === null) { throw new Error('missing Timestamp'); } else if (args.length>1) { @@ -3196,7 +3196,7 @@ util.inherits(BeforeQueryDef, QueryDef); * @returns {queryBuilder.Query} a composable query */ function after() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length === 0 || args[0] === null) { throw new Error('missing Timestamp'); } else if (args.length>1) { @@ -3254,19 +3254,19 @@ function TermOptionsDef(options) { } /** @ignore */ function textQuery(variant, args) { - var isValue = (variant === 'value'); - - var index = null; - var text = null; - var weight = null; - var fragmentScope = null; - var termOptions = null; - var suggestOptions = null; - var constraintName = null; - var defaultConstraint = null; - var jsontype = null; - var arg = null; - for (var i=0; i < args.length; i++) { + const isValue = (variant === 'value'); + + let index = null; + let text = null; + let weight = null; + let fragmentScope = null; + let termOptions = null; + let suggestOptions = null; + let constraintName = null; + let defaultConstraint = null; + let jsontype = null; + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (i === 0) { index = asIndex(arg); @@ -3324,7 +3324,7 @@ function textQuery(variant, args) { null; } - var textDef = new TextDef( + const textDef = new TextDef( index, jsontype, text, weight, termOptions, fragmentScope ); @@ -3348,7 +3348,7 @@ function textQuery(variant, args) { } } - var constraint = isValue ? + const constraint = isValue ? new ValueConstraintDef(constraintName, textDef, suggestOptions) : new WordConstraintDef(constraintName, textDef, suggestOptions); @@ -3361,7 +3361,7 @@ function DefaultConstraintDef(constraintDef) { return new DefaultConstraintDef(constraintDef); } - this['default'] = constraintDef; + this.default = constraintDef; } /** @ignore */ function ValueConstraintDef(constraintName, textDef, suggestOptions) { @@ -3535,7 +3535,7 @@ function JSONTypeDef(type) { return new JSONTypeDef(type); } - var isJSONType = { + const isJSONType = { 'boolean': true, 'null': true, 'number': true, @@ -3627,18 +3627,18 @@ function word() { * @returns {queryBuilder.BuiltQuery} a built query */ function copyFromQueryBuilder(otherQueryBuilder) { - var qb = new QueryBuilder(); + const qb = new QueryBuilder(); if (otherQueryBuilder != null) { - var clauseKeys = [ + const clauseKeys = [ 'whereClause', 'calculateClause', 'orderByClause', 'sliceClause', 'withOptionsClause' ]; - var isString = (typeof otherQueryBuilder === 'string' || otherQueryBuilder instanceof String); - var other = isString ? + const isString = (typeof otherQueryBuilder === 'string' || otherQueryBuilder instanceof String); + const other = isString ? JSON.parse(otherQueryBuilder) : otherQueryBuilder; - for (var i=0; i < clauseKeys.length; i++){ - var key = clauseKeys[i]; - var value = other[key]; + for (let i=0; i < clauseKeys.length; i++){ + const key = clauseKeys[i]; + const value = other[key]; if (value != null) { // structuredClone instead of clone to avoid preserving prototype qb[key] = isString ? value : structuredClone(value); @@ -3670,19 +3670,19 @@ function copyFromQueryBuilder(otherQueryBuilder) { */ function where() { /*jshint validthis:true */ - var self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); + const self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; // TODO: if empty, clear the clause - var parsedQuery = null; - var fragmentScope = null; - var queries = null; + let parsedQuery = null; + let fragmentScope = null; + let queries = null; - var i=0; + let i=0; - var arg = (argLen > 0) ? args[0] : null; + let arg = (argLen > 0) ? args[0] : null; if (arg == null) { self.whereClause = {query: {queries: [and()]}}; self.queryType = 'structured'; @@ -3715,7 +3715,7 @@ function where() { queries.push(checkQuery(arg)); } } - var whereClause = {}; + const whereClause = {}; if (queries !== null) { whereClause.query = {queries: queries}; } @@ -3756,7 +3756,7 @@ QueryBuilder.prototype.where = where; * for the {@link queryBuilder#where} function */ function byExample() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: return {$query: []}; @@ -3787,18 +3787,18 @@ function byExample() { */ function orderBy() { /*jshint validthis:true */ - var self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); + const self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); // TODO: if empty, clear the clause - var sortOrder = []; + const sortOrder = []; - var scoreOption = null; - var scoreDirection = null; + let scoreOption = null; + let scoreDirection = null; - var arg = null; - for (var i=0; i < args.length; i++) { + let arg = null; + for (let i=0; i < args.length; i++) { arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { sortOrder.push(sort(arg)); @@ -3879,24 +3879,24 @@ function score() { * for the {@link queryBuilder#orderBy} function */ function sort() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length === 0) { throw new Error('missing sorted index'); } - var firstIndex = asIndex(args[0]); + const firstIndex = asIndex(args[0]); // null is a legitimate value of score - var isScore = (firstIndex.score !== void 0); + const isScore = (firstIndex.score !== void 0); - var sorter = {}; + const sorter = {}; if (isScore) { sorter.score = firstIndex.score; } else { addIndex(sorter, firstIndex, false); } - var arg = null; - for (var i=1; i < args.length; i++) { + let arg = null; + for (let i=1; i < args.length; i++) { arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { switch (arg) { @@ -3944,7 +3944,7 @@ function transform(name, params) { throw new Error('transform without name'); } - var transformList = [name]; + const transformList = [name]; if (params != null) { transformList.push(params); } @@ -3995,9 +3995,9 @@ util.inherits(TrueQueryDef, QueryDef); */ function slice() { /*jshint validthis:true */ - var self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); + const self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); // TODO: if empty, clear the clause @@ -4021,12 +4021,12 @@ QueryBuilder.prototype.slice = slice; */ function calculate() { /*jshint validthis:true */ - var self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); + const self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); // TODO: distinguish facets and values - var calculateClause = { + const calculateClause = { constraint: args }; @@ -4070,13 +4070,13 @@ QueryBuilder.prototype.calculate = calculate; * for the {@link queryBuilder#calculate} function */ function facet() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 1) { throw new Error('facet must at a minimum identify the index'); } - var isConstraintIndex = { + const isConstraintIndex = { collection: true, element: true, field: true, @@ -4089,7 +4089,7 @@ function facet() { 'json-property': true, 'path-index': true }; - var isGeoLocationIndex = { + const isGeoLocationIndex = { 'geo-attr-pair': true, 'geo-elem': true, 'geo-elem-pair': true, @@ -4098,19 +4098,19 @@ function facet() { 'geo-path': true }; - var constraintName = null; - var constraintIndex = null; - var firstKey = null; - var datatype; - var collation; - var facetOptions; - var calculateFunction; - var buckets = null; - var computedBuckets = null; - var heatmap = null; - - var arg = null; - for (var i=0; i < argLen; i++) { + let constraintName = null; + let constraintIndex = null; + let firstKey = null; + let datatype; + let collation; + let facetOptions; + let calculateFunction; + let buckets = null; + let computedBuckets = null; + let heatmap = null; + + let arg = null; + for (let i=0; i < argLen; i++) { arg = args[i]; switch(i) { case 0: @@ -4210,8 +4210,8 @@ function facet() { } } - var facetWrapper = {name: constraintName}; - var constraint = {facet: true}; + const facetWrapper = {name: constraintName}; + const constraint = {facet: true}; if (constraintIndex.collection !== undefined) { facetWrapper.collection = constraint; } else if (calculateFunction !== undefined) { @@ -4231,10 +4231,10 @@ function facet() { constraint.collation = collation; } } - var constraintKeys = Object.keys(constraintIndex); - var constraintKeyLen = constraintKeys.length; - for (var j=0; j < constraintKeyLen; j++) { - var key = constraintKeys[j]; + const constraintKeys = Object.keys(constraintIndex); + const constraintKeyLen = constraintKeys.length; + for (let j=0; j < constraintKeyLen; j++) { + const key = constraintKeys[j]; constraint[key] = constraintIndex[key]; } if (buckets !== null) { @@ -4274,14 +4274,14 @@ function facet() { * module for the {@link queryBuilder#facet} function. */ function calculateFunction() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 1) { throw new Error('calculate function without module name'); } - var moduleName = args[0]; + const moduleName = args[0]; - var rootname = mlutil.rootname(moduleName); + const rootname = mlutil.rootname(moduleName); if (rootname === null) { throw new Error('library must have an extension of .xqy'); } @@ -4377,7 +4377,7 @@ util.inherits(FalseQueryDef, QueryDef); * @returns {queryBuilder.BucketParam} specification for a {@link queryBuilder#facet} calculation */ function bucket() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('must specify name, comparison, and bound for bucket'); @@ -4442,7 +4442,7 @@ function BucketDef(name, lower, upper) { this.name = name; this.label = name; - var lowerType = -1; + let lowerType = -1; if (lower == null) { lowerType = 0; } else if (typeof lower === 'number' || lower instanceof Number) { @@ -4453,7 +4453,7 @@ function BucketDef(name, lower, upper) { throw new Error('invalid lower bound for bucket: '+mlutil.identify(lower, true)); } - var upperType = -1; + let upperType = -1; if (upper == null) { upperType = 0; } else if (typeof upper === 'number' || upper instanceof Number) { @@ -4491,7 +4491,7 @@ function ComputedBucketDef(name, lower, upper) { this.name = name; this.label = name; - var lowerType = -1; + let lowerType = -1; if (lower == null) { lowerType = 0; } else if (lower instanceof AnchorDef) { @@ -4500,7 +4500,7 @@ function ComputedBucketDef(name, lower, upper) { throw new Error('invalid lower bound for computed bucket: '+mlutil.identify(lower, true)); } - var upperType = -1; + let upperType = -1; if (upper == null) { upperType = 0; } else if (upper instanceof AnchorDef) { @@ -4561,7 +4561,7 @@ function ComputedBucketDef(name, lower, upper) { * as part of a facet calculation */ function anchor() { - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); switch(args.length) { case 0: throw new Error('no milestone or lower bound for anchor'); @@ -4591,7 +4591,7 @@ function AnchorDef(milestone, first, comparison, second) { throw new Error('invalid milestone for anchor: '+mlutil.identify(milestone, true)); } - var comparisonType = -1; + let comparisonType = -1; if (comparison == null) { comparisonType = 0; } else if (comparison === '<') { @@ -4673,10 +4673,10 @@ function defaultConstraintName(index) { * the {@link queryBuilder#where} function */ function parsedFrom() { - var qtext = null; - var bindings = null; - var constraints = null; - var term = null; + let qtext = null; + let bindings = null; + let constraints = null; + let term = null; switch(arguments.length) { case 0: @@ -4766,20 +4766,20 @@ function parseBindings() { } /** @ignore */ function makeBindings(variant, args) { - var isParse = (variant === 'parse'); - var desc = isParse ? 'parsing query text' : 'defining suggestion sources'; + const isParse = (variant === 'parse'); + const desc = isParse ? 'parsing query text' : 'defining suggestion sources'; - var argLen = args.length; + const argLen = args.length; if (argLen < 1) { throw new Error('no bindings for '+desc); } - var constraints = null; - var defaultConstraints = null; - var suggestOptions = null; - var empty = null; - var arg = null; - for (var i=0; i < argLen; i++) { + let constraints = null; + let defaultConstraints = null; + let suggestOptions = null; + let empty = null; + let arg = null; + for (let i=0; i < argLen; i++) { arg = args[i]; if (arg.name !== void 0) { if (isParse && (arg['suggest-option'] !== void 0)) { @@ -4793,7 +4793,7 @@ function makeBindings(variant, args) { continue; } if (defaultConstraints == null) { - defaultConstraints = arg['default']; + defaultConstraints = arg.default; if (defaultConstraints !== void 0) { suggestOptions = arg['suggest-option']; if (isParse && (suggestOptions !== void 0)) { @@ -4811,7 +4811,7 @@ function makeBindings(variant, args) { throw new Error('unknown argument for parse query binding: '+mlutil.identify(arg, true)); } - var termDef = ( + const termDef = ( (defaultConstraints == null) && (empty == null) && (suggestOptions == null) @@ -4844,7 +4844,7 @@ function TermBindingDef(defaultConstraints, empty, suggestOptions) { } if (defaultConstraints != null) { - this['default'] = defaultConstraints; + this.default = defaultConstraints; } if (empty != null) { this.empty = empty; @@ -4958,7 +4958,7 @@ function EmptyApplyDef(binding) { return new EmptyApplyDef(binding); } - var valid = {'all-results': true, 'no-results': true}; + const valid = {'all-results': true, 'no-results': true}; if ((typeof binding === 'string' || binding instanceof String) && valid[binding] === true) { this.apply = binding; @@ -4993,18 +4993,18 @@ function EmptyApplyDef(binding) { * module for the {@link queryBuilder#parseBindings} function. */ function parseFunction() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 2) { throw new Error('query parse function without module name or binding'); } - var moduleName = args[0]; + const moduleName = args[0]; - var constraintName = null; - var termOptions = null; - var arg = null; - for (var i=1; i < args.length; i++) { + let constraintName = null; + let termOptions = null; + let arg = null; + for (let i=1; i < args.length; i++) { arg = args[i]; if (termOptions === null && arg instanceof TermOptionsDef) { termOptions = arg['term-option']; @@ -5068,7 +5068,7 @@ function CustomParserDef(moduleName) { return new CustomParserDef(moduleName); } - var rootname = mlutil.rootname(moduleName); + const rootname = mlutil.rootname(moduleName); if (rootname === null) { throw new Error('library must have an extension of .xqy'); } @@ -5100,19 +5100,19 @@ function CustomParserDef(moduleName) { * for the {@link queryBuilder#slice} function */ function extract() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 1) { throw new Error('must specify paths to extract'); } - var extractdef = {}; + const extractdef = {}; - var arg = args[0]; + const arg = args[0]; if (typeof arg === 'string' || arg instanceof String) { extractdef['extract-path'] = args; } else { - var paths = arg.paths; + const paths = arg.paths; if (typeof paths === 'string' || paths instanceof String) { extractdef['extract-path'] = [paths]; } else if (Array.isArray(paths)) { @@ -5121,12 +5121,12 @@ function extract() { throw new Error('first argument does not have key for paths to extract'); } - var namespaces = arg.namespaces; + const namespaces = arg.namespaces; if (namespaces !== void 0) { extractdef.namespaces = namespaces; } - var selected = arg.selected; + const selected = arg.selected; if (selected !== void 0) { extractdef.selected = selected; } @@ -5158,10 +5158,10 @@ function extract() { * for the {@link queryBuilder#slice} function */ function snippet() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; - var builtins = { + const builtins = { empty: 'empty-snippet', 'empty-snippet': 'empty-snippet', metadata: 'metadata-snippet', @@ -5169,13 +5169,13 @@ function snippet() { snippet: 'snippet' }; - var snippeter = { + const snippeter = { apply: 'snippet' }; - var arg = null; - var builtin = null; - for (var i=0; i < argLen; i++) { + let arg = null; + let builtin = null; + for (let i=0; i < argLen; i++) { arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { builtin = builtins[arg]; @@ -5183,7 +5183,7 @@ function snippet() { snippeter.apply = builtin; continue; } else { - var rootname = mlutil.rootname(arg); + const rootname = mlutil.rootname(arg); snippeter.ns = 'http://marklogic.com/snippet/custom/'+rootname; snippeter.at = '/ext/marklogic/snippet/custom/'+arg; snippeter.apply = 'snippet'; @@ -5228,10 +5228,10 @@ function snippet() { */ function withOptions() { /*jshint validthis:true */ - var self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); + const self = (this instanceof QueryBuilder) ? this : new QueryBuilder(); // TODO: share with documents.js - var optionKeyMapping = { + const optionKeyMapping = { search:'search-option', weight:'quality-weight', forestNames:'forest', similarDocs:'return-similar', metrics:'return-metrics', queryPlan:'return-plan', @@ -5239,14 +5239,14 @@ function withOptions() { categories:true, txid:true }; - var withOptionsClause = {}; + const withOptionsClause = {}; if (0 < arguments.length) { - var arg = arguments[0]; - var argKeys = Object.keys(arg); - for (var i=0; i < argKeys.length; i++) { - var key = argKeys[i]; + const arg = arguments[0]; + const argKeys = Object.keys(arg); + for (let i=0; i < argKeys.length; i++) { + const key = argKeys[i]; if (optionKeyMapping[key] !== void 0) { - var value = arg[key]; + const value = arg[key]; if (value !== void 0) { withOptionsClause[key] = value; } else { @@ -5268,17 +5268,17 @@ function makeSearchBody(builtQuery) { throw new Error('no query for documents'); } - var categories = null; - var optionsName = null; - var pageStart = null; - var pageLength = null; - var txid = null; - var transform = null; - var view = null; + let categories = null; + let optionsName = null; + let pageStart = null; + let pageLength = null; + let txid = null; + let transform = null; + let view = null; - var i=0; + let i=0; - var searchBody = {}; + const searchBody = {}; if (builtQuery.search !== void 0) { searchBody.search = builtQuery.search; @@ -5307,10 +5307,10 @@ function makeSearchBody(builtQuery) { categories = (builtQuery.categories !== void 0) ? builtQuery.categories : ['content']; } else { - var search = {}; + const search = {}; searchBody.search = search; - var searchOptions = search.options; + let searchOptions = search.options; if (searchOptions == null) { searchOptions = {}; search.options = searchOptions; @@ -5318,11 +5318,11 @@ function makeSearchBody(builtQuery) { // TODO: validate clauses - var whereClause = builtQuery.whereClause; + const whereClause = builtQuery.whereClause; if (builtQuery.queryType === 'qbe') { search.$query = whereClause.$query; - var format = whereClause.$format; - var validate = whereClause.$validate; + const format = whereClause.$format; + const validate = whereClause.$validate; if (format != null) { search.$format = format; } @@ -5332,9 +5332,9 @@ function makeSearchBody(builtQuery) { } else if (builtQuery.queryType === 'cts') { search.ctsast = bldrbase.exportArg(whereClause); } else if (whereClause != null) { - var query = whereClause.query; - var parsedQuery = whereClause.parsedQuery; - var fragmentScope = whereClause['fragment-scope']; + const query = whereClause.query; + const parsedQuery = whereClause.parsedQuery; + const fragmentScope = whereClause['fragment-scope']; if (query != null) { search.query = query; @@ -5347,7 +5347,7 @@ function makeSearchBody(builtQuery) { } } - var calculateClause = builtQuery.calculateClause; + const calculateClause = builtQuery.calculateClause; if (calculateClause != null) { view = 'results'; searchOptions['return-facets'] = true; @@ -5355,30 +5355,30 @@ function makeSearchBody(builtQuery) { searchOptions['return-metrics'] = false; searchOptions['return-qtext'] = false; searchOptions['transform-results'] = {apply: 'empty-snippet'}; - var searchConstraintList = searchOptions.constraint; + const searchConstraintList = searchOptions.constraint; if (searchConstraintList == null) { searchOptions.constraint = calculateClause.constraint; } else { // TODO: convert into a generic deep merge utility - var constraintLookup = {}; - for (var li=0; li < searchConstraintList.length; li++) { - var lookupConstraint = searchConstraintList[li]; + const constraintLookup = {}; + for (let li=0; li < searchConstraintList.length; li++) { + const lookupConstraint = searchConstraintList[li]; constraintLookup[lookupConstraint.name] = lookupConstraint; } - var calculateConstraints = calculateClause.constraint; - for (var mi=0; mi < calculateConstraints.length; mi++) { - var calculateConstraint = calculateConstraints[mi]; - var searchConstraint = constraintLookup[calculateConstraint.name]; + const calculateConstraints = calculateClause.constraint; + for (let mi=0; mi < calculateConstraints.length; mi++) { + const calculateConstraint = calculateConstraints[mi]; + const searchConstraint = constraintLookup[calculateConstraint.name]; if (searchConstraint == null) { searchConstraintList.push(calculateConstraint); } else { - var constraintChildKeys = + const constraintChildKeys = Object.keys(calculateConstraint).filter(notNameFilter); - for (var ki=0; ki < constraintChildKeys.length; ki++) { - var constraintChildKey = constraintChildKeys[ki]; - var searchChild = searchConstraint[constraintChildKey]; - var searchType = (searchChild === null) ? + for (let ki=0; ki < constraintChildKeys.length; ki++) { + const constraintChildKey = constraintChildKeys[ki]; + const searchChild = searchConstraint[constraintChildKey]; + const searchType = (searchChild === null) ? 'undefined' : typeof searchChild; switch(searchType) { case 'boolean': @@ -5399,7 +5399,7 @@ function makeSearchBody(builtQuery) { } } - var searchFlags = searchOptions['search-option']; + let searchFlags = searchOptions['search-option']; if (searchFlags == null) { searchFlags = ['unfiltered']; searchOptions['search-option'] = searchFlags; @@ -5407,11 +5407,11 @@ function makeSearchBody(builtQuery) { searchFlags.push('unfiltered'); } - var orderByClause = builtQuery.orderByClause; + const orderByClause = builtQuery.orderByClause; if (orderByClause != null) { searchOptions['sort-order'] = orderByClause['sort-order']; - var scoreOption = orderByClause.scoreOption; + const scoreOption = orderByClause.scoreOption; if (scoreOption !== null && scoreOption !== void 0) { for (i=0; i < searchFlags.length; i++) { if (searchFlags[i].indexOf('score-') !== -1) { @@ -5424,25 +5424,25 @@ function makeSearchBody(builtQuery) { } } - var sliceClause = builtQuery.sliceClause; + const sliceClause = builtQuery.sliceClause; if (sliceClause != null) { - var sliceStart = sliceClause['page-start']; + const sliceStart = sliceClause['page-start']; if (sliceStart != null) { pageStart = sliceStart; } - var sliceLength = sliceClause['page-length']; + const sliceLength = sliceClause['page-length']; if (sliceLength != null) { pageLength = sliceLength; } - var transformResults = sliceClause['transform-results']; + const transformResults = sliceClause['transform-results']; if (transformResults != null) { searchOptions['transform-results'] = transformResults; searchOptions['return-results'] = true; view = 'results'; } - var extractResults = sliceClause['extract-document-data']; + const extractResults = sliceClause['extract-document-data']; if (extractResults != null) { searchOptions['extract-document-data'] = extractResults; } @@ -5452,27 +5452,27 @@ function makeSearchBody(builtQuery) { categories = (pageLength > 0) ? ['content'] : null; - var withOptionsClause = builtQuery.withOptionsClause; + const withOptionsClause = builtQuery.withOptionsClause; if (withOptionsClause != null) { // TODO: share with queryBuilder.js - var optionKeyMapping = { + const optionKeyMapping = { search:'search-option', weight:'quality-weight', forestNames:'forest', similarDocs:'return-similar', metrics:'return-metrics', queryPlan:'return-plan', debug:'debug', concurrencyLevel:'concurrency-level', categories:true, txid:true }; - var optionKeyInResponse = { + const optionKeyInResponse = { similarDocs:true, metrics:true, queryPlan:true, debug:true }; - var optionsKeys = Object.keys(withOptionsClause); + const optionsKeys = Object.keys(withOptionsClause); for (i=0; i < optionsKeys.length; i++) { - var key = optionsKeys[i]; - var mapping = optionKeyMapping[key]; + const key = optionsKeys[i]; + const mapping = optionKeyMapping[key]; if (mapping != null) { - var value = withOptionsClause[key]; + const value = withOptionsClause[key]; if (value != null) { if (mapping === true) { switch(key) { @@ -5509,15 +5509,15 @@ function makeSearchBody(builtQuery) { }; } function makeParsedQuery(searchBody, parsedQuery) { - var search = searchBody.search; + const search = searchBody.search; search.qtext = parsedQuery.qtext; - var constraintBindings = parsedQuery.constraint; - var hasConstraints = (constraintBindings != null); - var termBinding = parsedQuery.term; - var hasTerm = (termBinding != null); + const constraintBindings = parsedQuery.constraint; + const hasConstraints = (constraintBindings != null); + const termBinding = parsedQuery.term; + const hasTerm = (termBinding != null); if (hasConstraints || hasTerm) { - var searchOptions = search.options; + let searchOptions = search.options; if (searchOptions == null) { searchOptions = {}; search.options = searchOptions; diff --git a/lib/requester.js b/lib/requester.js index 7d4d3ba8..63bd1479 100644 --- a/lib/requester.js +++ b/lib/requester.js @@ -2,19 +2,19 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var createAuthInitializer = require('./www-authenticate-patched/www-authenticate'); -var Kerberos = require('./optional.js') +const createAuthInitializer = require('./www-authenticate-patched/www-authenticate'); +const Kerberos = require('./optional.js') .libraryProperty('kerberos', 'Kerberos'); -var Multipart = require('multipart-stream'); -var through2 = require('through2'); -var mlutil = require('./mlutil.js'); -var responder = require('./responder.js'); -var kerberos = null; +const Multipart = require('multipart-stream'); +const through2 = require('through2'); +const mlutil = require('./mlutil.js'); +const responder = require('./responder.js'); +let kerberos = null; const https = require('https'); const formData = require('form-data'); function createAuthenticator(client, user, password, challenge) { - var authenticator = createAuthInitializer.call(null, user, password)(challenge); + const authenticator = createAuthInitializer.call(null, user, password)(challenge); if (!client.authenticator) { client.authenticator = {}; } @@ -23,7 +23,7 @@ function createAuthenticator(client, user, password, challenge) { } function createAuthenticatorKerberos(client, credentials) { - var authenticatorKerberos = { + const authenticatorKerberos = { 'credentials': credentials }; client.authenticatorKerberos = authenticatorKerberos; @@ -81,11 +81,11 @@ function getAccessToken(operation){ } function startRequest(operation) { - var options = operation.options; - var operationErrorListener = responder.operationErrorListener; + const options = operation.options; + const operationErrorListener = responder.operationErrorListener; operation.errorListener = mlutil.callbackOn(operation, operationErrorListener); - var headers = options.headers; + let headers = options.headers; if (headers == null) { headers = {}; options.headers = headers; @@ -96,8 +96,8 @@ function startRequest(operation) { if(options.enableGzippedResponses) { headers['Accept-Encoding'] = 'gzip'; } - var started = null; - var operationResultPromise = null; + let started = null; + let operationResultPromise = null; switch(operation.requestType) { case 'empty': @@ -127,12 +127,12 @@ function startRequest(operation) { } const authType = options.authType.toUpperCase(); - var needsAuthenticator = ( + let needsAuthenticator = ( authType === 'DIGEST' || authType === 'KERBEROS' ); if (needsAuthenticator) { - var authenticator = null; + let authenticator = null; switch(authType) { case 'DIGEST': authenticator = getAuthenticator(operation.client, options.user); @@ -173,23 +173,23 @@ function startRequest(operation) { } if (started === null) { - var ResponseSelector = responder.ResponseSelector; + const ResponseSelector = responder.ResponseSelector; started = new ResponseSelector(operation); } return started; } function challengeRequest(operation) { - var isRead = (operation.inputSender === null); - var options = operation.options; - var challengeOpts = isRead ? options : { + const isRead = (operation.inputSender === null); + const options = operation.options; + const challengeOpts = isRead ? options : { method: 'HEAD', path: '/v1/ping' }; if (!isRead) { Object.keys(options).forEach(function optionKeyCopier(key) { if (challengeOpts[key] === void 0) { - var value = options[key]; + const value = options[key]; if (value != null) { challengeOpts[key] = value; } @@ -199,10 +199,10 @@ function challengeRequest(operation) { operation.logger.debug('challenge request for %s', challengeOpts.path); var request1 = operation.client.request(challengeOpts, function challengeResponder(response1) { - var statusCode1 = response1.statusCode; - var successStatus = (statusCode1 < 400); - var challenge = response1.headers['www-authenticate']; - var hasChallenge = (challenge != null); + const statusCode1 = response1.statusCode; + const successStatus = (statusCode1 < 400); + const challenge = response1.headers['www-authenticate']; + const hasChallenge = (challenge != null); operation.logger.debug('response with status %d and %s challenge for %s', statusCode1, hasChallenge, challengeOpts.path); @@ -218,7 +218,7 @@ function challengeRequest(operation) { authenticatedRequest(operation); // should never happen } else if (successStatus && isRead) { - var responseDispatcher = responder.responseDispatcher; + const responseDispatcher = responder.responseDispatcher; responseDispatcher.call(operation, response1); } else if (isRetry(response1)) { retryRequest(operation, response1, challengeRequest); @@ -232,7 +232,7 @@ function challengeRequest(operation) { } function credentialsRequest(operation) { kerberos = new Kerberos(); - var uri = 'HTTP@'+operation.options.host; + const uri = 'HTTP@'+operation.options.host; kerberos.authGSSClientInit(uri, 0, function(err, ctx) { if (err) { operation.errorListener('kerberos initialization failed at '+uri); @@ -257,12 +257,12 @@ function credentialsRequest(operation) { }); } function authenticatedRequest(operation) { - var isRead = (operation.inputSender === null); - var options = operation.options; + const isRead = (operation.inputSender === null); + const options = operation.options; operation.logger.debug('authenticated request for %s', options.path); - var authenticator = operation.authenticator; - var responseDispatcher = operation.isReplayable ? retryDispatcher : responder.responseDispatcher; - var request = operation.client.request( + const authenticator = operation.authenticator; + const responseDispatcher = operation.isReplayable ? retryDispatcher : responder.responseDispatcher; + const request = operation.client.request( options, mlutil.callbackOn(operation, responseDispatcher) ); const authType = options.authType.toUpperCase(); @@ -364,9 +364,9 @@ function retryRequest(operation, response, requestSender) { function singleRequester(request) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var requestSource = mlutil.marshal(operation.requestBody, operation); + const requestSource = mlutil.marshal(operation.requestBody, operation); if (requestSource == null) { request.end(); } else if (typeof requestSource === 'string' || requestSource instanceof String) { @@ -382,13 +382,13 @@ function singleRequester(request) { } function multipartRequester(request) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var operationBoundary = operation.multipartBoundary; - var multipartStream = new Multipart((operationBoundary == null) ? + const operationBoundary = operation.multipartBoundary; + const multipartStream = new Multipart((operationBoundary == null) ? mlutil.multipartBoundary : operationBoundary); - var requestPartsProvider = operation.requestPartsProvider; + const requestPartsProvider = operation.requestPartsProvider; if(operation.bindingParam) { const form = new formData(); const bindingParam = operation.bindingParam; @@ -443,14 +443,14 @@ function multipartRequester(request) { } else if (typeof requestPartsProvider === 'function') { requestPartsProvider.call(operation, multipartStream); } else { - var parts = operation.requestPartList; + const parts = operation.requestPartList; if (Array.isArray(parts)) { - var partsLen = parts.length; + const partsLen = parts.length; operation.logger.debug('writing %s parts', partsLen); - for (var i=0; i < partsLen; i++) { - var part = parts[i]; - var headers = part.headers; - var content = part.content; + for (let i=0; i < partsLen; i++) { + const part = parts[i]; + const headers = part.headers; + const content = part.content; if ((headers != null) && (content != null)) { operation.logger.debug('starting part %s', i); @@ -471,9 +471,9 @@ function multipartRequester(request) { } function chunkedRequester(request) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var requestWriter = operation.requestWriter; + const requestWriter = operation.requestWriter; if (requestWriter === null || requestWriter === undefined) { operation.errorListener('no request writer for streaming request'); request.end(); @@ -483,10 +483,10 @@ function chunkedRequester(request) { } function chunkedMultipartRequester(request) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var requestWriter = operation.requestWriter; - var requestDocument = operation.requestDocument; + const requestWriter = operation.requestWriter; + const requestDocument = operation.requestDocument; if (requestWriter == null) { operation.errorListener('no request writer for streaming request'); request.end(); @@ -494,17 +494,17 @@ function chunkedMultipartRequester(request) { operation.errorListener('no request document for streaming request'); request.end(); } else { - var operationBoundary = operation.multipartBoundary; + const operationBoundary = operation.multipartBoundary; - var multipartStream = new Multipart((operationBoundary == null) ? + const multipartStream = new Multipart((operationBoundary == null) ? mlutil.multipartBoundary : operationBoundary); - var partLast = requestDocument.length - 1; - for (var i=0; i <= partLast; i++) { - var part = requestDocument[i]; - var headers = part.headers; + const partLast = requestDocument.length - 1; + for (let i=0; i <= partLast; i++) { + const part = requestDocument[i]; + const headers = part.headers; if (i < partLast) { - var content = part.content; + const content = part.content; if ((headers != null) && (content != null)) { multipartStream.addPart({ diff --git a/lib/resources-config.js b/lib/resources-config.js index 6846a5ca..97762dcf 100644 --- a/lib/resources-config.js +++ b/lib/resources-config.js @@ -2,16 +2,16 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); /** @ignore */ function nameErrorTransform(message) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var name = operation.name; + const name = operation.name; return (name == null) ? message : (message+' (on '+name+' resource service)'); } @@ -26,7 +26,7 @@ function nameErrorTransform(message) { /** @ignore */ function emptyOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; return { name: operation.name @@ -59,11 +59,11 @@ Resources.prototype.read = function readResourceConfig(name) { throw new Error('must specify name when reading the resource service source'); } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'GET'; requestOptions.path = '/v1/config/resources/'+encodeURIComponent(name); - var operation = new Operation( + const operation = new Operation( 'read resource service', this.client, requestOptions, 'empty', 'single' ); operation.name = name; @@ -82,21 +82,21 @@ Resources.prototype.read = function readResourceConfig(name) { * @param {object|string} source - the source for the resource service */ Resources.prototype.write = function writeResourceConfig() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen === 0) { throw new Error('no arguments for writing an extension library'); } - var name = null; - var title = null; - var description = null; - var provider = null; - var version = null; - var format = null; - var source = null; + let name = null; + let title = null; + let description = null; + let provider = null; + let version = null; + let format = null; + let source = null; - var params = null; + let params = null; if (argLen === 1) { params = args[0]; name = params.name; @@ -117,7 +117,7 @@ Resources.prototype.write = function writeResourceConfig() { throw new Error('must specify name, format, and source when writing a resource service'); } - var contentType = null; + let contentType = null; switch(format) { case 'javascript': contentType = 'application/javascript'; @@ -129,9 +129,9 @@ Resources.prototype.write = function writeResourceConfig() { throw new Error('unsupported resource service format '+format); } - var endpoint = '/v1/config/resources/'+encodeURIComponent(name); + let endpoint = '/v1/config/resources/'+encodeURIComponent(name); - var sep = '?'; + let sep = '?'; if (title != null) { endpoint += sep+'title='+encodeURIComponent(title); if (sep === '?') {sep = '&';} @@ -149,14 +149,14 @@ Resources.prototype.write = function writeResourceConfig() { if (sep === '?') {sep = '&';} } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'PUT'; requestOptions.headers = { 'Content-Type': contentType }; requestOptions.path = endpoint; - var operation = new Operation( + const operation = new Operation( 'write resource service', this.client, requestOptions, 'single', 'empty' ); operation.name = name; @@ -178,11 +178,11 @@ Resources.prototype.remove = function removeResourceConfig(name) { throw new Error('must specify name when deleting the resource service source'); } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'DELETE'; requestOptions.path = '/v1/config/resources/'+encodeURIComponent(name); - var operation = new Operation( + const operation = new Operation( 'remove resource service', this.client, requestOptions, 'empty', 'empty' ); operation.name = name; @@ -201,14 +201,14 @@ Resources.prototype.remove = function removeResourceConfig(name) { * on the server */ Resources.prototype.list = function listResourceConfig() { - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'GET'; requestOptions.headers = { 'Accept': 'application/json' }; requestOptions.path = '/v1/config/resources'; - var operation = new Operation( + const operation = new Operation( 'list resource services', this.client, requestOptions, 'empty', 'single' ); diff --git a/lib/resources-exec.js b/lib/resources-exec.js index d9b9db70..c3103da0 100644 --- a/lib/resources-exec.js +++ b/lib/resources-exec.js @@ -2,9 +2,9 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); /** * Provides functions to execute resource services on the REST server @@ -20,7 +20,7 @@ function checkArgs() { throw new Error('no argument for executing resource service'); } - var args = arguments[0]; + const args = arguments[0]; if (args.name === void 0) { throw new Error('no name for executing resource service'); } @@ -29,18 +29,18 @@ function checkArgs() { } /** @ignore */ function makeRequestOptions(client, args) { - var path = '/v1/resources/'+args.name; - - var sep ='?'; - - var params = args.params; - var keys = (params === void 0) ? null : Object.keys(params); - var keyLen = (keys === null) ? 0 : keys.length; - var key = null; - var prefix = null; - var i=0; - var value = null; - var j=0; + let path = '/v1/resources/'+args.name; + + let sep ='?'; + + const params = args.params; + const keys = (params === void 0) ? null : Object.keys(params); + const keyLen = (keys === null) ? 0 : keys.length; + let key = null; + let prefix = null; + let i=0; + let value = null; + let j=0; for (; i < keyLen; i++) { key = keys?keys[i]:null; if(params){ @@ -63,7 +63,7 @@ function makeRequestOptions(client, args) { } } - var txid = mlutil.convertTransaction(args.txid); + const txid = mlutil.convertTransaction(args.txid); if (txid !== undefined && txid != null) { path += sep+'txid='+mlutil.getTxidParam(txid); if (sep === '?') { @@ -109,9 +109,9 @@ Resources.prototype.get = function getResourceExec() { ); }; Resources.prototype.getReadStream = function getResourceExecStream() { - var args = checkArgs.apply(null, arguments); + const args = checkArgs.apply(null, arguments); - var contentType = args.contentType; + const contentType = args.contentType; if (contentType == null) { throw new Error('no content type for reading stream from resource service'); } @@ -120,13 +120,13 @@ Resources.prototype.getReadStream = function getResourceExecStream() { }; /** @ignore */ function readResourceExec(self, responseType, contentType, args) { - var requestOptions = makeRequestOptions(self.client, args); + const requestOptions = makeRequestOptions(self.client, args); requestOptions.method = 'GET'; requestOptions.headers = { 'Accept': contentType }; - var operation = new Operation( + const operation = new Operation( 'execute remove service', self.client, requestOptions, 'empty', responseType ); operation.name = args.name; @@ -179,19 +179,19 @@ Resources.prototype.putWriteStream = function putResourceExecStream() { }; /** @ignore */ function writeResourceStream(self, method, responseType, args) { - var contentType = args.contentType; + const contentType = args.contentType; if (contentType == null) { throw new Error('no content type for writing stream to resource service'); } - var requestOptions = makeRequestOptions(self.client, args); + const requestOptions = makeRequestOptions(self.client, args); requestOptions.headers = { 'Content-Type': contentType, 'Accept': 'application/json' }; requestOptions.method = method; - var operation = new Operation( + const operation = new Operation( 'execute '+method+' service stream', self.client, requestOptions, 'chunked', responseType ); @@ -203,16 +203,16 @@ function writeResourceStream(self, method, responseType, args) { } /** @ignore */ function writeResources(self, method, responseType, args) { - var documents = args.documents; + let documents = args.documents; - var isEmpty = (documents == null); + const isEmpty = (documents == null); if (!isEmpty && !Array.isArray(documents)) { documents = [documents]; } - var multipartBoundary = mlutil.multipartBoundary; + const multipartBoundary = mlutil.multipartBoundary; - var requestOptions = makeRequestOptions(self.client, args); + const requestOptions = makeRequestOptions(self.client, args); requestOptions.method = method; requestOptions.headers = (!isEmpty) ? { @@ -223,7 +223,7 @@ function writeResources(self, method, responseType, args) { 'Accept': 'application/json' }; - var operation = new Operation( + const operation = new Operation( 'execute '+method+' service', self.client, requestOptions, (isEmpty ? 'empty' : 'multipart'), responseType ); @@ -234,7 +234,7 @@ function writeResources(self, method, responseType, args) { operation.requestPartList = []; if (typeof documents !== 'undefined' && documents !== null) { - for (var i=0; i < documents.length; i++) { + for (let i=0; i < documents.length; i++) { addPart(operation, documents[i]); } } @@ -245,17 +245,17 @@ function writeResources(self, method, responseType, args) { } /** @ignore */ function addPart(operation, document) { - var headers = {}; - var part = { + const headers = {}; + const part = { headers: headers }; - var content = document.content; - var hasContent = (content != null); - var contentType = hasContent ? document.contentType : null; + const content = document.content; + const hasContent = (content != null); + const contentType = hasContent ? document.contentType : null; if (hasContent && (contentType != null)) { - var marshaledData = mlutil.marshal(content, operation); + const marshaledData = mlutil.marshal(content, operation); /* TODO: allow encoding in multipart parse headers['Content-Type'] = contentType + ((typeof marshaledData === 'string' || marshaledData instanceof String) ? '; charset=utf-8' : ''); @@ -291,15 +291,15 @@ function addPart(operation, document) { * multi-statement transaction */ Resources.prototype.remove = function removeResourceExec() { - var args = checkArgs.apply(null, arguments); + const args = checkArgs.apply(null, arguments); - var requestOptions = makeRequestOptions(this.client, args); + const requestOptions = makeRequestOptions(this.client, args); requestOptions.headers = { 'Accept': 'application/json' }; requestOptions.method = 'DELETE'; - var operation = new Operation( + const operation = new Operation( 'execute remove service', this.client, requestOptions, 'empty', 'single' ); operation.name = args.name; diff --git a/lib/responder.js b/lib/responder.js index b5f6793f..412ca64d 100644 --- a/lib/responder.js +++ b/lib/responder.js @@ -2,11 +2,11 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var concatStream = require('concat-stream'); -var jsonParser = require('json-text-sequence').Parser; -var Dicer = require('@fastify/busboy/deps/dicer/lib/Dicer'); -var through2 = require('through2'); -var mlutil = require('./mlutil.js'); +const concatStream = require('concat-stream'); +const jsonParser = require('json-text-sequence').Parser; +const Dicer = require('@fastify/busboy/deps/dicer/lib/Dicer'); +const through2 = require('through2'); +const mlutil = require('./mlutil.js'); const requester = require('./requester'); const {createGunzip} = require('zlib'); @@ -31,20 +31,20 @@ const {createGunzip} = require('zlib'); */ function responseDispatcher(response) { /*jshint validthis:true */ - var operation = this; + const operation = this; if (!isResponseStatusOkay.call(operation, response)) { return; } - var outputMode = operation.outputMode; + const outputMode = operation.outputMode; if (outputMode === 'none') { return; } - var responseType = response.headers['content-type']; - var responseTypeLen = (!responseType) ? 0 : responseType.length; - var responseBoundary = null; + const responseType = response.headers['content-type']; + const responseTypeLen = (!responseType) ? 0 : responseType.length; + let responseBoundary = null; if (15 <= responseTypeLen && responseType.substr(0, 15) === 'multipart/mixed') { responseBoundary = responseType.replace( /^multipart.mixed\s*;\s*boundary\s*=\s*([^\s;]+)([\s;].*)?$/, '$1' @@ -60,16 +60,16 @@ function responseDispatcher(response) { ); } } - var isMultipart = (responseBoundary != null); + const isMultipart = (responseBoundary != null); // inputHeader may be boundary (for multipart) or content type (for body) // Allows dispatch function signatures to remain consistent - var inputHeader = isMultipart ? responseBoundary : responseType; + const inputHeader = isMultipart ? responseBoundary : responseType; - var responseLength = response.headers['content-length']; - var isEmpty = ((responseLength != null) && responseLength === '0'); + const responseLength = response.headers['content-length']; + const isEmpty = ((responseLength != null) && responseLength === '0'); - var expectedType = operation.responseType; + const expectedType = operation.responseType; // point-in-time operations: if timestamp unset, set with header value if (operation.timestamp !== undefined && operation.timestamp !== null) { @@ -79,7 +79,7 @@ function responseDispatcher(response) { } } - var dispatcher = null; + let dispatcher = null; if (isMultipart) { if (expectedType !== 'multipart') { operation.logger.debug('expected body but received multipart'); @@ -149,15 +149,15 @@ function CSVDispatcher(operation) { CSVDispatcher.prototype.promise = function dispatchCSVPromise( contentType, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('csv promise'); - var collectObject = function collectPromiseBodyObject(data) { + const collectObject = function collectPromiseBodyObject(data) { operation.data = data; resolvedPromise(operation, operation.resolve); }; - var isString = operation.copyResponseHeaders(response); + const isString = operation.copyResponseHeaders(response); if(isResponseGzipped(response.headers)) { response.pipe(createGunzip()).pipe(concatStream( {encoding: (isString ? 'string' : 'buffer')}, @@ -173,7 +173,7 @@ CSVDispatcher.prototype.promise = function dispatchCSVPromise( CSVDispatcher.prototype.chunkedStream = function dispatchCSVChunkedStream( contentType, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('csv chunked stream'); @@ -196,20 +196,20 @@ function JSONSeqDispatcher(operation) { JSONSeqDispatcher.prototype.promise = function dispatchJSONSeqPromise( contentType, response ) { - var operation = this.operation; - var errorListener = operation.errorListener; - var objectQueue = new FifoQueue(2); - var parsedObjects = 0; + const operation = this.operation; + const errorListener = operation.errorListener; + let objectQueue = new FifoQueue(2); + let parsedObjects = 0; operation.logger.debug('json sequence promise'); - var dataListener = function JSONSeqDataListener(object) { + let dataListener = function JSONSeqDataListener(object) { parsedObjects++; operation.logger.debug('json-seq parsing object %d', parsedObjects); objectQueue.addLast(object); }; - var finishListener = function JSONSeqFinishListener() { + let finishListener = function JSONSeqFinishListener() { operation.logger.debug('json-seq finished parsing %d objects', parsedObjects); operation.data = objectQueue.getQueue(); resolvedPromise(operation, operation.resolve); @@ -248,21 +248,21 @@ JSONSeqDispatcher.prototype.objectStream = function dispatchJSONSeqObjectStream( JSONSeqDispatcher.prototype.stream = function dispatchJSONSeqStream( streamMode, response ) { - var operation = this.operation; - var errorListener = operation.errorListener; - var outputStream = operation.outputStream; - var parsedObjects = 0; - var hasParsed = false; - var hasEnded = false; + const operation = this.operation; + const errorListener = operation.errorListener; + const outputStream = operation.outputStream; + let parsedObjects = 0; + let hasParsed = false; + let hasEnded = false; operation.logger.debug('json sequence stream ' + streamMode); - var dataListener = function JSONSeqDataListener(object) { + let dataListener = function JSONSeqDataListener(object) { parsedObjects++; operation.logger.debug('parsing object %d', parsedObjects); operation.logger.debug(object); - var writeResult = null; + let writeResult = null; if (object !== null && object !== undefined) { if (streamMode === 'object') { writeResult = outputStream.write(object); @@ -284,7 +284,7 @@ JSONSeqDispatcher.prototype.stream = function dispatchJSONSeqStream( }; - var responseFinisher = function JSONSeqFinishListener() { + let responseFinisher = function JSONSeqFinishListener() { if (hasParsed && hasEnded) { operation.logger.debug('finished parsing %d objects', parsedObjects); @@ -343,7 +343,7 @@ function BodyDispatcher(operation) { this.operation = operation; } BodyDispatcher.prototype.emptyPromise = function dispatchBodyEmptyPromise(response) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('empty body promise'); @@ -351,13 +351,13 @@ BodyDispatcher.prototype.emptyPromise = function dispatchBodyEmptyPromise(respon resolvedPromise(operation, operation.resolve); }; BodyDispatcher.prototype.emptyStream = function dispatchBodyEmptyStream(response) { - var operation = this.operation; + const operation = this.operation; - var data = operation.emptyHeaderData(response); + const data = operation.emptyHeaderData(response); operation.logger.debug('empty body stream'); - var outputStream = operation.outputStream; + const outputStream = operation.outputStream; if (data != null) { if (operation.outputStreamMode === 'chunked') { outputStream.write(JSON.stringify(data)); @@ -370,17 +370,17 @@ BodyDispatcher.prototype.emptyStream = function dispatchBodyEmptyStream(response BodyDispatcher.prototype.promise = function dispatchBodyPromise( contentType, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('body promise'); - var collectObject = function collectPromiseBodyObject(data) { + const collectObject = function collectPromiseBodyObject(data) { // turn collected data into something usable // e.g., if JSON, parse as JS object operation.data = operation.collectBodyObject(data); resolvedPromise(operation, operation.resolve); }; - var isString = operation.copyResponseHeaders(response); + const isString = operation.copyResponseHeaders(response); if(isResponseGzipped(response.headers)) { const gunzip = createGunzip(); @@ -400,7 +400,7 @@ BodyDispatcher.prototype.promise = function dispatchBodyPromise( BodyDispatcher.prototype.chunkedStream = function dispatchBodyChunkedStream( contentType, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('body chunked stream'); @@ -416,23 +416,23 @@ BodyDispatcher.prototype.chunkedStream = function dispatchBodyChunkedStream( BodyDispatcher.prototype.objectStream = function dispatchBodyObjectStream( contentType, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('body object stream'); // outputStream is a through2 stream in object mode - var outputStream = operation.outputStream; + const outputStream = operation.outputStream; - var collectObject = function collectStreamBodyObject(data) { + const collectObject = function collectStreamBodyObject(data) { // similar to promise body case, but write to through2 - var writableObject = operation.collectBodyObject(data); + const writableObject = operation.collectBodyObject(data); if (writableObject != null) { outputStream.write(writableObject); } outputStream.end(); }; - var isString = operation.copyResponseHeaders(response); + const isString = operation.copyResponseHeaders(response); if(isResponseGzipped(response.headers)) { response.pipe(createGunzip()).pipe(concatStream( {encoding: (isString ? 'string' : 'buffer')}, @@ -458,9 +458,9 @@ function MultipartDispatcher(operation) { this.operation = operation; } MultipartDispatcher.prototype.emptyPromise = function dispatchMultipartEmptyPromise(response) { - var operation = this.operation; + const operation = this.operation; - var data = operation.emptyHeaderData(response); + const data = operation.emptyHeaderData(response); operation.logger.debug('empty multipart promise'); @@ -468,13 +468,13 @@ MultipartDispatcher.prototype.emptyPromise = function dispatchMultipartEmptyProm resolvedPromise(operation, operation.resolve); }; MultipartDispatcher.prototype.emptyStream = function dispatchMultipartEmptyStream(response) { - var operation = this.operation; + const operation = this.operation; - var data = operation.emptyHeaderData(response); + const data = operation.emptyHeaderData(response); operation.logger.debug('empty multipart stream'); - var outputStream = operation.outputStream; + const outputStream = operation.outputStream; if (data != null) { if (operation.outputStreamMode === 'chunked') { outputStream.write(JSON.stringify(data)); @@ -492,10 +492,10 @@ MultipartDispatcher.prototype.emptyStream = function dispatchMultipartEmptyStrea MultipartDispatcher.prototype.promise = function dispatchMultipartPromise( boundary, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('multipart promise'); - const errorListenerCheck = (operation.options.headers['Accept'] === 'application/json' && (operation.name.includes('rows') || operation.name.includes('query') || operation.name.includes('/v1/rows'))); + const errorListenerCheck = (operation.options.headers.Accept === 'application/json' && (operation.name.includes('rows') || operation.name.includes('query') || operation.name.includes('/v1/rows'))); if(errorListenerCheck) { if(response.headers['content-encoding']!=='gzip'){ @@ -512,7 +512,7 @@ MultipartDispatcher.prototype.promise = function dispatchMultipartPromise( response.pipe(concatStream( {encoding: 'json'}, () => { - let data = JSON.parse(chunks); + const data = JSON.parse(chunks); operation.data = data; resolvedPromise(operation, operation.resolve); } @@ -521,22 +521,22 @@ MultipartDispatcher.prototype.promise = function dispatchMultipartPromise( return; } - var errorListener = operation.errorListener; + const errorListener = operation.errorListener; - var rawHeaderQueue = new FifoQueue(2); - var objectQueue = new FifoQueue(2); - var partReaderQueue = new FifoQueue(3); + let rawHeaderQueue = new FifoQueue(2); + let objectQueue = new FifoQueue(2); + let partReaderQueue = new FifoQueue(3); - var parsingParts = 0; - var parsedParts = 0; + let parsingParts = 0; + let parsedParts = 0; - var hasParsed = false; - var hasEnded = false; + let hasParsed = false; + let hasEnded = false; - var responseFinisher = function promiseResponseFinisher() { + let responseFinisher = function promiseResponseFinisher() { // If there is metadata left in the buffer, add it to queue if (operation.nextMetadataBuffer !== null) { - var metadataHeaders = operation.nextMetadataBuffer[0]; + const metadataHeaders = operation.nextMetadataBuffer[0]; mlutil.copyProperties(operation.nextMetadataBuffer[1], metadataHeaders); objectQueue.addLast(metadataHeaders); } @@ -563,7 +563,7 @@ MultipartDispatcher.prototype.promise = function dispatchMultipartPromise( partReaderQueue.removeFirst(); - var madeObject = operation.makeObject( + const madeObject = operation.makeObject( (data.length === 0) ? null : data, rawHeaderQueue ); @@ -572,10 +572,10 @@ MultipartDispatcher.prototype.promise = function dispatchMultipartPromise( } if (partReaderQueue.hasItem()) { - var partConcatenator = concatStream(partFinisher); + const partConcatenator = concatStream(partFinisher); partConcatenator.on('error', errorListener); - var partReadStream = partReaderQueue.getFirst(); + const partReadStream = partReaderQueue.getFirst(); partReadStream.pipe(partConcatenator); } else if (hasParsed) { responseFinisher(); @@ -597,7 +597,7 @@ MultipartDispatcher.prototype.promise = function dispatchMultipartPromise( partReaderQueue.addLast(partReadStream); if (partReaderQueue.isLast()) { - var partConcatenator = concatStream(partFinisher); + const partConcatenator = concatStream(partFinisher); partConcatenator.on('error', errorListener); partReadStream.pipe(partConcatenator); } @@ -629,19 +629,19 @@ MultipartDispatcher.prototype.promise = function dispatchMultipartPromise( MultipartDispatcher.prototype.chunkedStream = function dispatchMultipartChunkedStream( boundary, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('multipart chunked stream'); - var errorListener = operation.errorListener; + const errorListener = operation.errorListener; - var outputStream = operation.outputStream; + let outputStream = operation.outputStream; - var partReaderQueue = new FifoQueue(3); + const partReaderQueue = new FifoQueue(3); - var hasParsed = false; - var hasEnded = false; + let hasParsed = false; + let hasEnded = false; - var responseFinisher = function chunkedResponseFinisher() { + let responseFinisher = function chunkedResponseFinisher() { outputStream.end(); outputStream = null; partEndListener = null; @@ -656,7 +656,7 @@ MultipartDispatcher.prototype.chunkedStream = function dispatchMultipartChunkedS partReaderQueue.removeFirst(); if (partReaderQueue.hasItem()) { - var partReadStream = partReaderQueue.getFirst(); + const partReadStream = partReaderQueue.getFirst(); partReadStream.pipe(outputStream, {end: false}); } else if (hasParsed) { responseFinisher(); @@ -699,26 +699,26 @@ MultipartDispatcher.prototype.chunkedStream = function dispatchMultipartChunkedS MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStream( boundary, response ) { - var operation = this.operation; + const operation = this.operation; operation.logger.debug('multipart object stream'); - var errorListener = operation.errorListener; + const errorListener = operation.errorListener; - var rawHeaderQueue = new FifoQueue(5); - var partReaderQueue = new FifoQueue(3); + let rawHeaderQueue = new FifoQueue(5); + const partReaderQueue = new FifoQueue(3); // For referenced attachments case - var partBuffer = null; + let partBuffer = null; - var parsingParts = 0; - var parsedParts = 0; + let parsingParts = 0; + let parsedParts = 0; - var hasParsed = false; - var hasEnded = false; + let hasParsed = false; + let hasEnded = false; - var isConcatenating = false; + let isConcatenating = false; - var responseFinisher = function objectResponseFinisher() { + const responseFinisher = function objectResponseFinisher() { if (!partReaderQueue.hasItem() && hasParsed && hasEnded) { @@ -734,7 +734,7 @@ MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStr else { // If there is metadata left in the buffer, write it if (operation.nextMetadataBuffer !== null) { - var metadataHeaders = operation.nextMetadataBuffer[0]; + const metadataHeaders = operation.nextMetadataBuffer[0]; mlutil.copyProperties(operation.nextMetadataBuffer[1], metadataHeaders); operation.outputStream.write(metadataHeaders); operation.nextMetadataBuffer = null; @@ -753,16 +753,16 @@ MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStr }; - var partFinisher = function objectPartFinisher(data) { + const partFinisher = function objectPartFinisher(data) { parsedParts++; operation.logger.debug('parsed part %d', parsedParts); - var madeObject = operation.makeObject( + const madeObject = operation.makeObject( (data.length === 0) ? null : data, rawHeaderQueue ); // Handle multipart with reference attachments (rows) - var writeResult = null; + let writeResult = null; if (operation.complexValues === 'reference') { if (madeObject !== null && madeObject !== undefined) { // Columns object @@ -784,7 +784,7 @@ MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStr // Attachment object else { // Remove '[n]' to get column name - var columnName = madeObject.contentId + const columnName = madeObject.contentId .slice(0, madeObject.contentId.lastIndexOf('[')); // Put attachment into currently cached part partBuffer.content[columnName] = { @@ -819,9 +819,9 @@ MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStr // If item avail, concat-stream it with callback to finisher if (partReaderQueue.hasItem()) { isConcatenating = true; - var partRead = concatStream(partFinisher); + const partRead = concatStream(partFinisher); partRead.on('error', errorListener); - var partReadStream = partReaderQueue.getFirst(); + const partReadStream = partReaderQueue.getFirst(); partReadStream.pipe(partRead); } else if (hasParsed) { @@ -845,7 +845,7 @@ MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStr if (partReaderQueue.isLast()) { isConcatenating = true; - var partRead = concatStream(partFinisher); + const partRead = concatStream(partFinisher); partRead.on('error', errorListener); partReadStream.pipe(partRead); } @@ -861,15 +861,15 @@ MultipartDispatcher.prototype.objectStream = function dispatchMultipartObjectStr responseFinisher(); }; - var drainListener = function objectDrainListener() { + const drainListener = function objectDrainListener() { if (!hasEnded) { response.resume(); // Don't read if concat in progress to avoid double processing if (partReaderQueue.hasItem() && !isConcatenating) { isConcatenating = true; - var partRead = concatStream(partFinisher); + const partRead = concatStream(partFinisher); partRead.on('error', errorListener); - var partReadStream = partReaderQueue.getFirst(); + const partReadStream = partReaderQueue.getFirst(); partReadStream.pipe(partRead); } } @@ -951,7 +951,7 @@ FifoQueue.prototype.removeFirst = function fifoRemoveFirst() { } }; FifoQueue.prototype.pollFirst = function fifoPollFirst() { - var item = this.getFirst(); + const item = this.getFirst(); if (item !== undefined) { this.removeFirst(); } @@ -997,20 +997,20 @@ FifoQueue.prototype.compact = function fifoCompact() { function isResponseStatusOkay(response) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var statusCode = response.statusCode; + const statusCode = response.statusCode; - var errMsg = null; + let errMsg = null; - var statusCodeValidator = operation.statusCodeValidator; + const statusCodeValidator = operation.statusCodeValidator; if (typeof statusCodeValidator === 'function') { errMsg = statusCodeValidator.call(operation, statusCode, response); } else { - var validStatusCodes = operation.validStatusCodes; + const validStatusCodes = operation.validStatusCodes; if (Array.isArray(validStatusCodes)) { - var isError = true; - for (var i=0; i < validStatusCodes.length; i++) { + let isError = true; + for (let i=0; i < validStatusCodes.length; i++) { if (validStatusCodes[i] === statusCode) { isError = false; break; @@ -1025,16 +1025,16 @@ function isResponseStatusOkay(response) { } if (errMsg != null) { - var clientError = operation.makeError(errMsg); + const clientError = operation.makeError(errMsg); clientError.statusCode = statusCode; if (statusCode >= 400) { - let errorResponse = (isResponseGzipped(response.headers))?response.pipe(createGunzip()):response; + const errorResponse = (isResponseGzipped(response.headers))?response.pipe(createGunzip()):response; errorResponse.pipe(concatStream( {encoding: 'string'}, function errorBodyDispatcher(body) { if (body.length > 0) { - var bodyMsg = (typeof body === 'string' || body instanceof String) ? body : body.toString(); - var contentType = response.headers['content-type']; + const bodyMsg = (typeof body === 'string' || body instanceof String) ? body : body.toString(); + const contentType = response.headers['content-type']; clientError.body = ((typeof contentType === 'string' || contentType instanceof String) && /^application\/([^+]+\+)?json(\s*;.*)?$/.test(contentType)) ? @@ -1065,7 +1065,7 @@ function ResponseSelector(operation) { } function operationResultPromise(fullfilled, rejected) { /*jshint validthis:true */ - var operation = this; + const operation = this; switch (operation.outputMode) { case 'none': @@ -1080,7 +1080,7 @@ function operationResultPromise(fullfilled, rejected) { } operation.outputMode = 'promise'; - var promise = new Promise(function promiseDispatcher(resolve, reject) { + const promise = new Promise(function promiseDispatcher(resolve, reject) { if (operation.done !== true) { if (resolve) { operation.resolve = resolve; @@ -1109,9 +1109,9 @@ function resolvedPromise(operation, resolve) { return; } - var data = operation.data; - var hasData = (data != null); - var dataLen = hasData ? data.length : null; + const data = operation.data; + const hasData = (data != null); + const dataLen = hasData ? data.length : null; if(hasData && dataLen) { for(let i=0; i 1) { firstError.otherErrors = errorArray.slice(1); } @@ -1163,7 +1163,7 @@ function rejectedPromise(operation, reject) { } function operationResultStream() { /*jshint validthis:true */ - var operation = this; + const operation = this; switch (operation.outputMode) { case 'none': @@ -1177,8 +1177,8 @@ function operationResultStream() { throw new Error('already created stream'); } - var streamArg = (arguments.length > 0) ? arguments[0] : null; - var streamMode = null; + const streamArg = (arguments.length > 0) ? arguments[0] : null; + let streamMode = null; if (streamArg === null) { streamMode = operation.streamDefaultMode; operation.outputStreamMode = streamMode; @@ -1194,7 +1194,7 @@ function operationResultStream() { } operation.outputMode = streamMode+'Stream'; - var outputStream = null; + let outputStream = null; switch(streamMode) { case 'chunked': outputStream = through2(); @@ -1210,9 +1210,9 @@ function operationResultStream() { } operation.outputStream = outputStream; - var error = operation.error; + const error = operation.error; if (error != null) { - var i = 0; + let i = 0; for (; i < error.length; i++) { outputStream.emit('error', error[i]); } @@ -1223,7 +1223,7 @@ function operationResultStream() { } function operationErrorListener(error) { /*jshint validthis:true */ - var operation = this; + const operation = this; if(operation.client.connectionParams.apiKey){ if(error.statusCode === 401 && operation.expiration <= (new Date())){ if(!operation.lockAccessToken){ @@ -1245,7 +1245,7 @@ function operationErrorListener(error) { operation.done = true; - var outputStream = operation.outputStream; + const outputStream = operation.outputStream; if (outputStream != null) { outputStream.end(); diff --git a/lib/rest-server-properties.js b/lib/rest-server-properties.js index 12f6ab63..ee6c0f43 100644 --- a/lib/rest-server-properties.js +++ b/lib/rest-server-properties.js @@ -2,9 +2,9 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); /** * Provides functions to modify the properties of the REST server for @@ -28,14 +28,14 @@ function RESTServerProperties(client) { * @returns {object} the properties */ RESTServerProperties.prototype.read = function readRESTServerProperties() { - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'GET'; requestOptions.headers = { 'Accept': 'application/json' }; requestOptions.path = '/v1/config/properties'; - var operation = new Operation( + const operation = new Operation( 'read REST server properties', this.client, requestOptions, 'empty', 'single' ); @@ -45,9 +45,9 @@ RESTServerProperties.prototype.read = function readRESTServerProperties() { /** @ignore */ function RESTServerPropertiesOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var statusCode = operation.responseStatusCode; + const statusCode = operation.responseStatusCode; return (statusCode === 204 || statusCode === 200); } @@ -62,14 +62,14 @@ RESTServerProperties.prototype.write = function writeRESTServerProperties(proper throw new Error('cannot write with missing properties object'); } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'PUT'; requestOptions.headers = { 'Content-Type': 'application/json' }; requestOptions.path = '/v1/config/properties'; - var operation = new Operation( + const operation = new Operation( 'write REST server properties', this.client, requestOptions, 'single', 'empty' ); operation.outputTransform = RESTServerPropertiesOutputTransform; diff --git a/lib/rows.js b/lib/rows.js index 61dbad31..f24b72b2 100644 --- a/lib/rows.js +++ b/lib/rows.js @@ -64,13 +64,13 @@ function Rows(client) { * @returns {Promise} A Promise. */ Rows.prototype.query = function queryRows() { - let args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 1) { throw new Error('built plan required'); } - let builtPlan = args[0], + const builtPlan = args[0], options = (args.length >= 2) ? args[1] : null; return queryRowsImpl(this, builtPlan, null, options, args[2]); @@ -87,12 +87,13 @@ function queryRowsImpl(self, builtPlan, streamType, options, bindingArg, graphql } function queryRowsOperationImpl(self, builtPlan, streamType, options, bindingArg, graphqlQuery) { + const validFormats = ['json','xml','csv'], + validStructures = ['object','array'], + validColumnTypes = ['rows','header'], + validComplexValues = ['inline','reference'], + validStreamTypes = ['chunked','object','sequence']; + let sep = '?', - validFormats = ['json','xml','csv'], - validStructures = ['object','array'], - validColumnTypes = ['rows','header'], - validComplexValues = ['inline','reference'], - validStreamTypes = ['chunked','object','sequence'], // set defaults format = 'json', structure = 'object', @@ -237,7 +238,7 @@ function queryRowsOperationImpl(self, builtPlan, streamType, options, bindingArg } } - let requestOptions = mlutil.newRequestOptions(connectionParams, endpoint, 'POST'); + const requestOptions = mlutil.newRequestOptions(connectionParams, endpoint, 'POST'); requestOptions.headers = { 'Content-Type': contentTypeHeader, 'Accept': acceptHeader @@ -291,7 +292,7 @@ function queryContentType(builtPlan, queryType) { const validQueryTypes = ['json', 'sparql', 'sql', 'dsl']; if (validQueryTypes.indexOf(queryType) < 0) { throw new Error('invalid queryType "' + queryType + '"'); - } else if (queryType != 'json' && typeof builtPlan != 'string' && !(builtPlan instanceof String)) { + } else if (queryType != 'json' && typeof builtPlan !== 'string' && !(builtPlan instanceof String)) { throw new Error('queryType "' + queryType + '" must be provided as string'); } @@ -318,15 +319,15 @@ function queryContentType(builtPlan, queryType) { * @returns {ReadableStream} A readable stream. */ Rows.prototype.queryAsStream = function queryAsStreamRows() { - let args = mlutil.asArray.apply(null, arguments), - streamType = 'chunked', // default + const args = mlutil.asArray.apply(null, arguments); + let streamType = 'chunked', // default options = null; if (args.length < 1) { throw new Error('built plan required'); } - let builtPlan = args[0]; + const builtPlan = args[0]; if (args.length === 2) { if (typeof args[1] === 'string' || args[1] instanceof String) { @@ -414,7 +415,7 @@ Rows.prototype.generateView = function generateViewRows(builtPlan, schema, view, throw new Error('view cannot be null or empty'); } - let acceptHeader = 'application/xml'; + const acceptHeader = 'application/xml'; const contentTypeHeader = queryContentType(builtPlan, queryType); const endpoint = '/v1/rows?output=generateView&schemaName='+schema+'&viewName='+view; @@ -475,7 +476,7 @@ Rows.prototype.generateView = function generateViewRows(builtPlan, schema, view, */ Rows.prototype.queryAll = function queryAllDocumentsImpl(batchView, jobOptions){ - let path = '/v1/internal/viewinfo'; + const path = '/v1/internal/viewinfo'; const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'POST'); requestOptions.headers = { @@ -483,7 +484,7 @@ Rows.prototype.generateView = function generateViewRows(builtPlan, schema, view, 'Content-Type': 'application/json' }; - let operation = new Operation( + const operation = new Operation( 'read viewInfo', this.client, requestOptions, 'single', 'single' ); if (batchView instanceof planBuilder.Plan) { @@ -492,7 +493,7 @@ Rows.prototype.generateView = function generateViewRows(builtPlan, schema, view, operation.requestBody = batchView; } - let jobState = { + const jobState = { docInstance : this, requesterCount: 0, rowsReadSuccessfully:0, @@ -623,26 +624,26 @@ Rows.prototype.generateView = function generateViewRows(builtPlan, schema, view, */ Rows.prototype.execute = function executeRows() { - let args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 1) { throw new Error('built plan required'); } - let builtPlan = args[0], options = (args.length >= 2 && args[1])?args[1] : {}; + const builtPlan = args[0], options = (args.length >= 2 && args[1])?args[1] : {}; // opticExecute is an internal flag to ensure output doesn't default to anything. options.opticExecute = true; queryRowsImpl(this, builtPlan, null, options, args[2]); }; Rows.prototype.graphQL = function graphqlRows() { - let args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); if (args.length < 1) { throw new Error('graphql query required'); } - let options = (args.length >= 2) ? args[1] : null; + const options = (args.length >= 2) ? args[1] : null; return queryRowsImpl(this, null, null, options,null, args[0]); }; @@ -702,10 +703,10 @@ function onQueryAllRows(jobState, readerId, batchNum) { finishOnQueryAllRows(jobState); return; } - let lowerBound = bigInt((currentBatchNum - 1) * jobState.requestBatchSize); - let upperBound = (currentBatchNum === jobState.numberOfBatches) ? '-1' : + const lowerBound = bigInt((currentBatchNum - 1) * jobState.requestBatchSize); + const upperBound = (currentBatchNum === jobState.numberOfBatches) ? '-1' : bigInt(lowerBound + jobState.requestBatchSize -1); - let options = { + const options = { bindings: {ML_LOWER_BOUND:lowerBound, ML_UPPER_BOUND:upperBound}, format: jobState.jobOptions.rowFormat, structure: jobState.jobOptions.rowStructure, diff --git a/lib/server-exec.js b/lib/server-exec.js index ddf1a40b..cc934500 100644 --- a/lib/server-exec.js +++ b/lib/server-exec.js @@ -2,10 +2,10 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var qs = require('qs'); -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const qs = require('qs'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); function execOutputTransform(headers, data) { /*jshint validthis:true */ @@ -13,7 +13,7 @@ function execOutputTransform(headers, data) { return []; } - var contentType = headers['content-type'][0]; + let contentType = headers['content-type'][0]; if (typeof contentType === 'string' || contentType instanceof String) { contentType = contentType.replace(/;.*$/, ''); } @@ -39,8 +39,8 @@ function execOutputTransform(headers, data) { }; } - var primitive = headers['x-primitive'][0]; - var value = null; + const primitive = headers['x-primitive'][0]; + let value = null; switch(primitive) { case 'node()': return { @@ -102,7 +102,7 @@ function execOutputTransform(headers, data) { case 'unsignedLong': value = data.content; if (isFinite(value)) { - var number = Number(value); + const number = Number(value); if (Math.abs(number) < 9007199254740992) { value = number; } @@ -224,10 +224,10 @@ function serverInvoke() { /** @ignore */ function serverExec(execName, args) { /*jshint validthis:true */ - var client = this; + const client = this; - var operationDesc = null; - var execType = null; + let operationDesc = null; + let execType = null; if (execName === 'invoke') { operationDesc = 'invoke code on server'; execType = execName; @@ -240,13 +240,13 @@ function serverExec(execName, args) { throw new Error('must specify the source to '+operationDesc); } - var isInvoke = (execType === 'invoke'); + const isInvoke = (execType === 'invoke'); - var arg = args[0]; + const arg = args[0]; - var source = isInvoke ? arg.path : arg.source; - var variables = null; - var txid = null; + let source = isInvoke ? arg.path : arg.source; + let variables = null; + let txid = null; if (source !== void 0) { variables = arg.variables; txid = mlutil.convertTransaction(arg.txid); @@ -257,7 +257,7 @@ function serverExec(execName, args) { } } - var body = {}; + const body = {}; if (isInvoke) { body.module = source; } else { @@ -267,8 +267,8 @@ function serverExec(execName, args) { body.vars = JSON.stringify(variables); } - var endpoint = isInvoke? '/v1/invoke' : '/v1/eval'; - var sep = '?'; + let endpoint = isInvoke? '/v1/invoke' : '/v1/eval'; + let sep = '?'; if (txid != null) { endpoint += sep+'txid='+mlutil.getTxidParam(txid); sep = '&'; @@ -281,7 +281,7 @@ function serverExec(execName, args) { }; mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( operationDesc, client, requestOptions, 'single', 'multipart' ); operation.requestBody = qs.stringify(body); diff --git a/lib/transactions.js b/lib/transactions.js index a4a28ac7..f010ef4c 100644 --- a/lib/transactions.js +++ b/lib/transactions.js @@ -2,9 +2,9 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); /** * Provides functions to open, commit, or rollback multi-statement @@ -16,9 +16,9 @@ var Operation = require('./operation.js'); /** @ignore */ function openOutputTransform(headers/*, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var txid = headers.location.substring('/v1/transactions/'.length); + const txid = headers.location.substring('/v1/transactions/'.length); if (operation.withState === true) { return new mlutil.Transaction(txid, operation.rawHeaders['set-cookie']); @@ -57,17 +57,17 @@ function Transactions(client) { * will be removed in the next major release. */ Transactions.prototype.open = function openTransaction() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; - var transactionName = null; - var timeLimit = null; - var withState = null; + let transactionName = null; + let timeLimit = null; + let withState = null; - var arg = (argLen > 0) ? args[0] : null; + let arg = (argLen > 0) ? args[0] : null; if (argLen > 1 || (typeof arg === 'string' || arg instanceof String) || (typeof arg === 'number' || arg instanceof Number) || (typeof arg === 'boolean')) { - var i=0; + let i=0; for (; i < argLen; i++) { arg = args[i]; if (transactionName === null && (typeof arg === 'string' || arg instanceof String)) { @@ -88,8 +88,8 @@ Transactions.prototype.open = function openTransaction() { withState = arg.withState; } - var path = '/v1/transactions'; - var sep = '?'; + let path = '/v1/transactions'; + let sep = '?'; if (transactionName != null) { path += sep+'name='+encodeURIComponent(transactionName); sep = '&'; @@ -100,7 +100,7 @@ Transactions.prototype.open = function openTransaction() { const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'POST'); - var operation = new Operation( + const operation = new Operation( 'open transaction', this.client, requestOptions, 'empty', 'empty' ); operation.validStatusCodes = [303]; @@ -121,8 +121,8 @@ Transactions.prototype.open = function openTransaction() { * @returns {object} information about the transaction */ Transactions.prototype.read = function readTransaction(txidRaw) { - var txid = mlutil.convertTransaction(txidRaw); - var path = + const txid = mlutil.convertTransaction(txidRaw); + const path = '/v1/transactions/'+mlutil.getTxidParam(txid, 'read')+'?format=json'; const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'GET'); @@ -131,7 +131,7 @@ Transactions.prototype.read = function readTransaction(txidRaw) { }; mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( 'read transaction', this.client, requestOptions, 'empty', 'single' ); operation.txid = txid; @@ -166,7 +166,7 @@ Transactions.prototype.rollback = function rollbackTransaction(txid) { /** @ignore */ function finishOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; return { txid: operation.txid, @@ -175,14 +175,14 @@ function finishOutputTransform(/*headers, data*/) { } /** @ignore */ function finishTransaction(client, result, txidRaw) { - var txid = mlutil.convertTransaction(txidRaw); - var path = + const txid = mlutil.convertTransaction(txidRaw); + const path = '/v1/transactions/'+mlutil.getTxidParam(txid, result)+'?result='+result; const requestOptions = mlutil.newRequestOptions(client.getConnectionParams(), path, 'POST'); mlutil.addTxidHeaders(requestOptions, txid); - var operation = new Operation( + const operation = new Operation( result+' transaction', client, requestOptions, 'empty', 'empty' ); operation.txid = txid; diff --git a/lib/transforms.js b/lib/transforms.js index 1a69e2fb..e3c5338d 100644 --- a/lib/transforms.js +++ b/lib/transforms.js @@ -2,16 +2,16 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); /** @ignore */ function nameErrorTransform(message) { /*jshint validthis:true */ - var operation = this; + const operation = this; - var name = operation.name; + const name = operation.name; return (name == null) ? message : (message+' (on '+name+' transform)'); } @@ -26,7 +26,7 @@ function nameErrorTransform(message) { /** @ignore */ function emptyOutputTransform(/*headers, data*/) { /*jshint validthis:true */ - var operation = this; + const operation = this; return { name: operation.name @@ -59,11 +59,11 @@ Transforms.prototype.read = function readTransform(name) { throw new Error('must specify name when reading the transform source'); } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'GET'; requestOptions.path = '/v1/config/transforms/'+encodeURIComponent(name); - var operation = new Operation( + const operation = new Operation( 'read transform', this.client, requestOptions, 'empty', 'single' ); operation.name = name; @@ -82,21 +82,21 @@ Transforms.prototype.read = function readTransform(name) { * @param {object|string} source - the source for the transform */ Transforms.prototype.write = function writeTransform() { - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen === 0) { throw new Error('no arguments for writing an extension library'); } - var name = null; - var title = null; - var description = null; - var provider = null; - var version = null; - var format = null; - var source = null; + let name = null; + let title = null; + let description = null; + let provider = null; + let version = null; + let format = null; + let source = null; - var params = null; + let params = null; if (argLen === 1) { params = args[0]; name = params.name; @@ -117,7 +117,7 @@ Transforms.prototype.write = function writeTransform() { throw new Error('must specify name, format, and source when writing a transform'); } - var contentType = null; + let contentType = null; switch(format) { case 'javascript': contentType = 'application/javascript'; @@ -132,9 +132,9 @@ Transforms.prototype.write = function writeTransform() { throw new Error('unsupported transform format '+format); } - var endpoint = '/v1/config/transforms/'+encodeURIComponent(name); + let endpoint = '/v1/config/transforms/'+encodeURIComponent(name); - var sep = '?'; + let sep = '?'; if (title != null) { endpoint += sep+'title='+encodeURIComponent(title); if (sep === '?') {sep = '&';} @@ -152,14 +152,14 @@ Transforms.prototype.write = function writeTransform() { if (sep === '?') {sep = '&';} } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'PUT'; requestOptions.headers = { 'Content-Type': contentType }; requestOptions.path = endpoint; - var operation = new Operation( + const operation = new Operation( 'write transform', this.client, requestOptions, 'single', 'empty' ); operation.name = name; @@ -181,11 +181,11 @@ Transforms.prototype.remove = function removeTransform(name) { throw new Error('must specify name when deleting the transform source'); } - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'DELETE'; requestOptions.path = '/v1/config/transforms/'+encodeURIComponent(name); - var operation = new Operation( + const operation = new Operation( 'remove transform', this.client, requestOptions, 'empty', 'empty' ); operation.name = name; @@ -204,14 +204,14 @@ Transforms.prototype.remove = function removeTransform(name) { * on the server */ Transforms.prototype.list = function listTransforms() { - var requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); + const requestOptions = mlutil.copyProperties(this.client.getConnectionParams()); requestOptions.method = 'GET'; requestOptions.headers = { 'Accept': 'application/json' }; requestOptions.path = '/v1/config/transforms'; - var operation = new Operation( + const operation = new Operation( 'list transforms', this.client, requestOptions, 'empty', 'single' ); diff --git a/lib/values-builder.js b/lib/values-builder.js index b3b4d890..4c93caff 100644 --- a/lib/values-builder.js +++ b/lib/values-builder.js @@ -4,8 +4,8 @@ 'use strict'; -var mlutil = require('./mlutil.js'); -var qb = require('./query-builder.js').builder; +const mlutil = require('./mlutil.js'); +const qb = require('./query-builder.js').builder; /** * A source of datatyped values from a JSON property, @@ -113,18 +113,18 @@ function ValueBuilder() { */ function valuesFromIndexes() { /*jshint validthis:true */ - var self = (this instanceof ValueBuilder) ? this : new ValueBuilder(); + const self = (this instanceof ValueBuilder) ? this : new ValueBuilder(); - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; - var isRangeIndex = { + const isRangeIndex = { 'element': true, 'field': true, 'json-property': true, 'path-index': true }; - var isGeoLocationIndex = { + const isGeoLocationIndex = { 'geo-attr-pair': true, 'geo-elem': true, 'geo-elem-pair': true, @@ -133,10 +133,10 @@ function valuesFromIndexes() { 'geo-path': true }; - var arg = null; - var firstKey = null; - var range = null; - for (var i=0; i < argLen; i++) { + let arg = null; + let firstKey = null; + let range = null; + for (let i=0; i < argLen; i++) { arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { args[i] = {range: qb.property(arg)}; @@ -174,15 +174,15 @@ ValueBuilder.prototype.fromIndexes = valuesFromIndexes; * @returns {valuesBuilder.BuiltQuery} a built query */ ValueBuilder.prototype.where = function valuesWhere() { - var self = this; + const self = this; - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; // TODO: if empty, clear the clause - var parsedQuery = null; - var fragmentScope = null; - var queries = null; + let parsedQuery = null; + let fragmentScope = null; + let queries = null; switch(argLen) { case 0: @@ -190,8 +190,8 @@ ValueBuilder.prototype.where = function valuesWhere() { self.whereClause = {query: {queries: [qb.and()]}}; break; default: - for (var i=0; i < argLen; i++) { - var arg = args[i]; + for (let i=0; i < argLen; i++) { + const arg = args[i]; if (parsedQuery == null) { parsedQuery = arg.parsedQuery; if (parsedQuery != null) { @@ -244,17 +244,17 @@ ValueBuilder.prototype.where = function valuesWhere() { * @returns {valuesBuilder.BuiltQuery} a built query */ ValueBuilder.prototype.aggregates = function valuesAggregates() { - var self = this; + const self = this; - var args = mlutil.asArray.apply(null, arguments); - var argLen = args.length; + const args = mlutil.asArray.apply(null, arguments); + const argLen = args.length; if (argLen < 1) { throw new Error('aggregates must specify at least one built-in function or UDF'); } - var aggregateFunctions = []; - for (var i=0; i < argLen; i++) { - var arg = args[i]; + const aggregateFunctions = []; + for (let i=0; i < argLen; i++) { + const arg = args[i]; if (typeof arg === 'string' || arg instanceof String) { aggregateFunctions.push({apply:arg}); } else if (arg.udf !== void 0) { @@ -318,9 +318,9 @@ function udf() { * @returns {valuesBuilder.BuiltQuery} a built query */ ValueBuilder.prototype.slice = function valuesSlice() { - var self = this; + const self = this; - var args = mlutil.asArray.apply(null, arguments); + const args = mlutil.asArray.apply(null, arguments); // TODO: if empty, clear the clause @@ -342,23 +342,23 @@ ValueBuilder.prototype.slice = function valuesSlice() { * @returns {valuesBuilder.BuiltQuery} a built query */ ValueBuilder.prototype.withOptions = function valuesWithOptions() { - var self = this; + const self = this; // TODO: share with values.js - var optionKeyMapping = { + const optionKeyMapping = { values: 'values-option', forestNames: 'forest-names' }; // TODO: reuse key copy logic with query-build withOptions - var withOptionsClause = {}; + const withOptionsClause = {}; if (0 < arguments.length) { - var arg = arguments[0]; - var argKeys = Object.keys(arg); - for (var i=0; i < argKeys.length; i++) { - var key = argKeys[i]; + const arg = arguments[0]; + const argKeys = Object.keys(arg); + for (let i=0; i < argKeys.length; i++) { + const key = argKeys[i]; if (optionKeyMapping[key] !== undefined) { - var value = arg[key]; + const value = arg[key]; if (value !== undefined) { withOptionsClause[key] = value; } @@ -393,20 +393,20 @@ function valuesUri() { * @returns {valuesBuilder.BuiltQuery} a built query */ function copyFromValueBuilder(otherValueBuilder) { - var tb = new ValueBuilder(); + const tb = new ValueBuilder(); // TODO: share with QueryBuilder if (otherValueBuilder != null) { - var clauseKeys = [ + const clauseKeys = [ 'fromIndexesClause', 'whereClause', 'aggregatesClause', 'sliceClause', 'withOptionsClause' ]; - var isString = (typeof otherValueBuilder === 'string' || otherValueBuilder instanceof String); - var other = isString ? + const isString = (typeof otherValueBuilder === 'string' || otherValueBuilder instanceof String); + const other = isString ? JSON.parse(otherValueBuilder) : otherValueBuilder; - for (var i=0; i < clauseKeys.length; i++){ - var key = clauseKeys[i]; - var value = other[key]; + for (let i=0; i < clauseKeys.length; i++){ + const key = clauseKeys[i]; + const value = other[key]; if (value != null) { // structuredClone instead of clone to avoid preserving prototype tb[key] = isString ? value : structuredClone(value); diff --git a/lib/values.js b/lib/values.js index 7290f728..308dfbd1 100644 --- a/lib/values.js +++ b/lib/values.js @@ -2,9 +2,9 @@ * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ 'use strict'; -var requester = require('./requester.js'); -var mlutil = require('./mlutil.js'); -var Operation = require('./operation.js'); +const requester = require('./requester.js'); +const mlutil = require('./mlutil.js'); +const Operation = require('./operation.js'); /** * Provides functions to project tuples (aka rows) of values out of documents. @@ -40,9 +40,9 @@ Values.prototype.read = function readValues() { if (arguments.length === 0 || arguments.length > 2) { throw new Error('incorrect number of arguments to read values'); } - var arg = arguments[0]; + const arg = arguments[0]; - var timestamp = null; + let timestamp = null; if (arguments.length === 2) { if (arguments[1] instanceof mlutil.Timestamp) { timestamp = arguments[1]; @@ -51,49 +51,49 @@ Values.prototype.read = function readValues() { } } - var structuredef = { + const structuredef = { name: 'structuredef', style: 'consistent' }; - var indexesClause = arg.fromIndexesClause; - var indexesLength = Array.isArray(indexesClause) ? indexesClause.length : 0; + const indexesClause = arg.fromIndexesClause; + const indexesLength = Array.isArray(indexesClause) ? indexesClause.length : 0; if (indexesLength < 1) { throw new Error('must specify indexes to read values'); } - var isValues = (indexesLength === 1); - var structureName = isValues ? 'values' : 'tuples'; + const isValues = (indexesLength === 1); + const structureName = isValues ? 'values' : 'tuples'; if (isValues) { - var indexObject = indexesClause[0]; - var indexKey = Object.keys(indexObject)[0]; + const indexObject = indexesClause[0]; + const indexKey = Object.keys(indexObject)[0]; structuredef[indexKey] = indexObject[indexKey]; } else { structuredef.indexes = indexesClause; } - var aggregatesClause = arg.aggregatesClause; + const aggregatesClause = arg.aggregatesClause; if (aggregatesClause !== void 0) { structuredef.aggregate = aggregatesClause.aggregates; } - var structureOptions = {}; + const structureOptions = {}; structureOptions[structureName] = [structuredef]; - var withOptionsClause = arg.withOptionsClause; + const withOptionsClause = arg.withOptionsClause; if (withOptionsClause !== void 0) { // TODO: share with value-builder.js - var optionKeyMapping = { + const optionKeyMapping = { values: 'values-option', forestNames: 'forest-names' }; - var optionsKeys = Object.keys(withOptionsClause); - var key = null; - var mapping = null; - var value = null; - for (var i=0; i < optionsKeys.length; i++) { + const optionsKeys = Object.keys(withOptionsClause); + let key = null; + let mapping = null; + let value = null; + for (let i=0; i < optionsKeys.length; i++) { key = optionsKeys[i]; mapping = optionKeyMapping[key]; if (mapping !== void 0) { @@ -109,23 +109,23 @@ Values.prototype.read = function readValues() { } } - var searchBody = { + const searchBody = { options: structureOptions }; - var whereClause = arg.whereClause; + const whereClause = arg.whereClause; if (whereClause != null) { - var query = whereClause.query; - var parsedQuery = whereClause.parsedQuery; - var fragmentScope = whereClause['fragment-scope']; + const query = whereClause.query; + const parsedQuery = whereClause.parsedQuery; + const fragmentScope = whereClause['fragment-scope']; if (query != null) { searchBody.query = query; } if (parsedQuery != null) { searchBody.qtext = parsedQuery.qtext; - var constraintBindings = parsedQuery.constraint; - var termBinding = parsedQuery.term; + const constraintBindings = parsedQuery.constraint; + const termBinding = parsedQuery.term; if (constraintBindings != null) { structureOptions.constraint = constraintBindings; } @@ -138,17 +138,17 @@ Values.prototype.read = function readValues() { } } - var pageStart = null; - var pageLength = null; - var transform = null; + let pageStart = null; + let pageLength = null; + let transform = null; - var sliceClause = arg.sliceClause; + const sliceClause = arg.sliceClause; if (sliceClause !== void 0) { - var sliceStart = sliceClause['page-start']; + const sliceStart = sliceClause['page-start']; if (sliceStart !== void 0) { pageStart = sliceStart; } - var sliceLength = sliceClause['page-length']; + const sliceLength = sliceClause['page-length']; if (sliceLength !== void 0) { pageLength = sliceLength; } @@ -156,7 +156,7 @@ Values.prototype.read = function readValues() { transform = sliceClause['document-transform']; } - var endpoint = '/v1/values/structuredef?format=json'; + let endpoint = '/v1/values/structuredef?format=json'; if (pageStart !== null) { endpoint += '&start='+pageStart; @@ -180,7 +180,7 @@ Values.prototype.read = function readValues() { 'Accept': 'application/json' }; - var operation = new Operation( + const operation = new Operation( 'query values', this.client, requestOptions, 'single', 'single' ); operation.validStatusCodes = [200, 204]; diff --git a/lib/www-authenticate-patched/md5.js b/lib/www-authenticate-patched/md5.js index ba61d430..10a5df0f 100644 --- a/lib/www-authenticate-patched/md5.js +++ b/lib/www-authenticate-patched/md5.js @@ -9,7 +9,7 @@ /* * Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. */ -var crypto= require('crypto'); +const crypto= require('crypto'); function md5(s) { return crypto.createHash('md5').update(s).digest('hex'); diff --git a/lib/www-authenticate-patched/parsers.js b/lib/www-authenticate-patched/parsers.js index 1bda7820..6998fc40 100644 --- a/lib/www-authenticate-patched/parsers.js +++ b/lib/www-authenticate-patched/parsers.js @@ -10,25 +10,25 @@ * Licensed under the MIT license. */ -var ParseAuth= /(\w+)\s+(.*)/ // -> scheme, params +const ParseAuth= /(\w+)\s+(.*)/ // -> scheme, params , Separators= /([",=])/ ; function parse_params(header) { // This parser will definitely fail if there is more than one challenge - var tok, _i, _len, key, value; - var state= 0; //0: token, - var m= header.split(Separators) + let tok, _i, _len, key, value; + let state= 0; //0: token, + const m= header.split(Separators); for (_i = 0, _len = m.length; _i < _len; _i++) { tok = m[_i]; - if (!tok.length) continue; + if (!tok.length) {continue;} switch (state) { case 0: // token key= tok.trim(); state= 1; // expect equals continue; case 1: // expect equals - if ('=' != tok) return 'Equal sign was expected after '+key; + if ('=' != tok) {return 'Equal sign was expected after '+key;} state= 2; continue; case 2: // expect value @@ -68,7 +68,7 @@ function parse_params(header) { return 'Unexpected token ('+tok+') after '+value+'"'; } case 9: // expect commma - if (',' != tok) return 'Comma expected after '+value; + if (',' != tok) {return 'Comma expected after '+value;} state= 0; continue; } @@ -87,10 +87,10 @@ function parse_params(header) { function Parse_WWW_Authenticate(to_parse) { - var m= to_parse.match(ParseAuth); + const m= to_parse.match(ParseAuth); this.scheme= m[1]; this.parms= {}; - var err= this.parse_params(m[2]); + const err= this.parse_params(m[2]); if (err) { this.scheme= ''; this.parms= {}; @@ -102,7 +102,7 @@ function Parse_Authentication_Info(to_parse) { this.scheme= 'Digest'; this.parms= {}; - var err= this.parse_params(to_parse); + const err= this.parse_params(to_parse); if (err) { this.scheme= ''; this.parms= {}; diff --git a/lib/www-authenticate-patched/user-credentials.js b/lib/www-authenticate-patched/user-credentials.js index e9128a3a..3d3555af 100644 --- a/lib/www-authenticate-patched/user-credentials.js +++ b/lib/www-authenticate-patched/user-credentials.js @@ -11,7 +11,7 @@ */ -var md5= require('./md5'); +const md5= require('./md5'); /* * Hide the password. Uses the password to form authorization strings, @@ -25,14 +25,14 @@ function user_credentials(username,password,options) { return username; } - var basic_string= options && options.hide_basic ? + const basic_string= options && options.hide_basic ? '' : (!password && password !== '' ? Buffer.from(username, 'ascii').toString('base64') : Buffer.from(username+':'+password, 'ascii').toString('base64') - ) + ); function Credentials() { this.username= username; @@ -40,18 +40,18 @@ function user_credentials(username,password,options) { Credentials.prototype.basic= function() { return basic_string; - } + }; Credentials.prototype.digest= function(realm) { return !password && password !== '' ? md5(username+':'+realm) : - md5(username+':'+realm+':'+password) - } + md5(username+':'+realm+':'+password); + }; Credentials.prototype.is_user_credentials= function() { return true; - } + }; return new Credentials; } diff --git a/lib/www-authenticate-patched/www-authenticate.js b/lib/www-authenticate-patched/www-authenticate.js index f4d818ac..5b85f9f7 100644 --- a/lib/www-authenticate-patched/www-authenticate.js +++ b/lib/www-authenticate-patched/www-authenticate.js @@ -12,7 +12,7 @@ 'use strict'; -var crypto= require('crypto') +const crypto= require('crypto') , parsers= require('./parsers') , md5= require('./md5') , user_credentials= require('./user-credentials') @@ -29,32 +29,32 @@ function hex8(num) return ('00000000' + num.toString(16)).slice(-8); } -var www_authenticator = function(username,password,options) +const www_authenticator = function(username,password,options) { if (2 == arguments.length && toString.call(password) != '[object String]') { options= password; password= null; } - var credentials= user_credentials(username,password) - var cnonce; + const credentials= user_credentials(username,password); + let cnonce; if (options) { if (toString.call(options.cnonce) == '[object String]') - cnonce= options.cnonce; + {cnonce= options.cnonce;} } - if (cnonce === void 0) cnonce= crypto.pseudoRandomBytes(8).toString('hex'); - var parse_header= function(www_authenticate) + if (cnonce === void 0) {cnonce= crypto.pseudoRandomBytes(8).toString('hex');} + const parse_header= function(www_authenticate) { function Authenticator() { function note_error(err) { - this.err= err + this.err= err; } - var nc= 0; + let nc= 0; - var parsed= new parsers.WWW_Authenticate(www_authenticate); - if (parsed.err) return note_error(parsed.err); - var auth_parms= this.parms= parsed.parms; + const parsed= new parsers.WWW_Authenticate(www_authenticate); + if (parsed.err) {return note_error(parsed.err);} + const auth_parms= this.parms= parsed.parms; this.cnonce= cnonce; switch(parsed.scheme) { @@ -83,7 +83,7 @@ var www_authenticator = function(username,password,options) var qop= auth_parms.qop; if (!qop) { this.authorize= function(method,digestURI) { - var ha2= md5(method+':'+digestURI); + const ha2= md5(method+':'+digestURI); return fixed+ ' uri="'+digestURI+'",'+ ' response="'+md5(ha1+':'+nonce+':'+ha2)+'",'; @@ -91,12 +91,12 @@ var www_authenticator = function(username,password,options) return; } else { - var qopa= qop.split(','); - var _i, _len; + const qopa= qop.split(','); + let _i, _len; for (_i = 0, _len = qopa.length; _i < _len; _i++) { if ('auth' === qopa[_i]) { var opaque= auth_parms.opaque; - var algorithm= auth_parms.algorithm; + let algorithm= auth_parms.algorithm; if (algorithm) { fixed+= ' algorithm="'+algorithm+'",'; } @@ -108,10 +108,10 @@ var www_authenticator = function(username,password,options) : ha1; this.authorize= function(method,digestURI) { - var ha2= md5(method+':'+digestURI); + const ha2= md5(method+':'+digestURI); nc= nc+1; - var hexed_nc= hex8(nc); - var s= fixed+ + const hexed_nc= hex8(nc); + let s= fixed+ ' uri="'+digestURI+'",'+ ' qop=auth,'+ ' nc='+hexed_nc+','+ @@ -142,8 +142,8 @@ var www_authenticator = function(username,password,options) function HigherLevel(credentials,options) { - this.credentials= credentials - this.options= options + this.credentials= credentials; + this.options= options; if (options && options.sendImmediately) { this.sendImmediately= true; } @@ -151,42 +151,42 @@ function HigherLevel(credentials,options) HigherLevel.prototype.get_challenge= function(request) { if (401 == request.statusCode && 'www-authenticate' in request.headers) { if (!this.parse_header) { - this.parse_header= www_authenticator(this.credentials,this.options) + this.parse_header= www_authenticator(this.credentials,this.options); } - this.challenge= this.parse_header(request.headers['www-authenticate']) + this.challenge= this.parse_header(request.headers['www-authenticate']); return this.challenge.err; } -} +}; HigherLevel.prototype._challenge= function() { if (!this.challenge) { if (this.sendImmediately) { // simulate receipt of a basic challenge - this.get_challenge(basic_challenge) - return this.challenge + this.get_challenge(basic_challenge); + return this.challenge; } - else return; // simply won't produce an 'Authorization' header + else {return;} // simply won't produce an 'Authorization' header } return this.challenge; -} +}; HigherLevel.prototype.authentication_string= function(method,digestURI) { - var challenge= this._challenge(); - if (!challenge) return; // simply won't produce an 'Authorization' header - if (challenge.err) return challenge.err; + const challenge= this._challenge(); + if (!challenge) {return;} // simply won't produce an 'Authorization' header + if (challenge.err) {return challenge.err;} return challenge.authorize(method,digestURI); -} +}; HigherLevel.prototype.authenticate_headers= function(headers,method,digestURI) { - var challenge= this._challenge(); - if (!challenge) return; // simply won't produce an 'Authorization' header - if (challenge.err) return challenge.err; + const challenge= this._challenge(); + if (!challenge) {return;} // simply won't produce an 'Authorization' header + if (challenge.err) {return challenge.err;} headers.authorization= challenge.authorize(method,digestURI); -} +}; HigherLevel.prototype.authenticate_request_options= function(request_options) { - var challenge= this._challenge(); - if (!challenge) return; // simply won't produce an 'Authorization' header - if (challenge.err) return challenge.err; - if (!request_options.headers) request_options.headers= {}; + const challenge= this._challenge(); + if (!challenge) {return;} // simply won't produce an 'Authorization' header + if (challenge.err) {return challenge.err;} + if (!request_options.headers) {request_options.headers= {};} request_options.headers.authorization= challenge.authorize(request_options.method,request_options.path); -} +}; module.exports = www_authenticator; module.exports.parsers= parsers; @@ -198,6 +198,6 @@ module.exports.authenticator= function(username,password,options) options= password; password= null; } - var credentials= user_credentials(username,password) + const credentials= user_credentials(username,password); return new HigherLevel(credentials,options); -} \ No newline at end of file +}; \ No newline at end of file