flow like the river

This commit is contained in:
root 2025-11-07 00:06:12 +01:00
commit 013fe673f3
42435 changed files with 5764238 additions and 0 deletions

201
VISUALIZACION/node_modules/@elastic/transport/LICENSE generated vendored Executable file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021 Elastic and contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

49
VISUALIZACION/node_modules/@elastic/transport/README.md generated vendored Executable file
View file

@ -0,0 +1,49 @@
<img align="right" width="auto" height="auto" src="https://www.elastic.co/static-res/images/elastic-logo-200.png">
# Elastic Node.js Transport
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) [![Node CI](https://github.com/elastic/elastic-transport-js/actions/workflows/nodejs.yml/badge.svg)](https://github.com/elastic/elastic-transport-js/actions/workflows/nodejs.yml) [![codecov](https://codecov.io/gh/elastic/elastic-transport-js/branch/master/graph/badge.svg?token=4CU5AeB3FW)](https://codecov.io/gh/elastic/elastic-transport-js) [![NPM downloads](https://img.shields.io/npm/dm/@elastic/transport.svg?style=flat)](https://www.npmjs.com/package/@elastic/transport)
This is a HTTP transport Node.js library for communicate with [Elastic](http://elastic.co/) products,
like [Elasticsearch](https://github.com/elastic/elasticsearch).
## Install
```
npm install @elastic/transport
```
### Node.js support
NOTE: The minimum supported version of Node.js is `v14`.
The client versioning follows the Elastc Stack versioning, this means that
major, minor, and patch releases are done following a precise schedule that
often does not coincide with the [Node.js release](https://nodejs.org/en/about/releases/) times.
To avoid support insecure and unsupported versions of Node.js, the
client **will drop the support of EOL versions of Node.js between minor releases**.
Typically, as soon as a Node.js version goes into EOL, the client will continue
to support that version for at least another minor release. If you are using the client
with a version of Node.js that will be unsupported soon, you will see a warning
in your logs (the client will start logging the warning with two minors in advance).
Unless you are **always** using a supported version of Node.js,
we recommend defining the client dependency in your
`package.json` with the `~` instead of `^`. In this way, you will lock the
dependency on the minor release and not the major. (for example, `~7.10.0` instead
of `^7.10.0`).
| Node.js Version | Node.js EOL date | End of support |
| --------------- |------------------| ---------------------- |
| `8.x` | `December 2019` | `7.11` (early 2021) |
| `10.x` | `April 2021` | `7.12` (mid 2021) |
| `12.x` | `April 2022` | `8.2` (early 2022) |
| `14.x` | `April 2023` | `8.8` (early 2023) |
## API
## Usage
## License
This software is licensed under the [Apache 2 license](./LICENSE).

11
VISUALIZACION/node_modules/@elastic/transport/codecov.yml generated vendored Executable file
View file

@ -0,0 +1,11 @@
comment: off
coverage:
precision: 2
round: down
range: "95...100"
status:
project: yes
patch: yes
changes: no

84
VISUALIZACION/node_modules/@elastic/transport/index.d.ts generated vendored Executable file
View file

@ -0,0 +1,84 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Diagnostic, { events } from './lib/Diagnostic'
import Transport from './lib/Transport'
import {
BaseConnection,
HttpConnection,
UndiciConnection
} from './lib/connection'
import {
WeightedConnectionPool,
ClusterConnectionPool,
CloudConnectionPool,
BaseConnectionPool
} from './lib/pool'
import Serializer from './lib/Serializer'
import * as errors from './lib/errors'
export type {
Connection,
ConnectionOptions,
ConnectionRequestParams,
ConnectionRequestOptions,
ConnectionRequestOptionsAsStream,
ConnectionRequestResponse,
ConnectionRequestResponseAsStream
} from './lib/connection'
export type {
ConnectionPoolOptions,
GetConnectionOptions
} from './lib/pool'
export type {
TransportOptions,
TransportRequestParams,
TransportRequestOptions,
TransportRequestOptionsWithMeta,
TransportRequestOptionsWithOutMeta,
SniffOptions
} from './lib/Transport'
export type {
RequestBody,
RequestNDBody,
DiagnosticResult,
TransportResult,
HttpAgentOptions,
UndiciAgentOptions,
ApiKeyAuth,
BearerAuth
} from './lib/types'
export {
Diagnostic,
Transport,
WeightedConnectionPool,
ClusterConnectionPool,
BaseConnectionPool,
CloudConnectionPool,
BaseConnection,
HttpConnection,
UndiciConnection,
Serializer,
errors,
events
}

51
VISUALIZACION/node_modules/@elastic/transport/index.js generated vendored Executable file
View file

@ -0,0 +1,51 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
const { default: Diagnostic, events } = require('./lib/Diagnostic')
const Transport = require('./lib/Transport').default
const {
BaseConnection,
HttpConnection,
UndiciConnection
} = require('./lib/connection')
const {
BaseConnectionPool,
ClusterConnectionPool,
CloudConnectionPool,
WeightedConnectionPool
} = require('./lib/pool')
const Serializer = require('./lib/Serializer').default
const errors = require('./lib/errors')
module.exports = {
Diagnostic,
Transport,
BaseConnection,
HttpConnection,
UndiciConnection,
BaseConnectionPool,
ClusterConnectionPool,
CloudConnectionPool,
WeightedConnectionPool,
Serializer,
errors,
events
}

View file

@ -0,0 +1,34 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import { ElasticsearchClientError } from './errors';
import { ConnectionRequestOptions } from './connection';
import { ResurrectEvent } from './pool';
import { DiagnosticResult, DiagnosticResultResponse } from './types';
export type DiagnosticListener = (err: ElasticsearchClientError | null, meta: any | null) => void;
export type DiagnosticListenerFull = (err: ElasticsearchClientError | null, meta: DiagnosticResult | null) => void;
export type DiagnosticListenerFullResponse = (err: ElasticsearchClientError | null, meta: DiagnosticResultResponse | null) => void;
export type DiagnosticListenerLight = (err: ElasticsearchClientError | null, meta: ConnectionRequestOptions | null) => void;
export type DiagnosticListenerResurrect = (err: ElasticsearchClientError | null, meta: ResurrectEvent | null) => void;
export declare enum events {
RESPONSE = "response",
REQUEST = "request",
SNIFF = "sniff",
RESURRECT = "resurrect",
SERIALIZATION = "serialization",
DESERIALIZATION = "deserialization"
}
export default class Diagnostic extends EventEmitter {
on(event: 'request', listener: DiagnosticListenerFull): this;
on(event: 'response', listener: DiagnosticListenerFullResponse): this;
on(event: 'serialization', listener: DiagnosticListenerFull): this;
on(event: 'sniff', listener: DiagnosticListenerFull): this;
on(event: 'deserialization', listener: DiagnosticListenerLight): this;
on(event: 'resurrect', listener: DiagnosticListenerResurrect): this;
once(event: 'request', listener: DiagnosticListenerFull): this;
once(event: 'response', listener: DiagnosticListenerFullResponse): this;
once(event: 'serialization', listener: DiagnosticListenerFull): this;
once(event: 'sniff', listener: DiagnosticListenerFull): this;
once(event: 'deserialization', listener: DiagnosticListenerLight): this;
once(event: 'resurrect', listener: DiagnosticListenerResurrect): this;
off(event: string, listener: DiagnosticListener): this;
}

View file

@ -0,0 +1,58 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.events = void 0;
const events_1 = require("events");
const errors_1 = require("./errors");
var events;
(function (events) {
events["RESPONSE"] = "response";
events["REQUEST"] = "request";
events["SNIFF"] = "sniff";
events["RESURRECT"] = "resurrect";
events["SERIALIZATION"] = "serialization";
events["DESERIALIZATION"] = "deserialization";
})(events = exports.events || (exports.events = {}));
class Diagnostic extends events_1.EventEmitter {
on(event, listener) {
assertSupportedEvent(event);
super.on(event, listener);
return this;
}
once(event, listener) {
assertSupportedEvent(event);
super.once(event, listener);
return this;
}
off(event, listener) {
assertSupportedEvent(event);
super.off(event, listener);
return this;
}
}
exports.default = Diagnostic;
function assertSupportedEvent(event) {
if (!supportedEvents.includes(event)) {
throw new errors_1.ConfigurationError(`The event '${event}' is not supported.`);
}
}
// @ts-expect-error
const supportedEvents = Object.keys(events).map(key => events[key]);
//# sourceMappingURL=Diagnostic.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"Diagnostic.js","sourceRoot":"","sources":["../src/Diagnostic.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAEH,mCAAqC;AACrC,qCAAuE;AAWvE,IAAY,MAOX;AAPD,WAAY,MAAM;IAChB,+BAAqB,CAAA;IACrB,6BAAmB,CAAA;IACnB,yBAAe,CAAA;IACf,iCAAuB,CAAA;IACvB,yCAA+B,CAAA;IAC/B,6CAAmC,CAAA;AACrC,CAAC,EAPW,MAAM,GAAN,cAAM,KAAN,cAAM,QAOjB;AAED,MAAqB,UAAW,SAAQ,qBAAY;IAOlD,EAAE,CAAE,KAAa,EAAE,QAA4B;QAC7C,oBAAoB,CAAC,KAAK,CAAC,CAAA;QAC3B,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QACzB,OAAO,IAAI,CAAA;IACb,CAAC;IAQD,IAAI,CAAE,KAAa,EAAE,QAA4B;QAC/C,oBAAoB,CAAC,KAAK,CAAC,CAAA;QAC3B,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QAC3B,OAAO,IAAI,CAAA;IACb,CAAC;IAED,GAAG,CAAE,KAAa,EAAE,QAA4B;QAC9C,oBAAoB,CAAC,KAAK,CAAC,CAAA;QAC3B,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QAC1B,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA9BD,6BA8BC;AAED,SAAS,oBAAoB,CAAE,KAAa;IAC1C,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QACpC,MAAM,IAAI,2BAAkB,CAAC,cAAc,KAAK,qBAAqB,CAAC,CAAA;KACvE;AACH,CAAC;AAED,mBAAmB;AACnB,MAAM,eAAe,GAAa,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAA"}

View file

@ -0,0 +1,15 @@
import { kJsonOptions } from './symbols';
export interface SerializerOptions {
enablePrototypePoisoningProtection?: boolean | 'proto' | 'constructor';
}
export default class Serializer {
[kJsonOptions]: {
protoAction: string;
constructorAction: string;
};
constructor(opts?: SerializerOptions);
serialize(object: Record<string, any>): string;
deserialize<T = unknown>(json: string): T;
ndserialize(array: Array<Record<string, any> | string>): string;
qserialize(object?: Record<string, any> | string): string;
}

View file

@ -0,0 +1,107 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const querystring_1 = require("querystring");
const debug_1 = tslib_1.__importDefault(require("debug"));
const secure_json_parse_1 = tslib_1.__importDefault(require("secure-json-parse"));
const errors_1 = require("./errors");
const symbols_1 = require("./symbols");
const debug = (0, debug_1.default)('elasticsearch');
class Serializer {
constructor(opts = {}) {
var _b;
Object.defineProperty(this, _a, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
const enabled = (_b = opts.enablePrototypePoisoningProtection) !== null && _b !== void 0 ? _b : false;
this[symbols_1.kJsonOptions] = {
protoAction: enabled === true || enabled === 'proto' ? 'error' : 'ignore',
constructorAction: enabled === true || enabled === 'constructor' ? 'error' : 'ignore'
};
}
serialize(object) {
debug('Serializing', object);
let json;
try {
json = JSON.stringify(object);
}
catch (err) {
throw new errors_1.SerializationError(err.message, object);
}
return json;
}
deserialize(json) {
debug('Deserializing', json);
let object;
try {
// @ts-expect-error
object = secure_json_parse_1.default.parse(json, this[symbols_1.kJsonOptions]);
}
catch (err) {
throw new errors_1.DeserializationError(err.message, json);
}
return object;
}
ndserialize(array) {
debug('ndserialize', array);
if (!Array.isArray(array)) {
throw new errors_1.SerializationError('The argument provided is not an array', array);
}
let ndjson = '';
for (let i = 0, len = array.length; i < len; i++) {
if (typeof array[i] === 'string') {
ndjson += array[i] + '\n'; // eslint-disable-line
}
else {
// @ts-expect-error
ndjson += this.serialize(array[i]) + '\n'; // eslint-disable-line
}
}
return ndjson;
}
qserialize(object) {
debug('qserialize', object);
if (object == null)
return '';
if (typeof object === 'string')
return object;
// arrays should be serialized as comma separated list
const keys = Object.keys(object);
for (let i = 0, len = keys.length; i < len; i++) {
const key = keys[i];
// elasticsearch will complain for keys without a value
if (object[key] === undefined) {
delete object[key]; // eslint-disable-line
}
else if (Array.isArray(object[key])) {
object[key] = object[key].join(',');
}
}
return (0, querystring_1.stringify)(object);
}
}
exports.default = Serializer;
_a = symbols_1.kJsonOptions;
//# sourceMappingURL=Serializer.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"Serializer.js","sourceRoot":"","sources":["../src/Serializer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,6CAAuC;AACvC,0DAAyB;AACzB,kFAAqC;AACrC,qCAAmE;AACnE,uCAAwC;AAExC,MAAM,KAAK,GAAG,IAAA,eAAK,EAAC,eAAe,CAAC,CAAA;AAMpC,MAAqB,UAAU;IAM7B,YAAa,OAA0B,EAAE;;QALzC;;;;;WAGC;QAGC,MAAM,OAAO,GAAG,MAAA,IAAI,CAAC,kCAAkC,mCAAI,KAAK,CAAA;QAChE,IAAI,CAAC,sBAAY,CAAC,GAAG;YACnB,WAAW,EAAE,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;YACzE,iBAAiB,EAAE,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;SACtF,CAAA;IACH,CAAC;IAED,SAAS,CAAE,MAA2B;QACpC,KAAK,CAAC,aAAa,EAAE,MAAM,CAAC,CAAA;QAC5B,IAAI,IAAI,CAAA;QACR,IAAI;YACF,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;SAC9B;QAAC,OAAO,GAAQ,EAAE;YACjB,MAAM,IAAI,2BAAkB,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;SAClD;QACD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,WAAW,CAAe,IAAY;QACpC,KAAK,CAAC,eAAe,EAAE,IAAI,CAAC,CAAA;QAC5B,IAAI,MAAM,CAAA;QACV,IAAI;YACF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,EAAE,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;YAC/C,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;YACnB,uDAAuD;YACvD,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE;gBAC7B,OAAO,MAAM,CAAC,GAAG,CAAC,CAAA,CAAC,sBAAsB;aAC1C;iBAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE;gBACrC,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;aACpC;SACF;QACD,OAAO,IAAA,uBAAS,EAAC,MAAM,CAAC,CAAA;IAC1B,CAAC;CACF;AAvED,6BAuEC;KAtEE,sBAAY"}

View file

@ -0,0 +1,143 @@
/// <reference types="node" />
/// <reference types="node" />
import * as http from 'http';
import { Connection } from './connection';
import Diagnostic from './Diagnostic';
import Serializer from './Serializer';
import { BaseConnectionPool } from './pool';
import { nodeFilterFn, nodeSelectorFn, generateRequestIdFn, RequestBody, RequestNDBody, TransportResult, Context } from './types';
import { kSniffEnabled, kNextSniff, kIsSniffing, kSniffInterval, kSniffOnConnectionFault, kSniffEndpoint, kRequestTimeout, kCompression, kMaxRetries, kName, kOpaqueIdPrefix, kGenerateRequestId, kContext, kConnectionPool, kSerializer, kDiagnostic, kHeaders, kNodeFilter, kNodeSelector, kProductCheck, kMaxResponseSize, kMaxCompressedResponseSize, kJsonContentType, kNdjsonContentType, kAcceptHeader } from './symbols';
export interface TransportOptions {
diagnostic?: Diagnostic;
connectionPool: BaseConnectionPool;
serializer?: Serializer;
maxRetries?: number;
requestTimeout?: number | string;
compression?: boolean;
sniffInterval?: number | boolean;
sniffOnConnectionFault?: boolean;
sniffEndpoint?: string;
sniffOnStart?: boolean;
nodeFilter?: nodeFilterFn;
nodeSelector?: nodeSelectorFn;
headers?: http.IncomingHttpHeaders;
generateRequestId?: generateRequestIdFn;
name?: string | symbol;
opaqueIdPrefix?: string;
context?: Context;
productCheck?: string;
maxResponseSize?: number;
maxCompressedResponseSize?: number;
vendoredHeaders?: {
jsonContentType?: string;
ndjsonContentType?: string;
accept?: string;
};
}
export interface TransportRequestParams {
method: string;
path: string;
body?: RequestBody;
bulkBody?: RequestNDBody;
querystring?: Record<string, any> | string;
}
export interface TransportRequestOptions {
ignore?: number[];
requestTimeout?: number | string;
maxRetries?: number;
asStream?: boolean;
headers?: http.IncomingHttpHeaders;
querystring?: Record<string, any>;
compression?: boolean;
id?: any;
context?: Context;
warnings?: string[];
opaqueId?: string;
signal?: AbortSignal;
maxResponseSize?: number;
maxCompressedResponseSize?: number;
/**
* Warning: If you set meta to true the result will no longer be
* the response body, but an object containing the body, statusCode,
* headers and meta keys.
* You can use the destructuring assignment to update your code without
* refactoring the entire code base:
* From:
* ```
* const result = await client.method(params)
* ```
* To:
* ```
* const {
* body: result,
* statusCode,
* headers,
* meta
* } = await client.method(params, { meta: true })
* ```
*/
meta?: boolean;
}
export interface TransportRequestOptionsWithMeta extends TransportRequestOptions {
meta: true;
}
export interface TransportRequestOptionsWithOutMeta extends TransportRequestOptions {
meta: false;
}
export interface GetConnectionOptions {
requestId: string | number;
context: any;
}
export interface SniffOptions {
requestId?: string | number;
reason: string;
context: any;
}
export default class Transport {
[kNodeFilter]: nodeFilterFn;
[kNodeSelector]: nodeSelectorFn;
[kHeaders]: http.IncomingHttpHeaders;
[kDiagnostic]: Diagnostic;
[kConnectionPool]: BaseConnectionPool;
[kSerializer]: Serializer;
[kContext]: Context;
[kGenerateRequestId]: generateRequestIdFn;
[kOpaqueIdPrefix]: string | null;
[kName]: string | symbol;
[kMaxRetries]: number;
[kCompression]: boolean;
[kRequestTimeout]: number;
[kSniffEnabled]: boolean;
[kNextSniff]: number;
[kIsSniffing]: boolean;
[kSniffInterval]: number | boolean;
[kSniffOnConnectionFault]: boolean;
[kSniffEndpoint]: string | null;
[kProductCheck]: string | null;
[kMaxResponseSize]: number;
[kMaxCompressedResponseSize]: number;
[kJsonContentType]: string;
[kNdjsonContentType]: string;
[kAcceptHeader]: string;
static sniffReasons: {
SNIFF_ON_START: string;
SNIFF_INTERVAL: string;
SNIFF_ON_CONNECTION_FAULT: string;
DEFAULT: string;
};
constructor(opts: TransportOptions);
get connectionPool(): BaseConnectionPool;
get sniffEnabled(): boolean;
get nextSniff(): number | null;
get sniffEndpoint(): string | null;
get isSniffing(): boolean;
set isSniffing(val: boolean);
get diagnostic(): Diagnostic;
request<TResponse = unknown>(params: TransportRequestParams, options?: TransportRequestOptionsWithOutMeta): Promise<TResponse>;
request<TResponse = unknown, TContext = any>(params: TransportRequestParams, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<TResponse, TContext>>;
request<TResponse = unknown>(params: TransportRequestParams, options?: TransportRequestOptions): Promise<TResponse>;
getConnection(opts: GetConnectionOptions): Connection | null;
sniff(opts: SniffOptions): void;
}
export declare function generateRequestId(): generateRequestIdFn;
export declare function lowerCaseHeaders(oldHeaders?: http.IncomingHttpHeaders): http.IncomingHttpHeaders | null;

View file

@ -0,0 +1,621 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
Object.defineProperty(exports, "__esModule", { value: true });
exports.lowerCaseHeaders = exports.generateRequestId = void 0;
const tslib_1 = require("tslib");
const debug_1 = tslib_1.__importDefault(require("debug"));
const os_1 = tslib_1.__importDefault(require("os"));
const zlib_1 = tslib_1.__importDefault(require("zlib"));
const buffer_1 = tslib_1.__importDefault(require("buffer"));
const util_1 = require("util");
const ms_1 = tslib_1.__importDefault(require("ms"));
const errors_1 = require("./errors");
const Diagnostic_1 = tslib_1.__importDefault(require("./Diagnostic"));
const Serializer_1 = tslib_1.__importDefault(require("./Serializer"));
const symbols_1 = require("./symbols");
const { version: clientVersion } = require('../package.json'); // eslint-disable-line
const debug = (0, debug_1.default)('elasticsearch');
const gzip = (0, util_1.promisify)(zlib_1.default.gzip);
const unzip = (0, util_1.promisify)(zlib_1.default.unzip);
const { createGzip } = zlib_1.default;
const userAgent = `elastic-transport-js/${clientVersion} (${os_1.default.platform()} ${os_1.default.release()}-${os_1.default.arch()}; Node.js ${process.version})`; // eslint-disable-line
class Transport {
constructor(opts) {
var _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20;
Object.defineProperty(this, _a, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _b, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _c, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _d, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _e, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _f, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _g, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _h, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _j, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _k, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _l, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _m, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _o, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _p, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _q, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _r, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _s, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _t, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _u, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _v, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _w, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _x, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _y, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _z, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _0, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
if (opts.connectionPool == null) {
throw new errors_1.ConfigurationError('The Connection Pool option is not defined');
}
if (typeof opts.maxRetries === 'number' && opts.maxRetries < 0 && Number.isInteger(opts.maxRetries)) {
throw new errors_1.ConfigurationError('The maxRetries option must be a positive integer or zero');
}
if (opts.sniffInterval === true ||
(typeof opts.sniffInterval === 'number' && opts.sniffInterval < 0 && Number.isInteger(opts.sniffInterval))) {
throw new errors_1.ConfigurationError('The sniffInterval option must be false or a positive integer');
}
if (opts.maxResponseSize != null && opts.maxResponseSize > buffer_1.default.constants.MAX_STRING_LENGTH) {
throw new errors_1.ConfigurationError(`The maxResponseSize cannot be bigger than ${buffer_1.default.constants.MAX_STRING_LENGTH}`);
}
if (opts.maxCompressedResponseSize != null && opts.maxCompressedResponseSize > buffer_1.default.constants.MAX_LENGTH) {
throw new errors_1.ConfigurationError(`The maxCompressedResponseSize cannot be bigger than ${buffer_1.default.constants.MAX_LENGTH}`);
}
this[symbols_1.kNodeFilter] = (_1 = opts.nodeFilter) !== null && _1 !== void 0 ? _1 : defaultNodeFilter;
this[symbols_1.kNodeSelector] = (_2 = opts.nodeSelector) !== null && _2 !== void 0 ? _2 : roundRobinSelector();
this[symbols_1.kHeaders] = Object.assign({}, { 'user-agent': userAgent }, opts.compression === true ? { 'accept-encoding': 'gzip,deflate' } : null, lowerCaseHeaders(opts.headers));
this[symbols_1.kDiagnostic] = (_3 = opts.diagnostic) !== null && _3 !== void 0 ? _3 : new Diagnostic_1.default();
this[symbols_1.kConnectionPool] = opts.connectionPool;
this[symbols_1.kSerializer] = (_4 = opts.serializer) !== null && _4 !== void 0 ? _4 : new Serializer_1.default();
this[symbols_1.kContext] = (_5 = opts.context) !== null && _5 !== void 0 ? _5 : null;
this[symbols_1.kGenerateRequestId] = (_6 = opts.generateRequestId) !== null && _6 !== void 0 ? _6 : generateRequestId();
this[symbols_1.kOpaqueIdPrefix] = (_7 = opts.opaqueIdPrefix) !== null && _7 !== void 0 ? _7 : null;
this[symbols_1.kName] = (_8 = opts.name) !== null && _8 !== void 0 ? _8 : 'elastic-transport-js';
this[symbols_1.kMaxRetries] = typeof opts.maxRetries === 'number' ? opts.maxRetries : 3;
this[symbols_1.kCompression] = opts.compression === true;
this[symbols_1.kRequestTimeout] = opts.requestTimeout != null ? toMs(opts.requestTimeout) : 30000;
this[symbols_1.kSniffInterval] = (_9 = opts.sniffInterval) !== null && _9 !== void 0 ? _9 : false;
this[symbols_1.kSniffEnabled] = typeof this[symbols_1.kSniffInterval] === 'number';
this[symbols_1.kNextSniff] = this[symbols_1.kSniffEnabled] ? (Date.now() + this[symbols_1.kSniffInterval]) : 0;
this[symbols_1.kIsSniffing] = false;
this[symbols_1.kSniffOnConnectionFault] = (_10 = opts.sniffOnConnectionFault) !== null && _10 !== void 0 ? _10 : false;
this[symbols_1.kSniffEndpoint] = (_11 = opts.sniffEndpoint) !== null && _11 !== void 0 ? _11 : null;
this[symbols_1.kProductCheck] = (_12 = opts.productCheck) !== null && _12 !== void 0 ? _12 : null;
this[symbols_1.kMaxResponseSize] = (_13 = opts.maxResponseSize) !== null && _13 !== void 0 ? _13 : buffer_1.default.constants.MAX_STRING_LENGTH;
this[symbols_1.kMaxCompressedResponseSize] = (_14 = opts.maxCompressedResponseSize) !== null && _14 !== void 0 ? _14 : buffer_1.default.constants.MAX_LENGTH;
this[symbols_1.kJsonContentType] = (_16 = (_15 = opts.vendoredHeaders) === null || _15 === void 0 ? void 0 : _15.jsonContentType) !== null && _16 !== void 0 ? _16 : 'application/json';
this[symbols_1.kNdjsonContentType] = (_18 = (_17 = opts.vendoredHeaders) === null || _17 === void 0 ? void 0 : _17.ndjsonContentType) !== null && _18 !== void 0 ? _18 : 'application/x-ndjson';
this[symbols_1.kAcceptHeader] = (_20 = (_19 = opts.vendoredHeaders) === null || _19 === void 0 ? void 0 : _19.accept) !== null && _20 !== void 0 ? _20 : 'application/json, text/plain';
if (opts.sniffOnStart === true) {
this.sniff({
reason: Transport.sniffReasons.SNIFF_ON_START,
requestId: this[symbols_1.kGenerateRequestId]({ method: 'GET', path: this[symbols_1.kSniffEndpoint] }, { context: this[symbols_1.kContext] }),
context: this[symbols_1.kContext]
});
}
}
get connectionPool() {
return this[symbols_1.kConnectionPool];
}
get sniffEnabled() {
return this[symbols_1.kSniffEnabled];
}
get nextSniff() {
return this[symbols_1.kNextSniff];
}
get sniffEndpoint() {
return this[symbols_1.kSniffEndpoint];
}
get isSniffing() {
return this[symbols_1.kIsSniffing];
}
set isSniffing(val) {
if (typeof val !== 'boolean') {
throw new errors_1.ConfigurationError(`isSniffing must be a boolean, instead got ${typeof val}`);
}
this[symbols_1.kIsSniffing] = val;
}
get diagnostic() {
return this[symbols_1.kDiagnostic];
}
async request(params, options = {}) {
var _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16;
const connectionParams = {
method: params.method,
path: params.path
};
const meta = {
context: null,
request: {
params: connectionParams,
options: options,
id: (_1 = options.id) !== null && _1 !== void 0 ? _1 : this[symbols_1.kGenerateRequestId](params, options)
},
name: this[symbols_1.kName],
connection: null,
attempts: 0,
aborted: false
};
const returnMeta = (_2 = options.meta) !== null && _2 !== void 0 ? _2 : false;
if (this[symbols_1.kContext] != null && options.context != null) {
meta.context = Object.assign({}, this[symbols_1.kContext], options.context);
}
else if (this[symbols_1.kContext] !== null) {
meta.context = this[symbols_1.kContext];
}
else if (options.context != null) {
meta.context = options.context;
}
const result = {
// the default body value can't be `null`
// as it's a valid JSON value
body: undefined,
statusCode: 0,
headers: {},
meta,
get warnings() {
var _1;
return ((_1 = this.headers) === null || _1 === void 0 ? void 0 : _1.warning) != null
? this.headers.warning.split(/(?!\B"[^"]*),(?![^"]*"\B)/)
: null;
}
};
// We should not retry if we are sending a stream body, because we should store in memory
// a copy of the stream to be able to send it again, but since we don't know in advance
// the size of the stream, we risk to take too much memory.
// Furthermore, copying everytime the stream is very a expensive operation.
const maxRetries = isStream((_3 = params.body) !== null && _3 !== void 0 ? _3 : params.bulkBody) ? 0 : (typeof options.maxRetries === 'number' ? options.maxRetries : this[symbols_1.kMaxRetries]);
const compression = typeof options.compression === 'boolean' ? options.compression : this[symbols_1.kCompression];
const signal = options.signal;
const maxResponseSize = (_4 = options.maxResponseSize) !== null && _4 !== void 0 ? _4 : this[symbols_1.kMaxResponseSize];
const maxCompressedResponseSize = (_5 = options.maxCompressedResponseSize) !== null && _5 !== void 0 ? _5 : this[symbols_1.kMaxCompressedResponseSize];
this[symbols_1.kDiagnostic].emit('serialization', null, result);
const headers = Object.assign({}, this[symbols_1.kHeaders], lowerCaseHeaders(options.headers));
if (options.opaqueId !== undefined) {
headers['x-opaque-id'] = typeof this[symbols_1.kOpaqueIdPrefix] === 'string'
? this[symbols_1.kOpaqueIdPrefix] + options.opaqueId // eslint-disable-line
: options.opaqueId;
}
// handle json body
if (params.body != null) {
if (shouldSerialize(params.body)) {
try {
connectionParams.body = this[symbols_1.kSerializer].serialize(params.body);
}
catch (err) {
this[symbols_1.kDiagnostic].emit('request', err, result);
throw err;
}
headers['content-type'] = (_6 = headers['content-type']) !== null && _6 !== void 0 ? _6 : this[symbols_1.kJsonContentType];
headers.accept = (_7 = headers.accept) !== null && _7 !== void 0 ? _7 : this[symbols_1.kJsonContentType];
}
else {
if (params.body !== '') {
headers['content-type'] = (_8 = headers['content-type']) !== null && _8 !== void 0 ? _8 : 'text/plain';
headers.accept = (_9 = headers.accept) !== null && _9 !== void 0 ? _9 : this[symbols_1.kAcceptHeader];
}
connectionParams.body = params.body;
}
// handle ndjson body
}
else if (params.bulkBody != null) {
if (shouldSerialize(params.bulkBody)) {
try {
connectionParams.body = this[symbols_1.kSerializer].ndserialize(params.bulkBody);
}
catch (err) {
this[symbols_1.kDiagnostic].emit('request', err, result);
throw err;
}
}
else {
connectionParams.body = params.bulkBody;
}
if (connectionParams.body !== '') {
headers['content-type'] = (_10 = headers['content-type']) !== null && _10 !== void 0 ? _10 : this[symbols_1.kNdjsonContentType];
headers.accept = (_11 = headers.accept) !== null && _11 !== void 0 ? _11 : this[symbols_1.kJsonContentType];
}
}
// serializes the querystring
if (options.querystring == null) {
connectionParams.querystring = this[symbols_1.kSerializer].qserialize(params.querystring);
}
else {
connectionParams.querystring = this[symbols_1.kSerializer].qserialize(Object.assign({}, params.querystring, options.querystring));
}
// handle compression
if (connectionParams.body !== '' && connectionParams.body != null) {
if (isStream(connectionParams.body)) {
if (compression) {
headers['content-encoding'] = 'gzip';
connectionParams.body = connectionParams.body.pipe(createGzip());
}
}
else if (compression) {
try {
connectionParams.body = await gzip(connectionParams.body);
}
catch (err) {
/* istanbul ignore next */
this[symbols_1.kDiagnostic].emit('request', err, result);
/* istanbul ignore next */
throw err;
}
headers['content-encoding'] = 'gzip';
headers['content-length'] = '' + Buffer.byteLength(connectionParams.body); // eslint-disable-line
}
else {
headers['content-length'] = '' + Buffer.byteLength(connectionParams.body); // eslint-disable-line
}
}
headers.accept = (_12 = headers.accept) !== null && _12 !== void 0 ? _12 : this[symbols_1.kAcceptHeader];
connectionParams.headers = headers;
while (meta.attempts <= maxRetries) {
try {
if (signal === null || signal === void 0 ? void 0 : signal.aborted) { // eslint-disable-line
throw new errors_1.RequestAbortedError('Request has been aborted by the user', result);
}
meta.connection = this.getConnection({
requestId: meta.request.id,
context: meta.context
});
if (meta.connection === null) {
throw new errors_1.NoLivingConnectionsError('There are no living connections', result);
}
this[symbols_1.kDiagnostic].emit('request', null, result);
// perform the actual http request
let { statusCode, headers, body } = await meta.connection.request(connectionParams, {
requestId: meta.request.id,
name: this[symbols_1.kName],
context: meta.context,
maxResponseSize,
maxCompressedResponseSize,
signal,
timeout: toMs(options.requestTimeout != null ? options.requestTimeout : this[symbols_1.kRequestTimeout]),
...(options.asStream === true ? { asStream: true } : null)
});
result.statusCode = statusCode;
result.headers = headers;
if (this[symbols_1.kProductCheck] != null && headers['x-elastic-product'] !== this[symbols_1.kProductCheck] && statusCode >= 200 && statusCode < 300) {
/* eslint-disable @typescript-eslint/prefer-ts-expect-error */
// @ts-ignore
throw new errors_1.ProductNotSupportedError(this[symbols_1.kProductCheck], result);
/* eslint-enable @typescript-eslint/prefer-ts-expect-error */
}
if (options.asStream === true) {
result.body = body;
this[symbols_1.kDiagnostic].emit('response', null, result);
return returnMeta ? result : body;
}
const contentEncoding = ((_13 = headers['content-encoding']) !== null && _13 !== void 0 ? _13 : '').toLowerCase();
if (contentEncoding.includes('gzip') || contentEncoding.includes('deflate')) {
body = await unzip(body);
}
const isVectorTile = ((_14 = headers['content-type']) !== null && _14 !== void 0 ? _14 : '').includes('application/vnd.mapbox-vector-tile');
if (Buffer.isBuffer(body) && !isVectorTile) {
body = body.toString();
}
const isHead = params.method === 'HEAD';
// we should attempt the payload deserialization only if:
// - a `content-type` is defined and is equal to `application/json`
// - the request is not a HEAD request
// - the payload is not an empty string
if (headers['content-type'] !== undefined &&
(((_15 = headers['content-type']) === null || _15 === void 0 ? void 0 : _15.includes('application/json')) ||
((_16 = headers['content-type']) === null || _16 === void 0 ? void 0 : _16.includes('application/vnd.elasticsearch+json'))) &&
!isHead && body !== '') { // eslint-disable-line
result.body = this[symbols_1.kSerializer].deserialize(body);
}
else {
// cast to boolean if the request method was HEAD and there was no error
result.body = isHead && statusCode < 400 ? true : body;
}
// we should ignore the statusCode if the user has configured the `ignore` field with
// the statusCode we just got or if the request method is HEAD and the statusCode is 404
const ignoreStatusCode = (Array.isArray(options.ignore) && options.ignore.includes(statusCode)) ||
(isHead && statusCode === 404);
if (!ignoreStatusCode && (statusCode === 502 || statusCode === 503 || statusCode === 504)) {
// if the statusCode is 502/3/4 we should run our retry strategy
// and mark the connection as dead
this[symbols_1.kConnectionPool].markDead(meta.connection);
// retry logic
if (meta.attempts < maxRetries) {
meta.attempts++;
debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params);
continue;
}
}
else {
// everything has worked as expected, let's mark
// the connection as alive (or confirm it)
this[symbols_1.kConnectionPool].markAlive(meta.connection);
}
if (!ignoreStatusCode && statusCode >= 400) {
throw new errors_1.ResponseError(result);
}
else {
// cast to boolean if the request method was HEAD
if (isHead && statusCode === 404) {
result.body = false;
}
this[symbols_1.kDiagnostic].emit('response', null, result);
return returnMeta ? result : result.body;
}
}
catch (error) {
switch (error.name) {
// should not retry
case 'ProductNotSupportedError':
case 'NoLivingConnectionsError':
case 'DeserializationError':
case 'ResponseError':
this[symbols_1.kDiagnostic].emit('response', error, result);
throw error;
case 'RequestAbortedError': {
meta.aborted = true;
// Wrap the error to get a clean stack trace
const wrappedError = new errors_1.RequestAbortedError(error.message, result);
this[symbols_1.kDiagnostic].emit('response', wrappedError, result);
throw wrappedError;
}
// should retry
case 'TimeoutError':
case 'ConnectionError': {
// if there is an error in the connection
// let's mark the connection as dead
this[symbols_1.kConnectionPool].markDead(meta.connection);
if (this[symbols_1.kSniffOnConnectionFault]) {
this.sniff({
reason: Transport.sniffReasons.SNIFF_ON_CONNECTION_FAULT,
requestId: meta.request.id,
context: meta.context
});
}
// retry logic
if (meta.attempts < maxRetries) {
meta.attempts++;
debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params);
continue;
}
// Wrap the error to get a clean stack trace
const wrappedError = error.name === 'TimeoutError'
? new errors_1.TimeoutError(error.message, result)
: new errors_1.ConnectionError(error.message, result);
this[symbols_1.kDiagnostic].emit('response', wrappedError, result);
throw wrappedError;
}
// edge cases, such as bad compression
default:
this[symbols_1.kDiagnostic].emit('response', error, result);
throw error;
}
}
}
return returnMeta ? result : result.body;
}
getConnection(opts) {
const now = Date.now();
if (this[symbols_1.kSniffEnabled] && now > this[symbols_1.kNextSniff]) {
this[symbols_1.kNextSniff] = now + this[symbols_1.kSniffInterval];
this.sniff({
reason: Transport.sniffReasons.SNIFF_INTERVAL,
requestId: opts.requestId,
context: opts.context
});
}
return this[symbols_1.kConnectionPool].getConnection({
filter: this[symbols_1.kNodeFilter],
selector: this[symbols_1.kNodeSelector],
requestId: opts.requestId,
name: this[symbols_1.kName],
context: opts.context,
now
});
}
/* istanbul ignore next */
sniff(opts) { }
}
exports.default = Transport;
_a = symbols_1.kNodeFilter, _b = symbols_1.kNodeSelector, _c = symbols_1.kHeaders, _d = symbols_1.kDiagnostic, _e = symbols_1.kConnectionPool, _f = symbols_1.kSerializer, _g = symbols_1.kContext, _h = symbols_1.kGenerateRequestId, _j = symbols_1.kOpaqueIdPrefix, _k = symbols_1.kName, _l = symbols_1.kMaxRetries, _m = symbols_1.kCompression, _o = symbols_1.kRequestTimeout, _p = symbols_1.kSniffEnabled, _q = symbols_1.kNextSniff, _r = symbols_1.kIsSniffing, _s = symbols_1.kSniffInterval, _t = symbols_1.kSniffOnConnectionFault, _u = symbols_1.kSniffEndpoint, _v = symbols_1.kProductCheck, _w = symbols_1.kMaxResponseSize, _x = symbols_1.kMaxCompressedResponseSize, _y = symbols_1.kJsonContentType, _z = symbols_1.kNdjsonContentType, _0 = symbols_1.kAcceptHeader;
Object.defineProperty(Transport, "sniffReasons", {
enumerable: true,
configurable: true,
writable: true,
value: {
SNIFF_ON_START: 'sniff-on-start',
SNIFF_INTERVAL: 'sniff-interval',
SNIFF_ON_CONNECTION_FAULT: 'sniff-on-connection-fault',
DEFAULT: 'default'
}
});
function toMs(time) {
if (typeof time === 'string') {
return (0, ms_1.default)(time);
}
return time;
}
function shouldSerialize(obj) {
return typeof obj !== 'string' &&
typeof obj.pipe !== 'function' &&
!Buffer.isBuffer(obj);
}
function isStream(obj) {
return obj != null && typeof obj.pipe === 'function';
}
function defaultNodeFilter(node) {
return true;
}
function roundRobinSelector() {
let current = -1;
return function _roundRobinSelector(connections) {
if (++current >= connections.length) {
current = 0;
}
return connections[current];
};
}
function generateRequestId() {
const maxInt = 2147483647;
let nextReqId = 0;
return function genReqId(params, options) {
return (nextReqId = (nextReqId + 1) & maxInt);
};
}
exports.generateRequestId = generateRequestId;
function lowerCaseHeaders(oldHeaders) {
if (oldHeaders == null)
return null;
const newHeaders = {};
for (const header in oldHeaders) {
// @ts-expect-error
newHeaders[header.toLowerCase()] = oldHeaders[header];
}
return newHeaders;
}
exports.lowerCaseHeaders = lowerCaseHeaders;
//# sourceMappingURL=Transport.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,86 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { inspect } from 'util';
import * as http from 'http';
import { URL } from 'url';
import { ConnectionOptions as TlsConnectionOptions, TLSSocket, DetailedPeerCertificate } from 'tls';
import { Readable as ReadableStream } from 'stream';
import Diagnostic from '../Diagnostic';
import { ApiKeyAuth, BasicAuth, BearerAuth, HttpAgentOptions, UndiciAgentOptions, agentFn } from '../types';
import { kStatus, kDiagnostic, kCaFingerprint } from '../symbols';
export interface ConnectionOptions {
url: URL;
tls?: TlsConnectionOptions;
id?: string;
headers?: http.IncomingHttpHeaders;
status?: string;
auth?: BasicAuth | ApiKeyAuth | BearerAuth;
diagnostic?: Diagnostic;
timeout?: number;
agent?: HttpAgentOptions | UndiciAgentOptions | agentFn | boolean;
proxy?: string | URL;
caFingerprint?: string;
}
export interface ConnectionRequestParams {
method: string;
path: string;
headers?: http.IncomingHttpHeaders;
body?: string | Buffer | ReadableStream | null;
querystring?: string;
}
export interface ConnectionRequestOptions {
requestId: string | number;
name: string | symbol;
context: any;
maxResponseSize?: number;
maxCompressedResponseSize?: number;
signal?: AbortSignal;
timeout?: number;
}
export interface ConnectionRequestOptionsAsStream extends ConnectionRequestOptions {
asStream: true;
}
export interface ConnectionRequestResponse {
body: string | Buffer;
headers: http.IncomingHttpHeaders;
statusCode: number;
}
export interface ConnectionRequestResponseAsStream {
body: ReadableStream;
headers: http.IncomingHttpHeaders;
statusCode: number;
}
export default class BaseConnection {
url: URL;
tls: TlsConnectionOptions | null;
id: string;
timeout: number;
headers: http.IncomingHttpHeaders;
deadCount: number;
resurrectTimeout: number;
_openRequests: number;
weight: number;
[kStatus]: string;
[kCaFingerprint]: string | null;
[kDiagnostic]: Diagnostic;
static statuses: {
ALIVE: string;
DEAD: string;
};
constructor(opts: ConnectionOptions);
get status(): string;
set status(status: string);
get diagnostic(): Diagnostic;
request(params: ConnectionRequestParams, options: ConnectionRequestOptions): Promise<ConnectionRequestResponse>;
request(params: ConnectionRequestParams, options: ConnectionRequestOptionsAsStream): Promise<ConnectionRequestResponseAsStream>;
close(): Promise<void>;
[inspect.custom](depth: number, options: Record<string, any>): Record<string, any>;
toJSON(): Record<string, any>;
}
export declare function prepareHeaders(headers?: http.IncomingHttpHeaders, auth?: BasicAuth | ApiKeyAuth | BearerAuth): http.IncomingHttpHeaders;
export declare function getIssuerCertificate(socket: TLSSocket): DetailedPeerCertificate | null;

View file

@ -0,0 +1,224 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var _a, _b, _c;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIssuerCertificate = exports.prepareHeaders = void 0;
const tslib_1 = require("tslib");
const util_1 = require("util");
const Diagnostic_1 = tslib_1.__importDefault(require("../Diagnostic"));
const errors_1 = require("../errors");
const symbols_1 = require("../symbols");
class BaseConnection {
constructor(opts) {
var _d, _e, _f, _g, _h, _j;
Object.defineProperty(this, "url", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "tls", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "id", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "timeout", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "headers", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "deadCount", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "resurrectTimeout", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "_openRequests", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "weight", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _a, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _b, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _c, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.url = opts.url;
this.tls = (_d = opts.tls) !== null && _d !== void 0 ? _d : null;
this.id = (_e = opts.id) !== null && _e !== void 0 ? _e : stripAuth(opts.url.href);
this.headers = prepareHeaders(opts.headers, opts.auth);
this.timeout = (_f = opts.timeout) !== null && _f !== void 0 ? _f : 30000;
this.deadCount = 0;
this.resurrectTimeout = 0;
this.weight = 0;
this._openRequests = 0;
this[symbols_1.kStatus] = (_g = opts.status) !== null && _g !== void 0 ? _g : BaseConnection.statuses.ALIVE;
this[symbols_1.kDiagnostic] = (_h = opts.diagnostic) !== null && _h !== void 0 ? _h : new Diagnostic_1.default();
this[symbols_1.kCaFingerprint] = (_j = opts.caFingerprint) !== null && _j !== void 0 ? _j : null;
if (!['http:', 'https:'].includes(this.url.protocol)) {
throw new errors_1.ConfigurationError(`Invalid protocol: '${this.url.protocol}'`);
}
}
get status() {
return this[symbols_1.kStatus];
}
set status(status) {
if (!validStatuses.includes(status)) {
throw new errors_1.ConfigurationError(`Unsupported status: '${status}'`);
}
this[symbols_1.kStatus] = status;
}
get diagnostic() {
return this[symbols_1.kDiagnostic];
}
async request(params, options) {
throw new errors_1.ConfigurationError('The request method should be implemented by extended classes');
}
/* istanbul ignore next */
async close() {
throw new errors_1.ConfigurationError('The close method should be implemented by extended classes');
}
// Handles console.log and utils.inspect invocations.
// We want to hide `auth`, `agent` and `tls` since they made
// the logs very hard to read. The user can still
// access them with `instance.agent` and `instance.tls`.
[(_a = symbols_1.kStatus, _b = symbols_1.kCaFingerprint, _c = symbols_1.kDiagnostic, util_1.inspect.custom)](depth, options) {
const { authorization, ...headers } = this.headers;
return {
url: stripAuth(this.url.toString()),
id: this.id,
headers,
status: this.status
};
}
toJSON() {
const { authorization, ...headers } = this.headers;
return {
url: stripAuth(this.url.toString()),
id: this.id,
headers,
status: this.status
};
}
}
exports.default = BaseConnection;
Object.defineProperty(BaseConnection, "statuses", {
enumerable: true,
configurable: true,
writable: true,
value: {
ALIVE: 'alive',
DEAD: 'dead'
}
});
const validStatuses = Object.keys(BaseConnection.statuses)
// @ts-expect-error
.map(k => BaseConnection.statuses[k]);
function stripAuth(url) {
if (!url.includes('@'))
return url;
return url.slice(0, url.indexOf('//') + 2) + url.slice(url.indexOf('@') + 1);
}
function prepareHeaders(headers = {}, auth) {
if (auth != null && headers.authorization == null) {
/* istanbul ignore else */
if (isApiKeyAuth(auth)) {
if (typeof auth.apiKey === 'object') {
headers.authorization = 'ApiKey ' + Buffer.from(`${auth.apiKey.id}:${auth.apiKey.api_key}`).toString('base64');
}
else {
headers.authorization = `ApiKey ${auth.apiKey}`;
}
}
else if (isBearerAuth(auth)) {
headers.authorization = `Bearer ${auth.bearer}`;
}
else if (auth.username != null && auth.password != null) {
headers.authorization = 'Basic ' + Buffer.from(`${auth.username}:${auth.password}`).toString('base64');
}
}
return headers;
}
exports.prepareHeaders = prepareHeaders;
function isApiKeyAuth(auth) {
return auth.apiKey != null;
}
function isBearerAuth(auth) {
return auth.bearer != null;
}
function getIssuerCertificate(socket) {
let certificate = socket.getPeerCertificate(true);
while (certificate !== null && Object.keys(certificate).length > 0) {
// invalid certificate
if (certificate.issuerCertificate == null) {
return null;
}
// We have reached the root certificate.
// In case of self-signed certificates, `issuerCertificate` may be a circular reference.
if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) {
break;
}
// continue the loop
certificate = certificate.issuerCertificate;
}
return certificate;
}
exports.getIssuerCertificate = getIssuerCertificate;
//# sourceMappingURL=BaseConnection.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"BaseConnection.js","sourceRoot":"","sources":["../../src/connection/BaseConnection.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;;AAEH,+BAA8B;AAK9B,uEAAsC;AAStC,sCAA8C;AAC9C,wCAAiE;AAkDjE,MAAqB,cAAc;IAmBjC,YAAa,IAAuB;;QAlBpC;;;;;WAAQ;QACR;;;;;WAAgC;QAChC;;;;;WAAU;QACV;;;;;WAAe;QACf;;;;;WAAiC;QACjC;;;;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,EAAE,CAAA;SAChD;aAAM,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,EAAE;YACzD,OAAO,CAAC,aAAa,GAAG,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;SACvG;KACF;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAhBD,wCAgBC;AAED,SAAS,YAAY,CAAE,IAAyB;IAC9C,OAAO,IAAI,CAAC,MAAM,IAAI,IAAI,CAAA;AAC5B,CAAC;AAED,SAAS,YAAY,CAAE,IAAyB;IAC9C,OAAO,IAAI,CAAC,MAAM,IAAI,IAAI,CAAA;AAC5B,CAAC;AAED,SAAgB,oBAAoB,CAAE,MAAiB;IACrD,IAAI,WAAW,GAAG,MAAM,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAA;IACjD,OAAO,WAAW,KAAK,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;QAClE,sBAAsB;QACtB,IAAI,WAAW,CAAC,iBAAiB,IAAI,IAAI,EAAE;YACzC,OAAO,IAAI,CAAA;SACZ;QAED,wCAAwC;QACxC,wFAAwF;QACxF,IAAI,WAAW,CAAC,cAAc,KAAK,WAAW,CAAC,iBAAiB,CAAC,cAAc,EAAE;YAC/E,MAAK;SACN;QAED,oBAAoB;QACpB,WAAW,GAAG,WAAW,CAAC,iBAAiB,CAAA;KAC5C;IACD,OAAO,WAAW,CAAA;AACpB,CAAC;AAlBD,oDAkBC"}

View file

@ -0,0 +1,15 @@
/// <reference types="node" />
/// <reference types="node" />
import hpagent from 'hpagent';
import http from 'http';
import https from 'https';
import BaseConnection, { ConnectionOptions, ConnectionRequestParams, ConnectionRequestOptions, ConnectionRequestOptionsAsStream, ConnectionRequestResponse, ConnectionRequestResponseAsStream } from './BaseConnection';
export default class HttpConnection extends BaseConnection {
agent?: http.Agent | https.Agent | hpagent.HttpProxyAgent | hpagent.HttpsProxyAgent;
makeRequest: typeof http.request | typeof https.request;
constructor(opts: ConnectionOptions);
request(params: ConnectionRequestParams, options: ConnectionRequestOptions): Promise<ConnectionRequestResponse>;
request(params: ConnectionRequestParams, options: ConnectionRequestOptionsAsStream): Promise<ConnectionRequestResponseAsStream>;
close(): Promise<void>;
buildRequestObject(params: ConnectionRequestParams, options: ConnectionRequestOptions): http.ClientRequestArgs;
}

View file

@ -0,0 +1,375 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/restrict-template-expressions */
const hpagent_1 = tslib_1.__importDefault(require("hpagent"));
const http_1 = tslib_1.__importDefault(require("http"));
const https_1 = tslib_1.__importDefault(require("https"));
const debug_1 = tslib_1.__importDefault(require("debug"));
const buffer_1 = tslib_1.__importDefault(require("buffer"));
const BaseConnection_1 = tslib_1.__importStar(require("./BaseConnection"));
const symbols_1 = require("../symbols");
const stream_1 = require("stream");
const errors_1 = require("../errors");
const debug = (0, debug_1.default)('elasticsearch');
const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;
const MAX_BUFFER_LENGTH = buffer_1.default.constants.MAX_LENGTH;
const MAX_STRING_LENGTH = buffer_1.default.constants.MAX_STRING_LENGTH;
class HttpConnection extends BaseConnection_1.default {
constructor(opts) {
super(opts);
Object.defineProperty(this, "agent", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "makeRequest", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
if (typeof opts.agent === 'function') {
this.agent = opts.agent(opts);
}
else if (typeof opts.agent === 'boolean') {
this.agent = undefined;
}
else {
if (opts.agent != null && !isHttpAgentOptions(opts.agent)) {
throw new errors_1.ConfigurationError('Bad agent configuration for Http agent');
}
const agentOptions = Object.assign({}, {
keepAlive: true,
keepAliveMsecs: 1000,
maxSockets: 256,
maxFreeSockets: 256,
scheduling: 'lifo'
}, opts.agent);
if (opts.proxy != null) {
const proxyAgentOptions = {
...agentOptions,
proxy: opts.proxy
};
this.agent = this.url.protocol === 'http:'
? new hpagent_1.default.HttpProxyAgent(proxyAgentOptions)
: new hpagent_1.default.HttpsProxyAgent(Object.assign({}, proxyAgentOptions, this.tls));
}
else {
this.agent = this.url.protocol === 'http:'
? new http_1.default.Agent(agentOptions)
: new https_1.default.Agent(Object.assign({}, agentOptions, this.tls));
}
}
this.makeRequest = this.url.protocol === 'http:'
? http_1.default.request
: https_1.default.request;
}
async request(params, options) {
return await new Promise((resolve, reject) => {
var _a, _b;
let cleanedListeners = false;
const maxResponseSize = (_a = options.maxResponseSize) !== null && _a !== void 0 ? _a : MAX_STRING_LENGTH;
const maxCompressedResponseSize = (_b = options.maxCompressedResponseSize) !== null && _b !== void 0 ? _b : MAX_BUFFER_LENGTH;
const requestParams = this.buildRequestObject(params, options);
// https://github.com/nodejs/node/commit/b961d9fd83
if (INVALID_PATH_REGEX.test(requestParams.path)) {
return reject(new TypeError(`ERR_UNESCAPED_CHARACTERS: ${requestParams.path}`));
}
debug('Starting a new request', params);
let request;
try {
request = this.makeRequest(requestParams);
}
catch (err) {
return reject(err);
}
const abortListener = () => {
request.abort();
};
this._openRequests++;
if (options.signal != null) {
options.signal.addEventListener('abort', abortListener, { once: true });
}
const onResponse = (response) => {
var _a, _b;
cleanListeners();
this._openRequests--;
if (options.asStream === true) {
return resolve({
body: response,
statusCode: response.statusCode,
headers: response.headers
});
}
const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase();
const isCompressed = contentEncoding.includes('gzip') || contentEncoding.includes('deflate');
const isVectorTile = ((_b = response.headers['content-type']) !== null && _b !== void 0 ? _b : '').includes('application/vnd.mapbox-vector-tile');
/* istanbul ignore else */
if (response.headers['content-length'] !== undefined) {
const contentLength = Number(response.headers['content-length']);
if (isCompressed && contentLength > maxCompressedResponseSize) {
response.destroy();
return reject(new errors_1.RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed buffer (${maxCompressedResponseSize})`));
}
else if (contentLength > maxResponseSize) {
response.destroy();
return reject(new errors_1.RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed string (${maxResponseSize})`));
}
}
// if the response is compressed, we must handle it
// as buffer for allowing decompression later
let payload = isCompressed || isVectorTile ? new Array() : '';
const onData = isCompressed || isVectorTile ? onDataAsBuffer : onDataAsString;
let currentLength = 0;
function onDataAsBuffer(chunk) {
currentLength += Buffer.byteLength(chunk);
if (currentLength > maxCompressedResponseSize) {
// TODO: hacky solution, refactor to avoid using the deprecated aborted event
response.removeListener('aborted', onAbort);
response.destroy();
onEnd(new errors_1.RequestAbortedError(`The content length (${currentLength}) is bigger than the maximum allowed buffer (${maxCompressedResponseSize})`));
}
else {
payload.push(chunk);
}
}
function onDataAsString(chunk) {
currentLength += Buffer.byteLength(chunk);
if (currentLength > maxResponseSize) {
// TODO: hacky solution, refactor to avoid using the deprecated aborted event
response.removeListener('aborted', onAbort);
response.destroy();
onEnd(new errors_1.RequestAbortedError(`The content length (${currentLength}) is bigger than the maximum allowed string (${maxResponseSize})`));
}
else {
payload = `${payload}${chunk}`;
}
}
const onEnd = (err) => {
response.removeListener('data', onData);
response.removeListener('end', onEnd);
response.removeListener('error', onEnd);
response.removeListener('aborted', onAbort);
if (err != null) {
if (err.name === 'RequestAbortedError') {
return reject(err);
}
return reject(new errors_1.ConnectionError(err.message));
}
resolve({
body: isCompressed || isVectorTile ? Buffer.concat(payload) : payload,
statusCode: response.statusCode,
headers: response.headers
});
};
const onAbort = () => {
response.destroy();
onEnd(new Error('Response aborted while reading the body'));
};
if (!isCompressed && !isVectorTile) {
response.setEncoding('utf8');
}
this.diagnostic.emit('deserialization', null, options);
response.on('data', onData);
response.on('error', onEnd);
response.on('end', onEnd);
response.on('aborted', onAbort);
};
const onTimeout = () => {
cleanListeners();
this._openRequests--;
request.once('error', () => { }); // we need to catch the request aborted error
request.abort();
reject(new errors_1.TimeoutError('Request timed out'));
};
const onError = (err) => {
var _a, _b, _c, _d, _e, _f, _g, _h;
cleanListeners();
this._openRequests--;
let message = err.message;
// @ts-expect-error
if (err.code === 'ECONNRESET') {
message += ` - Local: ${(_b = (_a = request.socket) === null || _a === void 0 ? void 0 : _a.localAddress) !== null && _b !== void 0 ? _b : 'unknown'}:${(_d = (_c = request.socket) === null || _c === void 0 ? void 0 : _c.localPort) !== null && _d !== void 0 ? _d : 'unknown'}, Remote: ${(_f = (_e = request.socket) === null || _e === void 0 ? void 0 : _e.remoteAddress) !== null && _f !== void 0 ? _f : 'unknown'}:${(_h = (_g = request.socket) === null || _g === void 0 ? void 0 : _g.remotePort) !== null && _h !== void 0 ? _h : 'unknown'}`;
}
reject(new errors_1.ConnectionError(message));
};
const onAbort = () => {
cleanListeners();
request.once('error', () => { }); // we need to catch the request aborted error
debug('Request aborted', params);
this._openRequests--;
reject(new errors_1.RequestAbortedError('Request aborted'));
};
const onSocket = (socket) => {
/* istanbul ignore else */
if (!socket.isSessionReused()) {
socket.once('secureConnect', () => {
const issuerCertificate = (0, BaseConnection_1.getIssuerCertificate)(socket);
/* istanbul ignore next */
if (issuerCertificate == null) {
onError(new Error('Invalid or malformed certificate'));
request.once('error', () => { }); // we need to catch the request aborted error
return request.abort();
}
// Check if fingerprint matches
/* istanbul ignore else */
if (this[symbols_1.kCaFingerprint] !== issuerCertificate.fingerprint256) {
onError(new Error('Server certificate CA fingerprint does not match the value configured in caFingerprint'));
request.once('error', () => { }); // we need to catch the request aborted error
return request.abort();
}
});
}
};
request.on('response', onResponse);
request.on('timeout', onTimeout);
request.on('error', onError);
request.on('abort', onAbort);
if (this[symbols_1.kCaFingerprint] != null && requestParams.protocol === 'https:') {
request.on('socket', onSocket);
}
// Disables the Nagle algorithm
request.setNoDelay(true);
// starts the request
if (isStream(params.body)) {
(0, stream_1.pipeline)(params.body, request, err => {
/* istanbul ignore if */
if (err != null && !cleanedListeners) {
cleanListeners();
this._openRequests--;
reject(err);
}
});
}
else {
request.end(params.body);
}
return request;
function cleanListeners() {
request.removeListener('response', onResponse);
request.removeListener('timeout', onTimeout);
request.removeListener('error', onError);
request.removeListener('abort', onAbort);
request.removeListener('socket', onSocket);
if (options.signal != null) {
if ('removeEventListener' in options.signal) {
options.signal.removeEventListener('abort', abortListener);
}
else {
options.signal.removeListener('abort', abortListener);
}
}
cleanedListeners = true;
}
});
}
async close() {
debug('Closing connection', this.id);
while (this._openRequests > 0) {
await sleep(1000);
}
/* istanbul ignore else */
if (this.agent !== undefined) {
this.agent.destroy();
}
}
buildRequestObject(params, options) {
var _a;
const url = this.url;
let search = url.search;
let pathname = url.pathname;
const request = {
protocol: url.protocol,
hostname: url.hostname[0] === '['
? url.hostname.slice(1, -1)
: url.hostname,
path: '',
// https://github.com/elastic/elasticsearch-js/issues/843
port: url.port !== '' ? url.port : undefined,
headers: this.headers,
agent: this.agent,
timeout: (_a = options.timeout) !== null && _a !== void 0 ? _a : this.timeout
};
const paramsKeys = Object.keys(params);
for (let i = 0, len = paramsKeys.length; i < len; i++) {
const key = paramsKeys[i];
if (key === 'path') {
pathname = resolve(pathname, params[key]);
}
else if (key === 'querystring' && Boolean(params[key])) {
if (search === '') {
search = `?${params[key]}`;
}
else {
search += `&${params[key]}`;
}
}
else if (key === 'headers') {
request.headers = Object.assign({}, request.headers, params.headers);
}
else {
// @ts-expect-error
request[key] = params[key];
}
}
request.path = pathname + search;
return request;
}
}
exports.default = HttpConnection;
function isStream(obj) {
return obj != null && typeof obj.pipe === 'function';
}
function resolve(host, path) {
const hostEndWithSlash = host[host.length - 1] === '/';
const pathStartsWithSlash = path[0] === '/';
if (hostEndWithSlash && pathStartsWithSlash) {
return host + path.slice(1);
}
else if (hostEndWithSlash !== pathStartsWithSlash) {
return host + path;
}
else {
return host + '/' + path;
}
}
/* istanbul ignore next */
function isHttpAgentOptions(opts) {
if (opts.keepAliveTimeout != null)
return false;
if (opts.keepAliveMaxTimeout != null)
return false;
if (opts.keepAliveTimeoutThreshold != null)
return false;
if (opts.pipelining != null)
return false;
if (opts.maxHeaderSize != null)
return false;
if (opts.connections != null)
return false;
return true;
}
async function sleep(ms) {
return await new Promise((resolve) => setTimeout(resolve, ms));
}
//# sourceMappingURL=HttpConnection.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,13 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import BaseConnection, { ConnectionOptions, ConnectionRequestParams, ConnectionRequestOptions, ConnectionRequestOptionsAsStream, ConnectionRequestResponse, ConnectionRequestResponseAsStream } from './BaseConnection';
import { Pool } from 'undici';
import { kEmitter } from '../symbols';
export default class Connection extends BaseConnection {
pool: Pool;
[kEmitter]: EventEmitter;
constructor(opts: ConnectionOptions);
request(params: ConnectionRequestParams, options: ConnectionRequestOptions): Promise<ConnectionRequestResponse>;
request(params: ConnectionRequestParams, options: ConnectionRequestOptionsAsStream): Promise<ConnectionRequestResponseAsStream>;
close(): Promise<void>;
}

View file

@ -0,0 +1,255 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/restrict-template-expressions */
const events_1 = require("events");
const debug_1 = tslib_1.__importDefault(require("debug"));
const buffer_1 = tslib_1.__importDefault(require("buffer"));
const BaseConnection_1 = tslib_1.__importStar(require("./BaseConnection"));
const undici_1 = require("undici");
const errors_1 = require("../errors");
const symbols_1 = require("../symbols");
const debug = (0, debug_1.default)('elasticsearch');
const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;
const MAX_BUFFER_LENGTH = buffer_1.default.constants.MAX_LENGTH;
const MAX_STRING_LENGTH = buffer_1.default.constants.MAX_STRING_LENGTH;
class Connection extends BaseConnection_1.default {
constructor(opts) {
var _b;
super(opts);
Object.defineProperty(this, "pool", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _a, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
if (opts.proxy != null) {
throw new errors_1.ConfigurationError('Undici connection can\'t work with proxies');
}
if (typeof opts.agent === 'function' || typeof opts.agent === 'boolean') {
throw new errors_1.ConfigurationError('Undici connection agent options can\'t be a function or a boolean');
}
if (opts.agent != null && !isUndiciAgentOptions(opts.agent)) {
throw new errors_1.ConfigurationError('Bad agent configuration for Undici agent');
}
this[symbols_1.kEmitter] = new events_1.EventEmitter();
const undiciOptions = {
keepAliveTimeout: 600e3,
keepAliveMaxTimeout: 600e3,
keepAliveTimeoutThreshold: 1000,
pipelining: 1,
maxHeaderSize: 16384,
connections: 256,
headersTimeout: this.timeout,
bodyTimeout: this.timeout,
...opts.agent
};
if (this[symbols_1.kCaFingerprint] !== null) {
const caFingerprint = this[symbols_1.kCaFingerprint];
const connector = (0, undici_1.buildConnector)(((_b = this.tls) !== null && _b !== void 0 ? _b : {}));
undiciOptions.connect = function (opts, cb) {
connector(opts, (err, socket) => {
if (err != null) {
return cb(err, null);
}
if (caFingerprint !== null && isTlsSocket(opts, socket)) {
const issuerCertificate = (0, BaseConnection_1.getIssuerCertificate)(socket);
/* istanbul ignore next */
if (issuerCertificate == null) {
socket.destroy();
return cb(new Error('Invalid or malformed certificate'), null);
}
// Check if fingerprint matches
/* istanbul ignore else */
if (caFingerprint !== issuerCertificate.fingerprint256) {
socket.destroy();
return cb(new Error('Server certificate CA fingerprint does not match the value configured in caFingerprint'), null);
}
}
return cb(null, socket);
});
};
}
else if (this.tls !== null) {
undiciOptions.connect = this.tls;
}
this.pool = new undici_1.Pool(this.url.toString(), undiciOptions);
}
async request(params, options) {
var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
const maxResponseSize = (_b = options.maxResponseSize) !== null && _b !== void 0 ? _b : MAX_STRING_LENGTH;
const maxCompressedResponseSize = (_c = options.maxCompressedResponseSize) !== null && _c !== void 0 ? _c : MAX_BUFFER_LENGTH;
const requestParams = {
method: params.method,
path: params.path + (params.querystring == null || params.querystring === '' ? '' : `?${params.querystring}`),
headers: Object.assign({}, this.headers, params.headers),
body: params.body,
signal: (_d = options.signal) !== null && _d !== void 0 ? _d : this[symbols_1.kEmitter]
};
if (requestParams.path[0] !== '/') {
requestParams.path = `/${requestParams.path}`;
}
// undici does not support per-request timeouts,
// to address this issue, we default to the constructor
// timeout (which is handled by undici) and create a local
// setTimeout callback if the request-specific timeout
// is different from the constructor timeout.
let timedout = false;
let timeoutId;
if (options.timeout != null && options.timeout !== this.timeout) {
timeoutId = setTimeout(() => {
timedout = true;
if (options.signal != null) {
options.signal.dispatchEvent('abort');
}
else {
this[symbols_1.kEmitter].emit('abort');
}
}, options.timeout);
}
// https://github.com/nodejs/node/commit/b961d9fd83
if (INVALID_PATH_REGEX.test(requestParams.path)) {
throw new TypeError(`ERR_UNESCAPED_CHARACTERS: ${requestParams.path}`);
}
debug('Starting a new request', params);
let response;
try {
// @ts-expect-error method it's fine as string
response = (await this.pool.request(requestParams));
if (timeoutId != null)
clearTimeout(timeoutId);
}
catch (err) {
if (timeoutId != null)
clearTimeout(timeoutId);
switch (err.code) {
case 'UND_ERR_ABORTED':
throw (timedout ? new errors_1.TimeoutError('Request timed out') : new errors_1.RequestAbortedError('Request aborted'));
case 'UND_ERR_HEADERS_TIMEOUT':
throw new errors_1.TimeoutError('Request timed out');
case 'UND_ERR_SOCKET':
throw new errors_1.ConnectionError(`${err.message} - Local: ${(_f = (_e = err.socket) === null || _e === void 0 ? void 0 : _e.localAddress) !== null && _f !== void 0 ? _f : 'unknown'}:${(_h = (_g = err.socket) === null || _g === void 0 ? void 0 : _g.localPort) !== null && _h !== void 0 ? _h : 'unknown'}, Remote: ${(_k = (_j = err.socket) === null || _j === void 0 ? void 0 : _j.remoteAddress) !== null && _k !== void 0 ? _k : 'unknown'}:${(_m = (_l = err.socket) === null || _l === void 0 ? void 0 : _l.remotePort) !== null && _m !== void 0 ? _m : 'unknown'}`); // eslint-disable-line
default:
throw new errors_1.ConnectionError(err.message);
}
}
if (options.asStream === true) {
return {
statusCode: response.statusCode,
headers: response.headers,
body: response.body
};
}
// @ts-expect-error Assume header is not string[] for now.
const contentEncoding = ((_o = response.headers['content-encoding']) !== null && _o !== void 0 ? _o : '').toLowerCase();
const isCompressed = contentEncoding.includes('gzip') || contentEncoding.includes('deflate'); // eslint-disable-line
const isVectorTile = ((_p = response.headers['content-type']) !== null && _p !== void 0 ? _p : '').includes('application/vnd.mapbox-vector-tile');
/* istanbul ignore else */
if (response.headers['content-length'] !== undefined) {
const contentLength = Number(response.headers['content-length']);
if (isCompressed && contentLength > maxCompressedResponseSize) { // eslint-disable-line
response.body.destroy();
throw new errors_1.RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed buffer (${maxCompressedResponseSize})`);
}
else if (contentLength > maxResponseSize) {
response.body.destroy();
throw new errors_1.RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed string (${maxResponseSize})`);
}
}
this.diagnostic.emit('deserialization', null, options);
try {
if (isCompressed || isVectorTile) { // eslint-disable-line
let currentLength = 0;
const payload = [];
for await (const chunk of response.body) {
currentLength += Buffer.byteLength(chunk);
if (currentLength > maxCompressedResponseSize) {
response.body.destroy();
throw new errors_1.RequestAbortedError(`The content length (${currentLength}) is bigger than the maximum allowed buffer (${maxCompressedResponseSize})`);
}
payload.push(chunk);
}
return {
statusCode: response.statusCode,
headers: response.headers,
body: Buffer.concat(payload)
};
}
else {
let payload = '';
let currentLength = 0;
response.body.setEncoding('utf8');
for await (const chunk of response.body) {
currentLength += Buffer.byteLength(chunk);
if (currentLength > maxResponseSize) {
response.body.destroy();
throw new errors_1.RequestAbortedError(`The content length (${currentLength}) is bigger than the maximum allowed string (${maxResponseSize})`);
}
payload += chunk;
}
return {
statusCode: response.statusCode,
headers: response.headers,
body: payload
};
}
}
catch (err) {
if (err.name === 'RequestAbortedError') {
throw err;
}
throw new errors_1.ConnectionError(err.message);
}
}
async close() {
debug('Closing connection', this.id);
await this.pool.close();
}
}
exports.default = Connection;
_a = symbols_1.kEmitter;
/* istanbul ignore next */
function isUndiciAgentOptions(opts) {
if (opts.keepAlive != null)
return false;
if (opts.keepAliveMsecs != null)
return false;
if (opts.maxSockets != null)
return false;
if (opts.maxFreeSockets != null)
return false;
if (opts.scheduling != null)
return false;
if (opts.proxy != null)
return false;
return true;
}
function isTlsSocket(opts, socket) {
return socket !== null && opts.protocol === 'https:';
}
//# sourceMappingURL=UndiciConnection.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,6 @@
import BaseConnection from './BaseConnection';
import HttpConnection from './HttpConnection';
import UndiciConnection from './UndiciConnection';
export type Connection = BaseConnection | HttpConnection | UndiciConnection;
export type { ConnectionOptions, ConnectionRequestParams, ConnectionRequestOptions, ConnectionRequestOptionsAsStream, ConnectionRequestResponse, ConnectionRequestResponseAsStream } from './BaseConnection';
export { BaseConnection, HttpConnection, UndiciConnection };

View file

@ -0,0 +1,29 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the 'License'); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.UndiciConnection = exports.HttpConnection = exports.BaseConnection = void 0;
const tslib_1 = require("tslib");
const BaseConnection_1 = tslib_1.__importDefault(require("./BaseConnection"));
exports.BaseConnection = BaseConnection_1.default;
const HttpConnection_1 = tslib_1.__importDefault(require("./HttpConnection"));
exports.HttpConnection = HttpConnection_1.default;
const UndiciConnection_1 = tslib_1.__importDefault(require("./UndiciConnection"));
exports.UndiciConnection = UndiciConnection_1.default;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/connection/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,8EAA6C;AAe3C,yBAfK,wBAAc,CAeL;AAdhB,8EAA6C;AAe3C,yBAfK,wBAAc,CAeL;AAdhB,kFAAiD;AAe/C,2BAfK,0BAAgB,CAeL"}

View file

@ -0,0 +1,44 @@
/// <reference types="node" />
import * as http from 'http';
import { DiagnosticResult } from './types';
export declare class ElasticsearchClientError extends Error {
constructor(message: string);
}
export declare class TimeoutError extends ElasticsearchClientError {
meta?: DiagnosticResult;
constructor(message: string, meta?: DiagnosticResult);
}
export declare class ConnectionError extends ElasticsearchClientError {
meta?: DiagnosticResult;
constructor(message: string, meta?: DiagnosticResult);
}
export declare class NoLivingConnectionsError extends ElasticsearchClientError {
meta: DiagnosticResult;
constructor(message: string, meta: DiagnosticResult);
}
export declare class SerializationError extends ElasticsearchClientError {
data: Record<string, any>;
constructor(message: string, data: Record<string, any>);
}
export declare class DeserializationError extends ElasticsearchClientError {
data: string;
constructor(message: string, data: string);
}
export declare class ConfigurationError extends ElasticsearchClientError {
constructor(message: string);
}
export declare class ResponseError extends ElasticsearchClientError {
meta: DiagnosticResult;
constructor(meta: DiagnosticResult);
get body(): any | undefined;
get statusCode(): number | undefined;
get headers(): http.IncomingHttpHeaders | undefined;
}
export declare class RequestAbortedError extends ElasticsearchClientError {
meta?: DiagnosticResult;
constructor(message: string, meta?: DiagnosticResult);
}
export declare class ProductNotSupportedError extends ElasticsearchClientError {
meta?: DiagnosticResult;
constructor(product: string, meta?: DiagnosticResult);
}

207
VISUALIZACION/node_modules/@elastic/transport/lib/errors.js generated vendored Executable file
View file

@ -0,0 +1,207 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProductNotSupportedError = exports.RequestAbortedError = exports.ResponseError = exports.ConfigurationError = exports.DeserializationError = exports.SerializationError = exports.NoLivingConnectionsError = exports.ConnectionError = exports.TimeoutError = exports.ElasticsearchClientError = void 0;
class ElasticsearchClientError extends Error {
constructor(message) {
super(message);
this.name = 'ElasticsearchClientError';
}
}
exports.ElasticsearchClientError = ElasticsearchClientError;
class TimeoutError extends ElasticsearchClientError {
constructor(message, meta) {
super(message);
Object.defineProperty(this, "meta", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, TimeoutError);
this.name = 'TimeoutError';
this.message = message !== null && message !== void 0 ? message : 'Timeout Error';
this.meta = meta;
}
}
exports.TimeoutError = TimeoutError;
class ConnectionError extends ElasticsearchClientError {
constructor(message, meta) {
super(message);
Object.defineProperty(this, "meta", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, ConnectionError);
this.name = 'ConnectionError';
this.message = message !== null && message !== void 0 ? message : 'Connection Error';
this.meta = meta;
}
}
exports.ConnectionError = ConnectionError;
class NoLivingConnectionsError extends ElasticsearchClientError {
constructor(message, meta) {
super(message);
Object.defineProperty(this, "meta", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, NoLivingConnectionsError);
this.name = 'NoLivingConnectionsError';
this.message = message !== null && message !== void 0 ? message : 'Given the configuration, the ConnectionPool was not able to find a usable Connection for this request.';
this.meta = meta;
}
}
exports.NoLivingConnectionsError = NoLivingConnectionsError;
class SerializationError extends ElasticsearchClientError {
constructor(message, data) {
super(message);
Object.defineProperty(this, "data", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, SerializationError);
this.name = 'SerializationError';
this.message = message !== null && message !== void 0 ? message : 'Serialization Error';
this.data = data;
}
}
exports.SerializationError = SerializationError;
class DeserializationError extends ElasticsearchClientError {
constructor(message, data) {
super(message);
Object.defineProperty(this, "data", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, DeserializationError);
this.name = 'DeserializationError';
this.message = message !== null && message !== void 0 ? message : 'Deserialization Error';
this.data = data;
}
}
exports.DeserializationError = DeserializationError;
class ConfigurationError extends ElasticsearchClientError {
constructor(message) {
super(message);
Error.captureStackTrace(this, ConfigurationError);
this.name = 'ConfigurationError';
this.message = message !== null && message !== void 0 ? message : 'Configuration Error';
}
}
exports.ConfigurationError = ConfigurationError;
class ResponseError extends ElasticsearchClientError {
constructor(meta) {
var _a;
super('Response Error');
Object.defineProperty(this, "meta", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, ResponseError);
this.name = 'ResponseError';
// TODO: this is for Elasticsearch
if (isObject(meta.body) && meta.body.error != null && meta.body.error.type != null) {
this.message = meta.body.error.type;
if (isObject(meta.body.error.caused_by)) {
const { type, reason } = meta.body.error.caused_by;
const causedBy = [
'\tCaused by:',
`\t\t${type}: ${reason}`
].join('\n');
this.message += `\n${causedBy}`;
}
if (Array.isArray(meta.body.error.root_cause) && meta.body.error.root_cause.length !== 0) {
const formatRootCause = (entry) => `\t\t${entry.type}: ${entry.reason}`;
const rootCauses = [
'\tRoot causes:',
...meta.body.error.root_cause.map(formatRootCause)
].join('\n');
this.message += `\n${rootCauses}`;
}
}
else if (typeof meta.body === 'object' && meta.body != null) {
this.message = JSON.stringify(meta.body);
}
else {
this.message = (_a = meta.body) !== null && _a !== void 0 ? _a : 'Response Error';
}
this.meta = meta;
}
get body() {
return this.meta.body;
}
get statusCode() {
if (isObject(this.meta.body) && typeof this.meta.body.status === 'number') {
return this.meta.body.status;
}
return this.meta.statusCode;
}
get headers() {
return this.meta.headers;
}
}
exports.ResponseError = ResponseError;
class RequestAbortedError extends ElasticsearchClientError {
constructor(message, meta) {
super(message);
Object.defineProperty(this, "meta", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, RequestAbortedError);
this.name = 'RequestAbortedError';
this.message = message !== null && message !== void 0 ? message : 'Request aborted';
this.meta = meta;
}
}
exports.RequestAbortedError = RequestAbortedError;
class ProductNotSupportedError extends ElasticsearchClientError {
constructor(product, meta) {
super('Product Not Supported Error');
Object.defineProperty(this, "meta", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, ProductNotSupportedError);
this.name = 'ProductNotSupportedError';
this.message = `The client noticed that the server is not ${product} and we do not support this unknown product.`;
this.meta = meta;
}
}
exports.ProductNotSupportedError = ProductNotSupportedError;
function isObject(obj) {
return typeof obj === 'object';
}
//# sourceMappingURL=errors.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAKH,MAAa,wBAAyB,SAAQ,KAAK;IACjD,YAAa,OAAe;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAA;IACxC,CAAC;CACF;AALD,4DAKC;AAED,MAAa,YAAa,SAAQ,wBAAwB;IAExD,YAAa,OAAe,EAAE,IAAuB;QACnD,KAAK,CAAC,OAAO,CAAC,CAAA;QAFhB;;;;;WAAuB;QAGrB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;QAC3C,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,eAAe,CAAA;QACzC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AATD,oCASC;AAED,MAAa,eAAgB,SAAQ,wBAAwB;IAE3D,YAAa,OAAe,EAAE,IAAuB;QACnD,KAAK,CAAC,OAAO,CAAC,CAAA;QAFhB;;;;;WAAuB;QAGrB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;QAC9C,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAA;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,kBAAkB,CAAA;QAC5C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AATD,0CASC;AAED,MAAa,wBAAyB,SAAQ,wBAAwB;IAEpE,YAAa,OAAe,EAAE,IAAsB;QAClD,KAAK,CAAC,OAAO,CAAC,CAAA;QAFhB;;;;;WAAsB;QAGpB,KAAK,CAAC,iBAAiB,CAAC,I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O,aAAP,OAAO,cAAP,OAAO,GAAI,iBAAiB,CAAA;QAC3C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AATD,kDASC;AAED,MAAa,wBAAyB,SAAQ,wBAAwB;IAEpE,YAAa,OAAe,EAAE,IAAuB;QACnD,KAAK,CAAC,6BAA6B,CAAC,CAAA;QAFtC;;;;;WAAuB;QAGrB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,wBAAwB,CAAC,CAAA;QACvD,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAA;QACtC,IAAI,CAAC,OAAO,GAAG,6CAA6C,OAAO,8CAA8C,CAAA;QACjH,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AATD,4DASC;AAED,SAAS,QAAQ,CAAE,GAAQ;IACzB,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAA;AAChC,CAAC"}

View file

@ -0,0 +1,89 @@
/// <reference types="node" />
/// <reference types="node" />
import { URL } from 'url';
import { ConnectionOptions as TlsConnectionOptions } from 'tls';
import Diagnostic from '../Diagnostic';
import { kCaFingerprint } from '../symbols';
import { Connection, ConnectionOptions, BaseConnection } from '../connection';
import { HttpAgentOptions, UndiciAgentOptions, agentFn, ApiKeyAuth, BasicAuth, BearerAuth, nodeFilterFn, nodeSelectorFn } from '../types';
type AddConnectionOptions = string | ConnectionOptions;
export interface ConnectionPoolOptions {
tls?: TlsConnectionOptions;
agent?: HttpAgentOptions | UndiciAgentOptions | agentFn | false;
proxy?: string | URL;
auth?: BasicAuth | ApiKeyAuth | BearerAuth;
diagnostic?: Diagnostic;
Connection: typeof BaseConnection;
pingTimeout?: number;
resurrectStrategy?: 'none' | 'ping' | 'optimistic';
caFingerprint?: string;
}
export interface GetConnectionOptions {
filter?: nodeFilterFn;
selector?: nodeSelectorFn;
now: number;
requestId: string | number;
name: string | symbol;
context: any;
}
export default class BaseConnectionPool {
connections: Connection[];
size: number;
Connection: typeof BaseConnection;
diagnostic: Diagnostic;
auth?: BasicAuth | ApiKeyAuth | BearerAuth;
_agent?: HttpAgentOptions | UndiciAgentOptions | agentFn | false;
_proxy?: string | URL;
_tls?: TlsConnectionOptions;
[kCaFingerprint]?: string;
constructor(opts: ConnectionPoolOptions);
markAlive(connection: Connection): this;
markDead(connection: Connection): this;
getConnection(opts: GetConnectionOptions): Connection | null;
/**
* Creates a new connection instance.
*/
createConnection(opts: string | ConnectionOptions): Connection;
/**
* Adds a new connection to the pool.
*
* @param {object|string} host
* @returns {ConnectionPool}
*/
addConnection(connection: AddConnectionOptions | AddConnectionOptions[]): this;
/**
* Removes a new connection to the pool.
*
* @param {object} connection
* @returns {ConnectionPool}
*/
removeConnection(connection: Connection): this;
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
empty(): Promise<void>;
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(nodes: Array<Connection | ConnectionOptions>): this;
/**
* Transforms the nodes objects to a host object.
*
* @param {object} nodes
* @returns {array} hosts
*/
nodesToHost(nodes: Record<string, any>, protocol: string): ConnectionOptions[];
/**
* Transforms an url string to a host object
*
* @param {string} url
* @returns {object} host
*/
urlToHost(url: string): ConnectionOptions;
}
export {};

View file

@ -0,0 +1,296 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const url_1 = require("url");
const debug_1 = tslib_1.__importDefault(require("debug"));
const Diagnostic_1 = tslib_1.__importDefault(require("../Diagnostic"));
const symbols_1 = require("../symbols");
const connection_1 = require("../connection");
const errors_1 = require("../errors");
const debug = (0, debug_1.default)('elasticsearch');
class BaseConnectionPool {
constructor(opts) {
var _b;
Object.defineProperty(this, "connections", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "size", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "Connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "diagnostic", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "auth", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "_agent", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "_proxy", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "_tls", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, _a, {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
// list of nodes and weights
this.connections = [];
// how many nodes we have in our scheduler
this.size = this.connections.length;
this.Connection = opts.Connection;
this.diagnostic = (_b = opts.diagnostic) !== null && _b !== void 0 ? _b : new Diagnostic_1.default();
this.auth = opts.auth;
this._tls = opts.tls;
this._agent = opts.agent;
this._proxy = opts.proxy;
this[symbols_1.kCaFingerprint] = opts.caFingerprint;
}
markAlive(connection) {
connection.status = connection_1.BaseConnection.statuses.ALIVE;
return this;
}
markDead(connection) {
connection.status = connection_1.BaseConnection.statuses.DEAD;
return this;
}
getConnection(opts) {
throw new errors_1.ConfigurationError('The getConnection method should be implemented by extended classes');
}
/**
* Creates a new connection instance.
*/
createConnection(opts) {
if (typeof opts === 'string') {
opts = this.urlToHost(opts);
}
if (this.auth != null) {
opts.auth = this.auth;
}
else if (opts.url.username !== '' && opts.url.password !== '') {
opts.auth = {
username: decodeURIComponent(opts.url.username),
password: decodeURIComponent(opts.url.password)
};
}
/* istanbul ignore else */
if (opts.tls == null)
opts.tls = this._tls;
/* istanbul ignore else */
if (opts.agent == null)
opts.agent = this._agent;
/* istanbul ignore else */
if (opts.proxy == null)
opts.proxy = this._proxy;
/* istanbul ignore else */
if (opts.diagnostic == null)
opts.diagnostic = this.diagnostic;
/* istanbul ignore else */
if (opts.caFingerprint == null)
opts.caFingerprint = this[symbols_1.kCaFingerprint];
const connection = new this.Connection(opts);
for (const conn of this.connections) {
if (conn.id === connection.id) {
throw new Error(`Connection with id '${connection.id}' is already present`);
}
}
return connection;
}
/**
* Adds a new connection to the pool.
*
* @param {object|string} host
* @returns {ConnectionPool}
*/
addConnection(connection) {
if (Array.isArray(connection)) {
const connections = [];
for (const conn of connection) {
connections.push(this.createConnection(conn));
}
return this.update([...this.connections, ...connections]);
}
else {
return this.update([...this.connections, this.createConnection(connection)]);
}
}
/**
* Removes a new connection to the pool.
*
* @param {object} connection
* @returns {ConnectionPool}
*/
removeConnection(connection) {
debug('Removing connection', connection);
return this.update(this.connections.filter(c => c.id !== connection.id));
}
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
async empty() {
debug('Emptying the connection pool');
const connections = this.connections;
this.connections = [];
this.size = 0;
for (const connection of connections) {
await connection.close();
}
}
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(nodes) {
debug('Updating the connection pool');
const newConnections = [];
const oldConnections = [];
for (const node of nodes) {
// if we already have a given connection in the pool
// we mark it as alive and we do not close the connection
// to avoid socket issues
const connectionById = this.connections.find(c => c.id === node.id);
const connectionByUrl = this.connections.find(c => c.id === node.url.href);
if (connectionById != null) {
debug(`The connection with id '${node.id}' is already present`);
this.markAlive(connectionById);
newConnections.push(connectionById);
// in case the user has passed a single url (or an array of urls),
// the connection id will be the full href; to avoid closing valid connections
// because are not present in the pool, we check also the node url,
// and if is already present we update its id with the ES provided one.
}
else if (connectionByUrl != null) {
connectionByUrl.id = node.id;
this.markAlive(connectionByUrl);
newConnections.push(connectionByUrl);
}
else {
if (node instanceof connection_1.BaseConnection) {
newConnections.push(node);
}
else {
newConnections.push(this.createConnection(node));
}
}
}
const ids = nodes.map(c => c.id);
// remove all the dead connections and old connections
for (const connection of this.connections) {
if (!ids.includes(connection.id)) {
oldConnections.push(connection);
}
}
// close old connections
for (const connection of oldConnections) {
connection.close().catch(/* istanbul ignore next */ () => { });
}
this.connections = newConnections;
this.size = this.connections.length;
return this;
}
/**
* Transforms the nodes objects to a host object.
*
* @param {object} nodes
* @returns {array} hosts
*/
nodesToHost(nodes, protocol) {
const ids = Object.keys(nodes);
const hosts = [];
for (let i = 0, len = ids.length; i < len; i++) {
const node = nodes[ids[i]];
// If there is no protocol in
// the `publish_address` new URL will throw
// the publish_address can have two forms:
// - ip:port
// - hostname/ip:port
// if we encounter the second case, we should
// use the hostname instead of the ip
let address = node.http.publish_address;
const parts = address.split('/');
// the url is in the form of hostname/ip:port
if (parts.length > 1) {
const hostname = parts[0];
const port = parts[1].match(/((?::))(?:[0-9]+)$/g)[0].slice(1);
address = `${hostname}:${port}`;
}
address = address.slice(0, 4) === 'http'
/* istanbul ignore next */
? address
: `${protocol}//${address}`;
hosts.push({
url: new url_1.URL(address),
id: ids[i]
});
}
return hosts;
}
/**
* Transforms an url string to a host object
*
* @param {string} url
* @returns {object} host
*/
urlToHost(url) {
return {
url: new url_1.URL(url)
};
}
}
exports.default = BaseConnectionPool;
_a = symbols_1.kCaFingerprint;
//# sourceMappingURL=BaseConnectionPool.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,25 @@
import BaseConnectionPool, { ConnectionPoolOptions, GetConnectionOptions } from './BaseConnectionPool';
import { Connection, ConnectionOptions } from '../connection';
export default class CloudConnectionPool extends BaseConnectionPool {
cloudConnection: Connection | null;
constructor(opts: ConnectionPoolOptions);
/**
* Returns the only cloud connection.
*
* @returns {object} connection
*/
getConnection(opts: GetConnectionOptions): Connection | null;
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
empty(): Promise<void>;
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(connections: Array<Connection | ConnectionOptions>): this;
}

View file

@ -0,0 +1,64 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const BaseConnectionPool_1 = tslib_1.__importDefault(require("./BaseConnectionPool"));
class CloudConnectionPool extends BaseConnectionPool_1.default {
constructor(opts) {
super(opts);
Object.defineProperty(this, "cloudConnection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.cloudConnection = null;
}
/**
* Returns the only cloud connection.
*
* @returns {object} connection
*/
getConnection(opts) {
return this.cloudConnection;
}
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
async empty() {
await super.empty();
this.cloudConnection = null;
}
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(connections) {
super.update(connections);
this.cloudConnection = this.connections[0];
return this;
}
}
exports.default = CloudConnectionPool;
//# sourceMappingURL=CloudConnectionPool.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"CloudConnectionPool.js","sourceRoot":"","sources":["../../src/pool/CloudConnectionPool.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAEH,sFAG6B;AAG7B,MAAqB,mBAAoB,SAAQ,4BAAkB;IAEjE,YAAa,IAA2B;QACtC,KAAK,CAAC,IAAI,CAAC,CAAA;QAFb;;;;;WAAkC;QAGhC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAA;IAC7B,CAAC;IAED;;;;OAIG;IACH,aAAa,CAAE,IAA0B;QACvC,OAAO,IAAI,CAAC,eAAe,CAAA;IAC7B,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK;QACT,MAAM,KAAK,CAAC,KAAK,EAAE,CAAA;QACnB,IAAI,CAAC,eAAe,GAAG,IAAI,CAAA;IAC7B,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAE,WAAkD;QACxD,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAA;QACzB,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;QAC1C,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AArCD,sCAqCC"}

View file

@ -0,0 +1,77 @@
import BaseConnectionPool, { ConnectionPoolOptions, GetConnectionOptions } from './BaseConnectionPool';
import { Connection, ConnectionOptions } from '../connection';
export interface ResurrectOptions {
now: number;
requestId: string | number;
name: string | symbol;
context: any;
}
export interface ResurrectEvent {
strategy: string;
name: string | symbol;
request: {
id: string;
};
isAlive: boolean;
connection: Connection;
}
export default class ClusterConnectionPool extends BaseConnectionPool {
dead: string[];
resurrectTimeout: number;
resurrectTimeoutCutoff: number;
pingTimeout: number;
resurrectStrategy: number;
static resurrectStrategies: {
none: number;
ping: number;
optimistic: number;
};
constructor(opts: ConnectionPoolOptions);
/**
* Marks a connection as 'alive'.
* If needed removes the connection from the dead list
* and then resets the `deadCount`.
*
* @param {object} connection
*/
markAlive(connection: Connection): this;
/**
* Marks a connection as 'dead'.
* If needed adds the connection to the dead list
* and then increments the `deadCount`.
*
* @param {object} connection
*/
markDead(connection: Connection): this;
/**
* If enabled, tries to resurrect a connection with the given
* resurrect strategy ('ping', 'optimistic', 'none').
*
* @param {object} { now, requestId }
*/
resurrect(opts: ResurrectOptions): void;
/**
* Returns an alive connection if present,
* otherwise returns a dead connection.
* By default it filters the `master` only nodes.
* It uses the selector to choose which
* connection return.
*
* @param {object} options (filter and selector)
* @returns {object|null} connection
*/
getConnection(opts: GetConnectionOptions): Connection | null;
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
empty(): Promise<void>;
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(connections: Array<Connection | ConnectionOptions>): this;
}

View file

@ -0,0 +1,259 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const BaseConnectionPool_1 = tslib_1.__importDefault(require("./BaseConnectionPool"));
const assert_1 = tslib_1.__importDefault(require("assert"));
const debug_1 = tslib_1.__importDefault(require("debug"));
const connection_1 = require("../connection");
const debug = (0, debug_1.default)('elasticsearch');
class ClusterConnectionPool extends BaseConnectionPool_1.default {
constructor(opts) {
var _a, _b;
super(opts);
Object.defineProperty(this, "dead", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "resurrectTimeout", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "resurrectTimeoutCutoff", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "pingTimeout", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "resurrectStrategy", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.dead = [];
// the resurrect timeout is 60s
this.resurrectTimeout = 1000 * 60;
// number of consecutive failures after which
// the timeout doesn't increase
this.resurrectTimeoutCutoff = 5;
this.pingTimeout = (_a = opts.pingTimeout) !== null && _a !== void 0 ? _a : 3000;
const resurrectStrategy = (_b = opts.resurrectStrategy) !== null && _b !== void 0 ? _b : 'ping';
this.resurrectStrategy = ClusterConnectionPool.resurrectStrategies[resurrectStrategy];
(0, assert_1.default)(this.resurrectStrategy != null, `Invalid resurrection strategy: '${resurrectStrategy}'`);
}
/**
* Marks a connection as 'alive'.
* If needed removes the connection from the dead list
* and then resets the `deadCount`.
*
* @param {object} connection
*/
markAlive(connection) {
const { id } = connection;
debug(`Marking as 'alive' connection '${id}'`);
const index = this.dead.indexOf(id);
if (index > -1)
this.dead.splice(index, 1);
connection.status = connection_1.BaseConnection.statuses.ALIVE;
connection.deadCount = 0;
connection.resurrectTimeout = 0;
return this;
}
/**
* Marks a connection as 'dead'.
* If needed adds the connection to the dead list
* and then increments the `deadCount`.
*
* @param {object} connection
*/
markDead(connection) {
const { id } = connection;
debug(`Marking as 'dead' connection '${id}'`);
if (!this.dead.includes(id)) {
// It might happen that `markDead` is called jsut after
// a pool update, and in such case we will add to the dead
// list a node that no longer exist. The following check verify
// that the connection is still part of the pool before
// marking it as dead.
for (let i = 0; i < this.size; i++) {
if (this.connections[i].id === id) {
this.dead.push(id);
break;
}
}
}
connection.status = connection_1.BaseConnection.statuses.DEAD;
connection.deadCount++;
// resurrectTimeout formula:
// `resurrectTimeout * 2 ** min(deadCount - 1, resurrectTimeoutCutoff)`
connection.resurrectTimeout = Date.now() + this.resurrectTimeout * Math.pow(2, Math.min(connection.deadCount - 1, this.resurrectTimeoutCutoff));
// sort the dead list in ascending order
// based on the resurrectTimeout
this.dead.sort((a, b) => {
const conn1 = this.connections.find(c => c.id === a);
const conn2 = this.connections.find(c => c.id === b);
return conn1.resurrectTimeout - conn2.resurrectTimeout;
});
return this;
}
/**
* If enabled, tries to resurrect a connection with the given
* resurrect strategy ('ping', 'optimistic', 'none').
*
* @param {object} { now, requestId }
*/
resurrect(opts) {
if (this.resurrectStrategy === 0 || this.dead.length === 0) {
debug('Nothing to resurrect');
return;
}
// the dead list is sorted in ascending order based on the timeout
// so the first element will always be the one with the smaller timeout
const connection = this.connections.find(c => c.id === this.dead[0]);
if (opts.now < connection.resurrectTimeout) {
debug('Nothing to resurrect');
return;
}
const { id } = connection;
// ping strategy
if (this.resurrectStrategy === 1) {
connection.request({ method: 'HEAD', path: '/' }, { timeout: this.pingTimeout, requestId: opts.requestId, name: opts.name, context: opts.context })
.then(({ statusCode }) => {
let isAlive = true;
if (statusCode === 502 || statusCode === 503 || statusCode === 504) {
debug(`Resurrect: connection '${id}' is still dead`);
this.markDead(connection);
isAlive = false;
}
else {
debug(`Resurrect: connection '${id}' is now alive`);
this.markAlive(connection);
}
this.diagnostic.emit('resurrect', null, {
strategy: 'ping',
name: opts.name,
request: { id: opts.requestId },
isAlive,
connection
});
})
.catch((err) => {
this.markDead(connection);
this.diagnostic.emit('resurrect', err, {
strategy: 'ping',
name: opts.name,
request: { id: opts.requestId },
isAlive: false,
connection
});
});
// optimistic strategy
}
else {
debug(`Resurrect: optimistic resurrection for connection '${id}'`);
this.dead.splice(this.dead.indexOf(id), 1);
connection.status = connection_1.BaseConnection.statuses.ALIVE;
this.diagnostic.emit('resurrect', null, {
strategy: 'optimistic',
name: opts.name,
request: { id: opts.requestId },
isAlive: true,
connection
});
}
}
/**
* Returns an alive connection if present,
* otherwise returns a dead connection.
* By default it filters the `master` only nodes.
* It uses the selector to choose which
* connection return.
*
* @param {object} options (filter and selector)
* @returns {object|null} connection
*/
getConnection(opts) {
const filter = opts.filter != null ? opts.filter : () => true;
const selector = opts.selector != null ? opts.selector : (c) => c[0];
this.resurrect({
now: opts.now,
requestId: opts.requestId,
name: opts.name,
context: opts.context
});
const noAliveConnections = this.size === this.dead.length;
// TODO: can we cache this?
const connections = [];
for (let i = 0; i < this.size; i++) {
const connection = this.connections[i];
if (noAliveConnections || connection.status === connection_1.BaseConnection.statuses.ALIVE) {
if (filter(connection)) {
connections.push(connection);
}
}
}
if (connections.length === 0)
return null;
return selector(connections);
}
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
async empty() {
await super.empty();
this.dead = [];
}
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(connections) {
super.update(connections);
this.dead = [];
return this;
}
}
exports.default = ClusterConnectionPool;
Object.defineProperty(ClusterConnectionPool, "resurrectStrategies", {
enumerable: true,
configurable: true,
writable: true,
value: {
none: 0,
ping: 1,
optimistic: 2
}
});
//# sourceMappingURL=ClusterConnectionPool.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,45 @@
import { Connection, ConnectionOptions } from '../connection';
import BaseConnectionPool, { ConnectionPoolOptions, GetConnectionOptions } from './BaseConnectionPool';
export default class WeightedConnectionPool extends BaseConnectionPool {
index: number;
maxWeight: number;
greatestCommonDivisor: number;
currentWeight: number;
constructor(opts: ConnectionPoolOptions);
/**
* Returns a connection, even if the connection might be dead.
*
* @param {object} options (filter)
* @returns {object|null} connection
*/
getConnection(opts: GetConnectionOptions): Connection | null;
/**
* Set the weight of a connection to the maximum value.
* If sniffing is not enabled and there is only
* one node, this method is a noop.
*
* @param {object} connection
*/
markAlive(connection: Connection): this;
/**
* Decreases the connection weight.
* If sniffing is not enabled and there is only
* one node, this method is a noop.
*
* @param {object} connection
*/
markDead(connection: Connection): this;
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
empty(): Promise<void>;
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(connections: Array<Connection | ConnectionOptions>): this;
}

View file

@ -0,0 +1,165 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const connection_1 = require("../connection");
const BaseConnectionPool_1 = tslib_1.__importDefault(require("./BaseConnectionPool"));
const noFilter = () => true;
class WeightedConnectionPool extends BaseConnectionPool_1.default {
constructor(opts) {
super(opts);
Object.defineProperty(this, "index", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "maxWeight", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "greatestCommonDivisor", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "currentWeight", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
// index choosen last time
this.index = -1;
// max weight of all nodes
this.maxWeight = 0;
// greatest common divisor of all nodes weights
this.greatestCommonDivisor = 0;
// current weight in scheduling
this.currentWeight = 0;
}
/**
* Returns a connection, even if the connection might be dead.
*
* @param {object} options (filter)
* @returns {object|null} connection
*/
getConnection(opts) {
const filter = opts.filter != null ? opts.filter : noFilter;
// we should be able to find the next node in 1 array scan,
// if we don't, it means that we are in an infinite loop
let counter = 0;
while (counter++ < this.size) {
// 0 <= index < size
this.index = (this.index + 1) % this.size;
if (this.index === 0) {
this.currentWeight = this.currentWeight - this.greatestCommonDivisor;
if (this.currentWeight <= 0) {
this.currentWeight = this.maxWeight;
/* istanbul ignore if */
if (this.currentWeight === 0) {
return null;
}
}
}
const connection = this.connections[this.index];
if (connection.weight >= this.currentWeight && filter(connection)) {
return connection;
}
}
return null;
}
/**
* Set the weight of a connection to the maximum value.
* If sniffing is not enabled and there is only
* one node, this method is a noop.
*
* @param {object} connection
*/
markAlive(connection) {
if (this.size === 1 || connection.status === connection_1.BaseConnection.statuses.ALIVE)
return this;
connection.status = connection_1.BaseConnection.statuses.ALIVE;
connection.deadCount = 0;
connection.weight = Math.round(1000 / this.size);
this.maxWeight = Math.max(...(this.connections.map(c => c.weight)));
this.greatestCommonDivisor = this.connections.map(c => c.weight).reduce(getGreatestCommonDivisor, 0);
return this;
}
/**
* Decreases the connection weight.
* If sniffing is not enabled and there is only
* one node, this method is a noop.
*
* @param {object} connection
*/
markDead(connection) {
if (this.size === 1)
return this;
connection.status = connection_1.BaseConnection.statuses.DEAD;
connection.deadCount++;
connection.weight -= Math.round(Math.pow(Math.log2(connection.weight), connection.deadCount));
/* istanbul ignore if */
if (connection.weight <= 0)
connection.weight = 1;
this.maxWeight = Math.max(...(this.connections.map(c => c.weight)));
this.greatestCommonDivisor = this.connections.map(c => c.weight).reduce(getGreatestCommonDivisor, 0);
return this;
}
/**
* Empties the connection pool.
*
* @returns {ConnectionPool}
*/
async empty() {
await super.empty();
this.maxWeight = 0;
this.greatestCommonDivisor = 0;
this.index = -1;
this.currentWeight = 0;
}
/**
* Update the ConnectionPool with new connections.
*
* @param {array} array of connections
* @returns {ConnectionPool}
*/
update(connections) {
super.update(connections);
this.connections.forEach(connection => {
connection.weight = Math.round(1000 / this.size);
});
this.maxWeight = Math.max(...(this.connections.map(c => c.weight)));
this.greatestCommonDivisor = this.connections.map(c => c.weight).reduce(getGreatestCommonDivisor, 0);
this.index = -1;
this.currentWeight = 0;
return this;
}
}
exports.default = WeightedConnectionPool;
function getGreatestCommonDivisor(a, b) {
if (b === 0)
return a;
return getGreatestCommonDivisor(b, a % b);
}
//# sourceMappingURL=WeightedConnectionPool.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"WeightedConnectionPool.js","sourceRoot":"","sources":["../../src/pool/WeightedConnectionPool.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAEH,8CAA6E;AAC7E,sFAG6B;AAE7B,MAAM,QAAQ,GAAG,G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C,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QACnE,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,wBAAwB,EAAE,CAAC,CAAC,CAAA;QACpG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAA;QACf,IAAI,CAAC,aAAa,GAAG,CAAC,CAAA;QAEtB,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA7HD,yCA6HC;AAED,SAAS,wBAAwB,CAAE,CAAS,EAAE,CAAS;IACrD,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,CAAC,CAAA;IACrB,OAAO,wBAAwB,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;AAC3C,CAAC"}

View file

@ -0,0 +1,7 @@
import BaseConnectionPool from './BaseConnectionPool';
import WeightedConnectionPool from './WeightedConnectionPool';
import ClusterConnectionPool from './ClusterConnectionPool';
import CloudConnectionPool from './CloudConnectionPool';
export type { ConnectionPoolOptions, GetConnectionOptions } from './BaseConnectionPool';
export type { ResurrectEvent, ResurrectOptions } from './ClusterConnectionPool';
export { BaseConnectionPool, WeightedConnectionPool, ClusterConnectionPool, CloudConnectionPool };

View file

@ -0,0 +1,31 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the 'License'); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.CloudConnectionPool = exports.ClusterConnectionPool = exports.WeightedConnectionPool = exports.BaseConnectionPool = void 0;
const tslib_1 = require("tslib");
const BaseConnectionPool_1 = tslib_1.__importDefault(require("./BaseConnectionPool"));
exports.BaseConnectionPool = BaseConnectionPool_1.default;
const WeightedConnectionPool_1 = tslib_1.__importDefault(require("./WeightedConnectionPool"));
exports.WeightedConnectionPool = WeightedConnectionPool_1.default;
const ClusterConnectionPool_1 = tslib_1.__importDefault(require("./ClusterConnectionPool"));
exports.ClusterConnectionPool = ClusterConnectionPool_1.default;
const CloudConnectionPool_1 = tslib_1.__importDefault(require("./CloudConnectionPool"));
exports.CloudConnectionPool = CloudConnectionPool_1.default;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pool/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,sFAAqD;AAgBnD,6BAhBK,4BAAkB,CAgBL;AAfpB,8FAA6D;AAgB3D,iCAhBK,gCAAsB,CAgBL;AAfxB,4FAA2D;AAgBzD,gCAhBK,+BAAqB,CAgBL;AAfvB,wFAAuD;AAgBrD,8BAhBK,6BAAmB,CAgBL"}

View file

@ -0,0 +1,29 @@
export declare const kSniffEnabled: unique symbol;
export declare const kNextSniff: unique symbol;
export declare const kIsSniffing: unique symbol;
export declare const kSniffInterval: unique symbol;
export declare const kSniffOnConnectionFault: unique symbol;
export declare const kSniffEndpoint: unique symbol;
export declare const kRequestTimeout: unique symbol;
export declare const kCompression: unique symbol;
export declare const kMaxRetries: unique symbol;
export declare const kName: unique symbol;
export declare const kOpaqueIdPrefix: unique symbol;
export declare const kGenerateRequestId: unique symbol;
export declare const kContext: unique symbol;
export declare const kConnectionPool: unique symbol;
export declare const kSerializer: unique symbol;
export declare const kDiagnostic: unique symbol;
export declare const kHeaders: unique symbol;
export declare const kNodeFilter: unique symbol;
export declare const kNodeSelector: unique symbol;
export declare const kJsonOptions: unique symbol;
export declare const kStatus: unique symbol;
export declare const kEmitter: unique symbol;
export declare const kProductCheck: unique symbol;
export declare const kCaFingerprint: unique symbol;
export declare const kMaxResponseSize: unique symbol;
export declare const kMaxCompressedResponseSize: unique symbol;
export declare const kJsonContentType: unique symbol;
export declare const kNdjsonContentType: unique symbol;
export declare const kAcceptHeader: unique symbol;

51
VISUALIZACION/node_modules/@elastic/transport/lib/symbols.js generated vendored Executable file
View file

@ -0,0 +1,51 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.kAcceptHeader = exports.kNdjsonContentType = exports.kJsonContentType = exports.kMaxCompressedResponseSize = exports.kMaxResponseSize = exports.kCaFingerprint = exports.kProductCheck = exports.kEmitter = exports.kStatus = exports.kJsonOptions = exports.kNodeSelector = exports.kNodeFilter = exports.kHeaders = exports.kDiagnostic = exports.kSerializer = exports.kConnectionPool = exports.kContext = exports.kGenerateRequestId = exports.kOpaqueIdPrefix = exports.kName = exports.kMaxRetries = exports.kCompression = exports.kRequestTimeout = exports.kSniffEndpoint = exports.kSniffOnConnectionFault = exports.kSniffInterval = exports.kIsSniffing = exports.kNextSniff = exports.kSniffEnabled = void 0;
exports.kSniffEnabled = Symbol('sniff enabled');
exports.kNextSniff = Symbol('next sniff');
exports.kIsSniffing = Symbol('is sniffing');
exports.kSniffInterval = Symbol('sniff interval');
exports.kSniffOnConnectionFault = Symbol('sniff on connection fault');
exports.kSniffEndpoint = Symbol('sniff endpoint');
exports.kRequestTimeout = Symbol('request timeout');
exports.kCompression = Symbol('compression');
exports.kMaxRetries = Symbol('max retries');
exports.kName = Symbol('name');
exports.kOpaqueIdPrefix = Symbol('opaque id prefix');
exports.kGenerateRequestId = Symbol('generate request id');
exports.kContext = Symbol('context');
exports.kConnectionPool = Symbol('connection pool');
exports.kSerializer = Symbol('serializer');
exports.kDiagnostic = Symbol('diagnostics');
exports.kHeaders = Symbol('headers');
exports.kNodeFilter = Symbol('node filter');
exports.kNodeSelector = Symbol('node selector');
exports.kJsonOptions = Symbol('secure json parse options');
exports.kStatus = Symbol('status');
exports.kEmitter = Symbol('event emitter');
exports.kProductCheck = Symbol('product check');
exports.kCaFingerprint = Symbol('ca fingerprint');
exports.kMaxResponseSize = Symbol('max response size');
exports.kMaxCompressedResponseSize = Symbol('max compressed response size');
exports.kJsonContentType = Symbol('json content type');
exports.kNdjsonContentType = Symbol('ndjson content type');
exports.kAcceptHeader = Symbol('accept header');
//# sourceMappingURL=symbols.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"symbols.js","sourceRoot":"","sources":["../src/symbols.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAEU,QAAA,aAAa,GAAG,MAAM,CAAC,eAAe,CAAC,CAAA;AACvC,QAAA,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;AACjC,QAAA,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AACnC,QAAA,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAA;AACzC,QAAA,uBAAuB,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAA;AAC7D,QAAA,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAA;AACzC,QAAA,eAAe,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAA;AAC3C,QAAA,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AACpC,QAAA,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AACnC,QAAA,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA;AACtB,QAAA,eAAe,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAA;AAC5C,QAAA,kBAAkB,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAA;AAClD,QAAA,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AAC5B,QAAA,eAAe,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAA;AAC3C,QAAA,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;AAClC,QAAA,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AACnC,QAAA,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AAC5B,QAAA,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AACnC,QAAA,aAAa,GAAG,MAAM,CAAC,eAAe,CAAC,CAAA;AACvC,QAAA,YAAY,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAA;AAClD,QAAA,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAC1B,QAAA,QAAQ,GAAG,MAAM,CAAC,eAAe,CAAC,CAAA;AAClC,QAAA,aAAa,GAAG,MAAM,CAAC,eAAe,CAAC,CAAA;AACvC,QAAA,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAA;AACzC,QAAA,gBAAgB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAA;AAC9C,QAAA,0BAA0B,GAAG,MAAM,CAAC,8BAA8B,CAAC,CAAA;AACnE,QAAA,gBAAgB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAA;AAC9C,QAAA,kBAAkB,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAA;AAClD,QAAA,aAAa,GAAG,MAAM,CAAC,eAAe,CAAC,CAAA"}

73
VISUALIZACION/node_modules/@elastic/transport/lib/types.d.ts generated vendored Executable file
View file

@ -0,0 +1,73 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { Readable as ReadableStream } from 'stream';
import { URL } from 'url';
import * as http from 'http';
import { Connection, ConnectionOptions, ConnectionRequestParams } from './connection';
import { TransportRequestParams, TransportRequestOptions } from './Transport';
export type Context = Record<string, unknown> | null;
export type RequestBody<T = Record<string, any>> = T | string | Buffer | ReadableStream;
export type RequestNDBody<T = Array<Record<string, any>>> = T | string | string[] | Buffer | ReadableStream;
export interface DiagnosticResult<TResponse = unknown, TContext = unknown> {
body?: TResponse;
statusCode?: number;
headers?: http.IncomingHttpHeaders;
warnings: string[] | null;
meta: {
context: TContext;
name: string | symbol;
request: {
params: ConnectionRequestParams;
options: TransportRequestOptions;
id: any;
};
connection: Connection | null;
attempts: number;
aborted: boolean;
sniff?: {
hosts: any[];
reason: string;
};
};
}
export type DiagnosticResultResponse<TResponse = unknown, TContext = unknown> = Required<DiagnosticResult<TResponse, TContext>>;
export interface TransportResult<TResponse = unknown, TContext = unknown> extends DiagnosticResult<TResponse, TContext> {
body: TResponse;
statusCode: number;
headers: http.IncomingHttpHeaders;
}
export declare type agentFn = (opts: ConnectionOptions) => any;
export interface HttpAgentOptions {
keepAlive?: boolean;
keepAliveMsecs?: number;
maxSockets?: number;
maxFreeSockets?: number;
scheduling?: 'lifo' | 'fifo';
proxy?: string | URL;
}
export interface UndiciAgentOptions {
keepAliveTimeout?: number;
keepAliveMaxTimeout?: number;
keepAliveTimeoutThreshold?: number;
pipelining?: number;
maxHeaderSize?: number;
connections?: number;
}
export interface ApiKeyAuth {
apiKey: string | {
id: string;
api_key: string;
};
}
export interface BasicAuth {
username: string;
password: string;
}
export interface BearerAuth {
bearer: string;
}
export type nodeSelectorFn = (connections: Connection[]) => Connection;
export type nodeFilterFn = (connection: Connection) => boolean;
export type generateRequestIdFn = (params: TransportRequestParams, options: TransportRequestOptions) => any;

21
VISUALIZACION/node_modules/@elastic/transport/lib/types.js generated vendored Executable file
View file

@ -0,0 +1,21 @@
"use strict";
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG"}

View file

@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,481 @@
# debug
[![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_.
<img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png">
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
`disable()`
Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.
For example:
```js
let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);
```
Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Usage in child processes
Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process.
For example:
```javascript
worker = fork(WORKER_WRAP_PATH, [workerPath], {
stdio: [
/* stdin: */ 0,
/* stdout: */ 'pipe',
/* stderr: */ 'pipe',
'ipc',
],
env: Object.assign({}, process.env, {
DEBUG_COLORS: 1 // without this settings, colors won't be shown
}),
});
worker.stderr.pipe(process.stderr, { end: false });
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
- Josh Junon
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Zeit, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,37 @@
{
"name": "ms",
"version": "2.1.2",
"description": "Tiny millisecond conversion utility",
"repository": "zeit/ms",
"main": "./index",
"files": [
"index.js"
],
"scripts": {
"precommit": "lint-staged",
"lint": "eslint lib/* bin/*",
"test": "mocha tests.js"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"license": "MIT",
"devDependencies": {
"eslint": "4.12.1",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1"
}
}

View file

@ -0,0 +1,60 @@
# ms
[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms)
[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

View file

@ -0,0 +1,59 @@
{
"name": "debug",
"version": "4.3.4",
"repository": {
"type": "git",
"url": "git://github.com/debug-js/debug.git"
},
"description": "Lightweight debugging utility for Node.js and the browser",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"LICENSE",
"README.md"
],
"author": "Josh Junon <josh.junon@protonmail.com>",
"contributors": [
"TJ Holowaychuk <tj@vision-media.ca>",
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"scripts": {
"lint": "xo",
"test": "npm run test:node && npm run test:browser && npm run lint",
"test:node": "istanbul cover _mocha -- test.js",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls"
},
"dependencies": {
"ms": "2.1.2"
},
"devDependencies": {
"brfs": "^2.0.1",
"browserify": "^16.2.3",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.1.4",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"xo": "^0.23.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"engines": {
"node": ">=6.0"
}
}

View file

@ -0,0 +1,269 @@
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};

View file

@ -0,0 +1,274 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;

View file

@ -0,0 +1,10 @@
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

View file

@ -0,0 +1,263 @@
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.format(...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};

View file

@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Vercel, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,38 @@
{
"name": "ms",
"version": "2.1.3",
"description": "Tiny millisecond conversion utility",
"repository": "vercel/ms",
"main": "./index",
"files": [
"index.js"
],
"scripts": {
"precommit": "lint-staged",
"lint": "eslint lib/* bin/*",
"test": "mocha tests.js"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"license": "MIT",
"devDependencies": {
"eslint": "4.18.2",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1",
"prettier": "2.0.5"
}
}

View file

@ -0,0 +1,59 @@
# ms
![CI](https://github.com/vercel/ms/workflows/CI/badge.svg)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

74
VISUALIZACION/node_modules/@elastic/transport/package.json generated vendored Executable file
View file

@ -0,0 +1,74 @@
{
"name": "@elastic/transport",
"version": "8.3.2",
"description": "Transport classes and utilities shared among Node.js Elastic client libraries",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"test": "npm run build && npm run lint && tap test/{unit,acceptance}/{*,**/*}.test.ts",
"test:unit": "npm run build && tap test/unit/{*,**/*}.test.ts",
"test:acceptance": "npm run build && tap test/acceptance/*.test.ts",
"test:coverage-100": "npm run build && tap test/{unit,acceptance}/{*,**/*}.test.ts --coverage --100",
"test:coverage-report": "npm run build && tap test/{unit,acceptance}/{*,**/*}.test.ts --coverage && nyc report --reporter=text-lcov > coverage.lcov",
"test:coverage-ui": "npm run build && tap test/{unit,acceptance}/{*,**/*}.test.ts --coverage --coverage-report=html",
"lint": "ts-standard src",
"lint:fix": "ts-standard --fix src",
"license-checker": "license-checker --production --onlyAllow='MIT;Apache-2.0;Apache1.1;ISC;BSD-3-Clause;BSD-2-Clause;0BSD'",
"prebuild": "npm run clean-build && npm run lint",
"build": "tsc",
"clean-build": "rimraf ./lib && mkdir lib",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/elastic/elastic-transport-js.git"
},
"keywords": [],
"author": {
"name": "Tomas Della Vedova",
"company": "Elastic BV"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/elastic/elastic-transport-js/issues"
},
"homepage": "https://github.com/elastic/elastic-transport-js#readme",
"engines": {
"node": ">=14"
},
"devDependencies": {
"@sinonjs/fake-timers": "github:sinonjs/fake-timers#0bfffc1",
"@types/debug": "^4.1.7",
"@types/ms": "^0.7.31",
"@types/node": "^17.0.31",
"@types/sinonjs__fake-timers": "^8.1.2",
"@types/stoppable": "^1.1.1",
"@types/tap": "^15.0.7",
"into-stream": "^6.0.0",
"license-checker": "^25.0.1",
"node-abort-controller": "^3.0.1",
"proxy": "^1.0.2",
"rimraf": "^3.0.2",
"stoppable": "^1.1.0",
"tap": "^16.1.0",
"ts-node": "^10.7.0",
"ts-standard": "^11.0.0",
"typescript": "^4.6.4",
"workq": "^3.0.0"
},
"dependencies": {
"debug": "^4.3.4",
"hpagent": "^1.0.0",
"ms": "^2.1.3",
"secure-json-parse": "^2.4.0",
"tslib": "^2.4.0",
"undici": "^5.22.1"
},
"tap": {
"ts": true,
"jsx": false,
"flow": false,
"coverage": false,
"check-coverage": false
}
}

37
VISUALIZACION/node_modules/@elastic/transport/tsconfig.json generated vendored Executable file
View file

@ -0,0 +1,37 @@
{
"compilerOptions": {
"target": "es2019",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"pretty": true,
"noEmitOnError": true,
"strict": true,
"resolveJsonModule": true,
"removeComments": false,
"sourceMap": true,
"newLine": "lf",
"noUnusedLocals": true,
"noFallthroughCasesInSwitch": true,
"useDefineForClassFields": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": false,
"esModuleInterop": true,
"isolatedModules": true,
"importHelpers": true,
"outDir": "lib",
"lib": [
"esnext"
]
},
"formatCodeOptions": {
"identSize": 2,
"tabSize": 2
},
"exclude": [
"node_modules"
],
"include": [
"./src/**/*.ts"
]
}