{"version":3,"sources":["../../core/src/results/chunkCombiner.ts","../../core/src/results/chunksToLines.ts","../../core/src/results/chunksToLinesIterable.ts","../../core/src/results/LineSplitter.ts","../../core/src/results/FluxTableColumn.ts","../../core/src/errors.ts","../../core/src/results/FluxTableMetaData.ts","../../core/src/results/linesToTables.ts","../../core/src/results/linesToRowsIterable.ts","../../core/src/results/stringToLines.ts","../../core/src/observable/symbol.ts","../../core/src/results/ObservableQuery.ts","../../core/src/options.ts","../../core/src/util/escape.ts","../../core/src/util/currentTime.ts","../../core/src/util/logger.ts","../../core/src/query/flux.ts","../../core/src/Point.ts","../../core/src/impl/retryStrategy.ts","../../core/src/impl/RetryBuffer.ts","../../core/src/util/utf8Length.ts","../../core/src/impl/WriteApiImpl.ts","../../core/src/impl/completeCommunicationObserver.ts","../../core/src/impl/browser/FetchTransport.ts","../../core/src/impl/QueryApiImpl.ts","../../core/src/results/AnnotatedCSVResponseImpl.ts","../../core/src/InfluxDB.ts","../src/csvToTable.ts","../src/queryTable.ts"],"sourcesContent":["/**\n * ChunkCombiner is a simplified platform-neutral manipulation of Uint8arrays\n * that allows to process text data on the fly. The implementation can be optimized\n * for the target platform (node vs browser).\n */\nexport interface ChunkCombiner {\n  /**\n   * Concatenates first and second chunk.\n   * @param first - first chunk\n   * @param second - second chunk\n   * @returns first + second\n   */\n  concat(first: Uint8Array, second: Uint8Array): Uint8Array\n\n  /**\n   * Converts chunk into a string.\n   * @param chunk - chunk\n   * @param start - start index\n   * @param end - end index\n   * @returns string representation of chunk slice\n   */\n  toUtf8String(chunk: Uint8Array, start: number, end: number): string\n\n  /**\n   * Creates a new chunk from the supplied chunk.\n   * @param chunk - chunk to copy\n   * @param start - start index\n   * @param end - end index\n   * @returns a copy of a chunk slice\n   */\n  copy(chunk: Uint8Array, start: number, end: number): Uint8Array\n}\n\n// TextDecoder is available since node v8.3.0 and in all modern browsers\ndeclare class TextDecoder {\n  constructor(encoding: string)\n  decode(chunk: Uint8Array): string\n}\n\n/**\n * Creates a chunk combiner instance that uses UTF-8\n * TextDecoder to decode Uint8Arrays into strings.\n */\nexport function createTextDecoderCombiner(): ChunkCombiner {\n  const decoder = new TextDecoder('utf-8')\n  return {\n    concat(first: Uint8Array, second: Uint8Array): Uint8Array {\n      const retVal = new Uint8Array(first.length + second.length)\n      retVal.set(first)\n      retVal.set(second, first.length)\n      return retVal\n    },\n    copy(chunk: Uint8Array, start: number, end: number): Uint8Array {\n      const retVal = new Uint8Array(end - start)\n      retVal.set(chunk.subarray(start, end))\n      return retVal\n    },\n    toUtf8String(chunk: Uint8Array, start: number, end: number): string {\n      return decoder.decode(chunk.subarray(start, end))\n    },\n  }\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\nimport {CommunicationObserver} from './CommunicationObserver'\nimport {Cancellable} from './Cancellable'\n\n/**\n * ChunksToLines is a transformation that accepts Uint8Array instances\n * and emmits strings representing CSV lines.\n * @param target - target to emmit CSV lines to\n * @param chunkCombiner - chunk combiner\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function chunksToLines(\n  target: CommunicationObserver<string>,\n  chunkCombiner?: ChunkCombiner\n): CommunicationObserver<Uint8Array> {\n  const chunks = chunkCombiner ?? createTextDecoderCombiner()\n  let previous: Uint8Array | undefined\n  let finished = false\n  let quoted = false\n  let paused = false\n  let resumeChunks: (() => void) | undefined\n\n  function bufferReceived(chunk: Uint8Array): void {\n    let index: number\n    let start = 0\n    if (previous) {\n      // inspect the whole remaining data upon empty chunk\n      // empty chunk signalizes to restart of receiving\n      index = chunk.length === 0 ? 0 : (previous as Uint8Array).length\n      chunk = chunks.concat(previous, chunk)\n    } else {\n      index = 0\n    }\n    while (index < chunk.length) {\n      const c = chunk[index]\n      if (c === 10) {\n        if (!quoted) {\n          /* do not emit CR+LR or LF line ending */\n          const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n          // do not emmit more lines if the processing is already finished\n          if (finished) {\n            return\n          }\n          paused = target.next(chunks.toUtf8String(chunk, start, end)) === false\n          start = index + 1\n          if (paused) {\n            break\n          }\n        }\n      } else if (c === 34 /* \" */) {\n        quoted = !quoted\n      }\n      index++\n    }\n    if (start < chunk.length) {\n      previous = chunks.copy(chunk, start, chunk.length)\n    } else {\n      previous = undefined\n    }\n    if (paused) {\n      if (target.useResume) {\n        target.useResume(() => {\n          paused = false\n          bufferReceived(new Uint8Array(0))\n        })\n        return\n      }\n      retVal.error(new Error('Unable to pause, useResume is not configured!'))\n      paused = false // consume remaining data\n    }\n    if (resumeChunks) {\n      resumeChunks()\n      resumeChunks = undefined\n    }\n  }\n\n  const retVal: CommunicationObserver<Uint8Array> = {\n    next(chunk: Uint8Array): boolean {\n      if (!finished) {\n        try {\n          bufferReceived(chunk)\n          return !paused\n        } catch (e) {\n          this.error(e as Error)\n        }\n      }\n      return true\n    },\n    error(error: Error): void {\n      if (!finished) {\n        finished = true\n        target.error(error)\n      }\n    },\n    complete(): void {\n      if (!finished) {\n        if (previous) {\n          target.next(chunks.toUtf8String(previous, 0, previous.length))\n        }\n        finished = true\n        target.complete()\n      }\n    },\n  }\n  if (target.useCancellable) {\n    retVal.useCancellable = (cancellable: Cancellable) => {\n      target.useCancellable &&\n        target.useCancellable({\n          cancel(): void {\n            cancellable.cancel()\n            previous = undefined // do not emit more lines\n            retVal.complete()\n          },\n          isCancelled(): boolean {\n            return cancellable.isCancelled()\n          },\n        })\n    }\n  }\n  if (target.useResume) {\n    retVal.useResume = (x: () => void) => {\n      resumeChunks = x\n    }\n  }\n\n  return retVal\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\n\n/**\n * ChunksToLinesIterable is a transformation that accepts\n * an iterable of Uint8Array instances and returns iterable of lines.\n * @param source - iterable of transport buffers\n * @param chunkCombiner - chunk combiner\n * @returns iterable of lines\n */\nexport async function* chunksToLinesIterable(\n  source: AsyncIterable<Uint8Array>,\n  chunkCombiner?: ChunkCombiner\n): AsyncIterableIterator<string> {\n  const chunks = chunkCombiner ?? createTextDecoderCombiner()\n  let previous: Uint8Array | undefined\n  let quoted = false\n\n  for await (let chunk of source) {\n    let index: number\n    let start = 0\n    if (previous) {\n      index = previous.length\n      chunk = chunks.concat(previous, chunk)\n    } else {\n      index = 0\n    }\n    while (index < chunk.length) {\n      const c = chunk[index]\n      if (c === 10) {\n        if (!quoted) {\n          /* do not emit CR+LR or LF line ending */\n          const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n          yield chunks.toUtf8String(chunk, start, end)\n          start = index + 1\n        }\n      } else if (c === 34 /* \" */) {\n        quoted = !quoted\n      }\n      index++\n    }\n    if (start < chunk.length) {\n      previous = chunks.copy(chunk, start, chunk.length)\n    } else {\n      previous = undefined\n    }\n  }\n  if (previous) {\n    yield chunks.toUtf8String(previous, 0, previous.length)\n  }\n}\n","/**\n * Optimized tokenizer of a single CSV line.\n */\nexport class LineSplitter {\n  /** returned value when reused  */\n  reusedValues: string[]\n  /** last length of elements in */\n  lastSplitLength: number\n  private _reuse = false\n\n  /**\n   * Reuse returned array between consecutive calls.\n   */\n  get reuse(): boolean {\n    return this._reuse\n  }\n  set reuse(val: boolean) {\n    if (val && !this.reusedValues) {\n      this.reusedValues = new Array(10)\n    }\n    this._reuse = val\n  }\n\n  /**\n   * Sets the reuse flag and returns this.\n   */\n  withReuse(): LineSplitter {\n    this.reuse = true\n    return this\n  }\n\n  /**\n   * Splits the supplied line to elements that are separated by\n   * comma with values possibly escaped within double quotes (\"value\")\n   * @param line - line\n   * @returns array of splitted parts\n   */\n  splitLine(line: string | undefined | null): string[] {\n    if (line === null || line === undefined) {\n      this.lastSplitLength = 0\n      return []\n    }\n    let quoteCount = 0\n    let startIndex = 0\n    const values = this._reuse ? this.reusedValues : []\n    let count = 0\n    for (let i = 0; i < line.length; i++) {\n      const c = line[i]\n      if (c === ',') {\n        if (quoteCount % 2 === 0) {\n          const val = this.getValue(line, startIndex, i, quoteCount)\n          if (this._reuse) {\n            values[count++] = val\n          } else {\n            values.push(val)\n          }\n          startIndex = i + 1\n          quoteCount = 0\n        }\n      } else if (c === '\"') {\n        quoteCount++\n      }\n    }\n    const val = this.getValue(line, startIndex, line.length, quoteCount)\n    if (this._reuse) {\n      values[count] = val\n      this.lastSplitLength = count + 1\n    } else {\n      values.push(val)\n      this.lastSplitLength = values.length\n    }\n\n    return values\n  }\n\n  private getValue(\n    line: string,\n    start: number,\n    end: number,\n    quoteCount: number\n  ): string {\n    if (start === line.length) {\n      return ''\n    } else if (quoteCount === 0) {\n      return line.substring(start, end)\n    } else if (quoteCount === 2) {\n      return line.substring(start + 1, end - 1)\n    } else {\n      // quoteCount >= 4\n      return line.substring(start + 1, end - 1).replace(/\"\"/gi, '\"')\n    }\n  }\n}\n","/**\n * Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport type ColumnType =\n  | 'boolean'\n  | 'unsignedLong'\n  | 'long'\n  | 'double'\n  | 'string'\n  | 'base64Binary'\n  | 'dateTime:RFC3339'\n  | 'duration'\n  | string\n\n/**\n * FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column.\n */\nexport interface FluxTableColumn {\n  /**\n   * Label (e.g., \"_start\", \"_stop\", \"_time\").\n   */\n  label: string\n\n  /**\n   * The data type of column (e.g., \"string\", \"long\", \"dateTime:RFC3339\").\n   */\n  dataType: ColumnType\n\n  /**\n   * Boolean flag indicating if the column is a part of the table's group key.\n   */\n  group: boolean\n\n  /**\n   * Default value to be used for rows whose string value is an empty string.\n   */\n  defaultValue: string\n\n  /**\n   * Index of this column in a row array.\n   */\n  index: number\n\n  /**\n   * Get returns a JavaScript object of this column in the supplied result row, using default deserializers.\n   * @param row - a data row\n   * @returns column value\n   */\n  get: (row: string[]) => any\n}\n\nconst identity = (x: string): any => x\n\n/**\n * A dictionary of serializers of particular types returned by a flux query.\n * See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport const typeSerializers: Record<ColumnType, (val: string) => any> = {\n  boolean: (x: string): any => (x === '' ? null : x === 'true'),\n  unsignedLong: (x: string): any => (x === '' ? null : +x),\n  long: (x: string): any => (x === '' ? null : +x),\n  double(x: string): any {\n    switch (x) {\n      case '':\n        return null\n      case '+Inf':\n        return Number.POSITIVE_INFINITY\n      case '-Inf':\n        return Number.NEGATIVE_INFINITY\n      default:\n        return +x\n    }\n  },\n  string: identity,\n  base64Binary: identity,\n  duration: (x: string): any => (x === '' ? null : x),\n  'dateTime:RFC3339': (x: string): any => (x === '' ? null : x),\n}\n\n/**\n * FluxTableColumn implementation.\n */\nclass FluxTableColumnImpl implements FluxTableColumn {\n  label: string\n  dataType: ColumnType\n  group: boolean\n  defaultValue: string\n  index: number\n  public get(row: string[]): any {\n    let val = row[this.index]\n    if ((val === '' || val === undefined) && this.defaultValue) {\n      val = this.defaultValue\n    }\n    return (typeSerializers[this.dataType] ?? identity)(val)\n  }\n}\nexport const UNKNOWN_COLUMN: FluxTableColumn = Object.freeze({\n  label: '',\n  dataType: '',\n  group: false,\n  defaultValue: '',\n  index: Number.MAX_SAFE_INTEGER,\n  get: () => undefined,\n})\n\n/**\n * Creates a new flux table column.\n * @returns column instance\n */\nexport function newFluxTableColumn(): FluxTableColumn {\n  return new FluxTableColumnImpl()\n}\n\n/**\n * Creates a flux table column from a partial FluxTableColumn.\n * @param object - source object\n * @returns column instance\n */\nexport function createFluxTableColumn(\n  object: Partial<FluxTableColumn>\n): FluxTableColumn {\n  const retVal = new FluxTableColumnImpl()\n  retVal.label = String(object.label)\n  retVal.dataType = object.dataType as ColumnType\n  retVal.group = Boolean(object.group)\n  retVal.defaultValue = object.defaultValue ?? ''\n  retVal.index = object.index ?? 0\n  return retVal\n}\n","import {HttpHeaders} from './results'\n\n/**\n * Strategy for calculating retry delays.\n */\nexport interface RetryDelayStrategy {\n  /**\n   * Returns delay for a next retry\n   * @param error - reason for retrying\n   * @param failedAttempts - a count of already failed attempts, 1 being the first\n   * @returns milliseconds to wait before retrying\n   */\n  nextDelay(error?: Error, failedAttempts?: number): number\n  /** Implementation should reset its state, this is mandatory to call upon success.  */\n  success(): void\n}\n\n/**\n * Interface for errors to inform that an associated operation can be retried.\n */\nexport interface RetriableDecision {\n  /**\n   * Informs whether this can be retried.\n   */\n  canRetry(): boolean\n  /**\n   * Get the delay in milliseconds to retry the action.\n   * @returns 0 to let the implementation decide, miliseconds delay otherwise\n   */\n  retryAfter(): number\n}\n\nconst retriableStatusCodes = [404, 408, 425, 429, 500, 502, 503, 504]\n/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */\nexport function isStatusCodeRetriable(statusCode: number): boolean {\n  return retriableStatusCodes.includes(statusCode)\n}\n\n/** IllegalArgumentError is thrown when illegal argument is supplied. */\nexport class IllegalArgumentError extends Error {\n  /* istanbul ignore next */\n  constructor(message: string) {\n    super(message)\n    this.name = 'IllegalArgumentError'\n    Object.setPrototypeOf(this, IllegalArgumentError.prototype)\n  }\n}\n\n/**\n * A general HTTP error.\n */\nexport class HttpError extends Error implements RetriableDecision {\n  private _retryAfter: number\n  /** application error code, when available */\n  public code: string | undefined\n  /** json error response */\n  public json: any\n\n  public headers?: HttpHeaders | undefined\n\n  /* istanbul ignore next because of super() not being covered*/\n  constructor(\n    readonly statusCode: number,\n    readonly statusMessage: string | undefined,\n    readonly body?: string,\n    retryAfter?: string | undefined | null,\n    readonly contentType?: string | undefined | null,\n    message?: string,\n    headers?: HttpHeaders | undefined\n  ) {\n    super()\n    Object.setPrototypeOf(this, HttpError.prototype)\n\n    this.headers = headers\n\n    if (message) {\n      this.message = message\n    } else if (body) {\n      if (contentType?.startsWith('application/json')) {\n        try {\n          this.json = JSON.parse(body)\n          this.message = this.json.message\n          this.code = this.json.code\n        } catch (e) {\n          // silently ignore, body string is still available\n        }\n      }\n      if (!this.message) {\n        this.message = `${statusCode} ${statusMessage} : ${body}`\n      }\n    } else {\n      this.message = `${statusCode} ${statusMessage}`\n    }\n    this.name = 'HttpError'\n    this.setRetryAfter(retryAfter)\n  }\n\n  private setRetryAfter(retryAfter?: string | undefined | null): void {\n    if (typeof retryAfter === 'string') {\n      // try to parse the supplied number as milliseconds\n      if (/^[0-9]+$/.test(retryAfter)) {\n        this._retryAfter = parseInt(retryAfter)\n      } else {\n        this._retryAfter = 0\n      }\n    } else {\n      this._retryAfter = 0\n    }\n  }\n\n  canRetry(): boolean {\n    return isStatusCodeRetriable(this.statusCode)\n  }\n  retryAfter(): number {\n    return this._retryAfter\n  }\n}\n\n//see https://nodejs.org/api/errors.html\nconst RETRY_CODES = [\n  'ECONNRESET',\n  'ENOTFOUND',\n  'ESOCKETTIMEDOUT',\n  'ETIMEDOUT',\n  'ECONNREFUSED',\n  'EHOSTUNREACH',\n  'EPIPE',\n]\n\n/**\n * Tests the error in order to know if an HTTP call can be retried.\n * @param error - error to test\n * @returns true for a retriable error\n */\nexport function canRetryHttpCall(error: any): boolean {\n  if (!error) {\n    return false\n  } else if (typeof (error as any).canRetry === 'function') {\n    return !!((error as any).canRetry as () => boolean)()\n  } else if ((error as any).code && RETRY_CODES.includes((error as any).code)) {\n    return true\n  }\n  return false\n}\n\n/**\n * Gets retry delay from the supplied error, possibly using random number up to retryJitter.\n */\nexport function getRetryDelay(error?: Error, retryJitter?: number): number {\n  if (!error) {\n    return 0\n  } else {\n    let retVal\n    if (typeof (error as any).retryAfter === 'function') {\n      return ((error as any).retryAfter as () => number)()\n    } else {\n      retVal = 0\n    }\n    if (retryJitter && retryJitter > 0) {\n      return retVal + Math.round(Math.random() * retryJitter)\n    } else {\n      return retVal\n    }\n  }\n}\n\n/** RequestTimedOutError indicates request timeout in the communication with the server */\nexport class RequestTimedOutError extends Error implements RetriableDecision {\n  /* istanbul ignore next because of super() not being covered */\n  constructor() {\n    super()\n    Object.setPrototypeOf(this, RequestTimedOutError.prototype)\n    this.name = 'RequestTimedOutError'\n    this.message = 'Request timed out'\n  }\n  canRetry(): boolean {\n    return true\n  }\n  retryAfter(): number {\n    return 0\n  }\n}\n\n/** AbortError indicates that the communication with the server was aborted */\nexport class AbortError extends Error implements RetriableDecision {\n  /* istanbul ignore next because of super() not being covered */\n  constructor() {\n    super()\n    this.name = 'AbortError'\n    Object.setPrototypeOf(this, AbortError.prototype)\n    this.message = 'Response aborted'\n  }\n  canRetry(): boolean {\n    return true\n  }\n  retryAfter(): number {\n    return 0\n  }\n}\n","import {\n  FluxTableColumn,\n  UNKNOWN_COLUMN,\n  typeSerializers,\n} from './FluxTableColumn'\nimport {IllegalArgumentError} from '../errors'\n\n/**\n * serializeDateTimeAsDate changes type serializers to return JavaScript Date instances\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsDate(): void {\n  typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n    x === '' ? null : new Date(Date.parse(x))\n}\n/**\n * serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsNumber(): void {\n  typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n    x === '' ? null : Date.parse(x)\n}\n/**\n * serializeDateTimeAsString changes type serializers to return string values\n * for `dateTime:RFC3339` query result data type.  Empty value is converted to null.\n */\nexport function serializeDateTimeAsString(): void {\n  typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n    x === '' ? null : x\n}\n\n/**\n * Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}.\n */\nexport interface FluxTableMetaData {\n  /**\n   * Table columns.\n   */\n  columns: Array<FluxTableColumn>\n\n  /**\n   * Gets columns by name\n   * @param label - column label\n   * @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false\n   * @returns table column\n   * @throws IllegalArgumentError if column is not found\n   **/\n  column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn\n\n  /**\n   * Creates an object out of the supplied row with the help of column descriptors.\n   * @param row - a row with data for each column\n   */\n  toObject(row: string[]): {[key: string]: any}\n\n  /**\n   * Gets column values out of the supplied row.\n   * @param row - a row with data for each column\n   * @param column - column name\n   * @returns column value, undefined for unknown column\n   */\n  get(row: string[], column: string): any\n}\n\n/**\n * FluxTableMetaData Implementation.\n */\nclass FluxTableMetaDataImpl implements FluxTableMetaData {\n  columns: Array<FluxTableColumn>\n  constructor(columns: FluxTableColumn[]) {\n    columns.forEach((col, i) => (col.index = i))\n    this.columns = columns\n  }\n  column(label: string, errorOnMissingColumn = true): FluxTableColumn {\n    for (let i = 0; i < this.columns.length; i++) {\n      const col = this.columns[i]\n      if (col.label === label) return col\n    }\n    if (errorOnMissingColumn) {\n      throw new IllegalArgumentError(`Column ${label} not found!`)\n    }\n    return UNKNOWN_COLUMN\n  }\n  toObject(row: string[]): {[key: string]: any} {\n    const acc: any = {}\n    for (let i = 0; i < this.columns.length && i < row.length; i++) {\n      const column = this.columns[i]\n      acc[column.label] = column.get(row)\n    }\n    return acc\n  }\n  get(row: string[], column: string): any {\n    return this.column(column, false).get(row)\n  }\n}\n\n/**\n * Created FluxTableMetaData from the columns supplied.\n * @param columns -  columns\n * @returns - instance\n */\nexport function createFluxTableMetaData(\n  columns: FluxTableColumn[]\n): FluxTableMetaData {\n  return new FluxTableMetaDataImpl(columns)\n}\n\n/** Wraps values and associated metadata of a query result row */\nexport interface Row {\n  values: string[]\n  tableMeta: FluxTableMetaData\n}\n","import {CommunicationObserver} from './CommunicationObserver'\nimport {LineSplitter} from './LineSplitter'\nimport {FluxResultObserver} from './FluxResultObserver'\nimport {\n  FluxTableColumn,\n  ColumnType,\n  newFluxTableColumn,\n} from './FluxTableColumn'\nimport {FluxTableMetaData, createFluxTableMetaData} from './FluxTableMetaData'\n\n/**\n * LinesToTables creates a transformation that accepts (flux) annotated CSV lines\n * and emits rows together with table metadata.\n */\nexport function linesToTables(\n  consumer: FluxResultObserver<string[]>\n): CommunicationObserver<string> {\n  const splitter = new LineSplitter().withReuse()\n  let columns: FluxTableColumn[] | undefined\n  let expectMeta = true\n  let firstColumnIndex = 0\n  let lastMeta: FluxTableMetaData\n  const retVal: CommunicationObserver<string> = {\n    error(error: Error): void {\n      consumer.error(error)\n    },\n    next(line: string): void | boolean {\n      if (line === '') {\n        expectMeta = true\n        columns = undefined\n      } else {\n        const values = splitter.splitLine(line)\n        const size = splitter.lastSplitLength\n        if (expectMeta) {\n          // create columns\n          if (!columns) {\n            columns = new Array(size)\n            for (let i = 0; i < size; i++) {\n              columns[i] = newFluxTableColumn()\n            }\n          }\n          if (!values[0].startsWith('#')) {\n            // fill in column names\n            if (values[0] === '') {\n              firstColumnIndex = 1\n              columns = columns.slice(1)\n            } else {\n              firstColumnIndex = 0\n            }\n            for (let i = firstColumnIndex; i < size; i++) {\n              columns[i - firstColumnIndex].label = values[i]\n            }\n            lastMeta = createFluxTableMetaData(columns)\n            expectMeta = false\n          } else if (values[0] === '#datatype') {\n            for (let i = 1; i < size; i++) {\n              columns[i].dataType = values[i] as ColumnType\n            }\n          } else if (values[0] === '#default') {\n            for (let i = 1; i < size; i++) {\n              columns[i].defaultValue = values[i]\n            }\n          } else if (values[0] === '#group') {\n            for (let i = 1; i < size; i++) {\n              columns[i].group = values[i][0] === 't'\n            }\n          }\n        } else {\n          return consumer.next(values.slice(firstColumnIndex, size), lastMeta)\n        }\n      }\n      return true\n    },\n    complete(): void {\n      consumer.complete()\n    },\n  }\n  if (consumer.useCancellable) {\n    retVal.useCancellable = consumer.useCancellable.bind(consumer)\n  }\n  if (consumer.useResume) {\n    retVal.useResume = consumer.useResume.bind(consumer)\n  }\n  return retVal\n}\n","import {LineSplitter} from './LineSplitter'\nimport {\n  FluxTableColumn,\n  ColumnType,\n  newFluxTableColumn,\n} from './FluxTableColumn'\nimport {\n  FluxTableMetaData,\n  createFluxTableMetaData,\n  Row,\n} from './FluxTableMetaData'\n\n/**\n * LinesToRowsIterable is a transformation that accepts\n * an iterable of flux annotated CSV lines and returns\n * an iterable of rows (row values and table metadata).\n */\nexport async function* linesToRowsIterable(\n  source: AsyncIterable<string>\n): AsyncIterableIterator<Row> {\n  const splitter = new LineSplitter().withReuse()\n  let columns: FluxTableColumn[] | undefined\n  let expectMeta = true\n  let firstColumnIndex = 0\n  let lastMeta: FluxTableMetaData | undefined = undefined\n  for await (const line of source) {\n    if (line === '') {\n      expectMeta = true\n      columns = undefined\n    } else {\n      const values = splitter.splitLine(line)\n      const size = splitter.lastSplitLength\n      if (expectMeta) {\n        // create columns\n        if (!columns) {\n          columns = new Array(size)\n          for (let i = 0; i < size; i++) {\n            columns[i] = newFluxTableColumn()\n          }\n        }\n        if (!values[0].startsWith('#')) {\n          // fill in column names\n          if (values[0] === '') {\n            firstColumnIndex = 1\n            columns = columns.slice(1)\n          } else {\n            firstColumnIndex = 0\n          }\n          for (let i = firstColumnIndex; i < size; i++) {\n            columns[i - firstColumnIndex].label = values[i]\n          }\n          lastMeta = createFluxTableMetaData(columns)\n          expectMeta = false\n        } else if (values[0] === '#datatype') {\n          for (let i = 1; i < size; i++) {\n            columns[i].dataType = values[i] as ColumnType\n          }\n        } else if (values[0] === '#default') {\n          for (let i = 1; i < size; i++) {\n            columns[i].defaultValue = values[i]\n          }\n        } else if (values[0] === '#group') {\n          for (let i = 1; i < size; i++) {\n            columns[i].group = values[i][0] === 't'\n          }\n        }\n      } else {\n        yield {\n          values: values.slice(firstColumnIndex, size),\n          tableMeta:\n            lastMeta as unknown as FluxTableMetaData /* never undefined */,\n        }\n      }\n    }\n  }\n}\n","import {CommunicationObserver} from './CommunicationObserver'\n\n/**\n * StringToLines is a transformation that emmits strings for each CSV\n * line in the supplied source string.\n * @param source - source string\n * @param target - target to emmit CSV lines to\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function stringToLines(\n  source: string,\n  target: CommunicationObserver<string>\n): void {\n  let quoted = false\n  let start = 0\n  let index = 0\n\n  while (index < source.length) {\n    const c = source.charCodeAt(index)\n    if (c === 10) {\n      if (!quoted) {\n        /* do not emit CR+LR or LF line ending */\n        const end =\n          index > 0 && source.charCodeAt(index - 1) === 13 ? index - 1 : index\n        // do not emmit more lines if the processing is already finished\n        target.next(source.substring(start, end))\n        start = index + 1\n      }\n    } else if (c === 34 /* \" */) {\n      quoted = !quoted\n    }\n    index++\n  }\n  if (start < index) {\n    target.next(source.substring(start, index))\n  }\n  target.complete()\n}\n","/* Observable interop typing. Taken from https://github.com/ReactiveX/rxjs */\n\n/* Note: This will add Symbol.observable globally for all TypeScript users */\ndeclare global {\n  interface SymbolConstructor {\n    readonly observable: symbol\n  }\n}\n\n/** Symbol.observable or a string \"\\@\\@observable\". Used for interop */\nexport const symbolObservable = (():\n  | typeof Symbol.observable\n  | '@@observable' =>\n  (typeof Symbol === 'function' && Symbol.observable) || '@@observable')()\n","import {\n  Observable,\n  Observer,\n  ObserverComplete,\n  ObserverError,\n  ObserverNext,\n  Subscription,\n  symbolObservable,\n} from '../observable'\nimport {CommunicationObserver} from '../results/CommunicationObserver'\nimport {Cancellable} from '../results/Cancellable'\n\n/** APIExecutor executes the API and passes its response to the supplied consumer */\nexport type APIExecutor = (consumer: CommunicationObserver<Uint8Array>) => void\n\ntype Decorator<T> = (observer: Observer<T>) => Observer<Uint8Array>\n\nclass QuerySubscription implements Subscription {\n  private cancellable?: Cancellable\n  private isClosed = false\n\n  public constructor(observer: Observer<Uint8Array>, executor: APIExecutor) {\n    try {\n      executor({\n        next: (value) => {\n          observer.next(value)\n        },\n        error: (e) => {\n          this.isClosed = true\n          observer.error(e)\n        },\n        complete: () => {\n          this.isClosed = true\n          observer.complete()\n        },\n        useCancellable: (c) => {\n          this.cancellable = c\n        },\n      })\n    } catch (e) {\n      this.isClosed = true\n      observer.error(e)\n    }\n  }\n\n  public get closed(): boolean {\n    return this.isClosed\n  }\n\n  public unsubscribe(): void {\n    this.cancellable?.cancel()\n    this.isClosed = true\n  }\n}\n\nfunction noop(): void {}\n\nfunction completeObserver<T>(observer: Partial<Observer<T>>): Observer<T> {\n  const {next, error, complete} = observer\n\n  return {\n    next: next ? next.bind(observer) : noop,\n    error: error ? error.bind(observer) : noop,\n    complete: complete ? complete.bind(observer) : noop,\n  }\n}\n\nexport default class ObservableQuery<T> implements Observable<T> {\n  public constructor(\n    private readonly executor: APIExecutor,\n    private readonly decorator: Decorator<T>\n  ) {}\n\n  public subscribe(\n    observerOrNext?: Partial<Observer<T>> | ObserverNext<T>,\n    error?: ObserverError,\n    complete?: ObserverComplete\n  ): Subscription {\n    const observer = completeObserver(\n      typeof observerOrNext !== 'object' || observerOrNext === null\n        ? {next: observerOrNext, error, complete}\n        : observerOrNext\n    )\n\n    return new QuerySubscription(this.decorator(observer), this.executor)\n  }\n\n  public [symbolObservable](): this {\n    return this\n  }\n\n  // this makes sure we satisfy the interface, while using a possibly polyfilled\n  // [symbolObservable] above for the actual implementation\n  public declare [Symbol.observable]: () => this\n}\n","import {Transport} from './transport'\nimport WriteApi from './WriteApi'\n\n/**\n * Option for the communication with InfluxDB server.\n */\nexport interface ConnectionOptions {\n  /** base URL */\n  url: string\n  /** authentication token */\n  token?: string\n  /**\n   * socket timeout, 10000 milliseconds by default in node.js\n   * @defaultValue 10000\n   */\n  timeout?: number\n  /**\n   * TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno.\n   * Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or\n   * {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to\n   * {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link  https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized }\n   * property can disable TLS server certificate verification. Additionally,\n   * {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified\n   * in order to follow redirects in node.js.\n   * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno.\n   * For example,\n   * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs.\n   */\n  transportOptions?: {[key: string]: any}\n  /**\n   * Default HTTP headers to send with every request.\n   */\n  headers?: Record<string, string>\n  /**\n   * Full HTTP web proxy URL including schema, for example http://your-proxy:8080.\n   */\n  proxyUrl?: string\n}\n\n/** default connection options */\nexport const DEFAULT_ConnectionOptions: Partial<ConnectionOptions> = {\n  timeout: 10000,\n}\n\n/**\n * Options that configure strategy for retrying failed requests.\n */\nexport interface RetryDelayStrategyOptions {\n  /** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */\n  retryJitter: number\n  /** minimum delay when retrying write (milliseconds) */\n  minRetryDelay: number\n  /** maximum delay when retrying write (milliseconds) */\n  maxRetryDelay: number\n  /** base for the exponential retry delay */\n  exponentialBase: number\n  /**\n   * randomRetry indicates whether the next retry delay is deterministic (false) or random (true).\n   * The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied\n   * by `exponentialBase` until it exceeds `maxRetryDelay`.\n   * When random is `true`, the next delay is computed as a random number between next retry attempt (upper)\n   * and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value.\n   */\n  randomRetry: boolean\n}\n\n/**\n * Options that configure strategy for retrying failed InfluxDB write operations.\n */\nexport interface WriteRetryOptions extends RetryDelayStrategyOptions {\n  /**\n   * WriteFailed is called to inform about write errors.\n   * @param this - the instance of the API that failed\n   * @param error - write error\n   * @param lines - failed lines\n   * @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1)\n   * @param expires - expiration time for the lines to be retried in millis since epoch\n   * @returns a Promise to force the API to use it as a result of the flush operation,\n   * void/undefined to continue with default retry mechanism\n   */\n  writeFailed(\n    this: WriteApi,\n    error: Error,\n    lines: Array<string>,\n    attempt: number,\n    expires: number\n  ): Promise<void> | void\n\n  /**\n   * WriteSuccess is informed about successfully written lines.\n   * @param this - the instance of the API in use\n   * @param lines - written lines\n   */\n  writeSuccess(this: WriteApi, lines: Array<string>): void\n\n  /**\n   * WriteRetrySkipped is informed about lines that were removed from the retry buffer\n   * to keep the size of the retry buffer under the configured limit (maxBufferLines).\n   * @param entry - lines that were skipped\n   */\n  writeRetrySkipped(entry: {lines: Array<string>; expires: number}): void\n\n  /** max count of retries after the first write fails */\n  maxRetries: number\n  /** max time (millis) that can be spent with retries */\n  maxRetryTime: number\n  /** the maximum size of retry-buffer (in lines) */\n  maxBufferLines: number\n}\n\n/**\n * Options used by {@link WriteApi} .\n */\nexport interface WriteOptions extends WriteRetryOptions {\n  /** max number of records/lines to send in a batch   */\n  batchSize: number\n  /** delay between data flushes in milliseconds, at most `batch size` records are sent during flush  */\n  flushInterval: number\n  /** default tags, unescaped */\n  defaultTags?: Record<string, string>\n  /** HTTP headers that will be sent with every write request */\n  headers?: {[key: string]: string}\n  /** When specified, write bodies larger than the threshold are gzipped  */\n  gzipThreshold?: number\n  /** max size of a batch in bytes */\n  maxBatchBytes: number\n  /** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */\n  consistency?: 'any' | 'one' | 'quorum' | 'all'\n}\n\n/** default RetryDelayStrategyOptions */\nexport const DEFAULT_RetryDelayStrategyOptions = {\n  retryJitter: 200,\n  minRetryDelay: 5000,\n  maxRetryDelay: 125000,\n  exponentialBase: 5,\n  randomRetry: true,\n}\n\n/** default writeOptions */\nexport const DEFAULT_WriteOptions: WriteOptions = {\n  batchSize: 1000,\n  maxBatchBytes: 50_000_000, // default max batch size in the cloud\n  flushInterval: 60000,\n  writeFailed: function () {},\n  writeSuccess: function () {},\n  writeRetrySkipped: function () {},\n  maxRetries: 5,\n  maxRetryTime: 180_000,\n  maxBufferLines: 32_000,\n  // a copy of DEFAULT_RetryDelayStrategyOptions, so that DEFAULT_WriteOptions could be tree-shaken\n  retryJitter: 200,\n  minRetryDelay: 5000,\n  maxRetryDelay: 125000,\n  exponentialBase: 2,\n  gzipThreshold: 1000,\n  randomRetry: true,\n}\n\n/**\n * Options used by {@link InfluxDB} .\n */\nexport interface ClientOptions extends ConnectionOptions {\n  /** supplies and overrides default writing options */\n  writeOptions?: Partial<WriteOptions>\n  /** specifies custom transport */\n  transport?: Transport\n}\n\n/**\n * Timestamp precision used in write operations.\n * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite }\n */\nexport type WritePrecisionType = 'ns' | 'us' | 'ms' | 's'\n","function createEscaper(\n  characters: string,\n  replacements: string[]\n): (value: string) => string {\n  return function (value: string): string {\n    let retVal = ''\n    let from = 0\n    let i = 0\n    while (i < value.length) {\n      const found = characters.indexOf(value[i])\n      if (found >= 0) {\n        retVal += value.substring(from, i)\n        retVal += replacements[found]\n        from = i + 1\n      }\n      i++\n    }\n    if (from == 0) {\n      return value\n    } else if (from < value.length) {\n      retVal += value.substring(from, value.length)\n    }\n    return retVal\n  }\n}\nfunction createQuotedEscaper(\n  characters: string,\n  replacements: string[]\n): (value: string) => string {\n  const escaper = createEscaper(characters, replacements)\n  return (value: string): string => '\"' + escaper(value) + '\"'\n}\n\n/**\n * Provides functions escape specific parts in InfluxDB line protocol.\n */\nexport const escape = {\n  /**\n   * Measurement escapes measurement names.\n   */\n  measurement: createEscaper(', \\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\n', '\\\\r', '\\\\t']),\n  /**\n   * Quoted escapes quoted values, such as database names.\n   */\n  quoted: createQuotedEscaper('\"\\\\', ['\\\\\"', '\\\\\\\\']),\n\n  /**\n   * TagEscaper escapes tag keys, tag values, and field keys.\n   */\n  tag: createEscaper(', =\\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\=', '\\\\n', '\\\\r', '\\\\t']),\n}\n","declare let process: any\nconst zeroPadding = '000000000'\nlet useHrTime = false\n\nexport function useProcessHrtime(use: boolean): boolean {\n  /* istanbul ignore else */\n  if (!process.env.BUILD_BROWSER) {\n    return (useHrTime = use && process && typeof process.hrtime === 'function')\n  } else {\n    return false\n  }\n}\nuseProcessHrtime(true) // preffer node\n\nlet startHrMillis: number | undefined = undefined\nlet startHrTime: [number, number] | undefined = undefined\nlet lastMillis = Date.now()\nlet stepsInMillis = 0\nfunction nanos(): string {\n  if (!process.env.BUILD_BROWSER && useHrTime) {\n    const hrTime = process.hrtime() as [number, number]\n    let millis = Date.now()\n    if (!startHrTime) {\n      startHrTime = hrTime\n      startHrMillis = millis\n    } else {\n      hrTime[0] = hrTime[0] - startHrTime[0]\n      hrTime[1] = hrTime[1] - startHrTime[1]\n      // istanbul ignore next \"cannot mock system clock, manually reviewed\"\n      if (hrTime[1] < 0) {\n        hrTime[0] -= 1\n        hrTime[1] += 1000_000_000\n      }\n      millis =\n        (startHrMillis as number) +\n        hrTime[0] * 1000 +\n        Math.floor(hrTime[1] / 1000_000)\n    }\n    const nanos = String(hrTime[1] % 1000_000)\n    return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n  } else {\n    const millis = Date.now()\n    if (millis !== lastMillis) {\n      lastMillis = millis\n      stepsInMillis = 0\n    } else {\n      stepsInMillis++\n    }\n    const nanos = String(stepsInMillis)\n    return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n  }\n}\n\nfunction micros(): string {\n  if (!process.env.BUILD_BROWSER && useHrTime) {\n    const hrTime = process.hrtime() as [number, number]\n    const micros = String(Math.trunc(hrTime[1] / 1000) % 1000)\n    return (\n      String(Date.now()) + zeroPadding.substr(0, 3 - micros.length) + micros\n    )\n  } else {\n    return String(Date.now()) + zeroPadding.substr(0, 3)\n  }\n}\nfunction millis(): string {\n  return String(Date.now())\n}\nfunction seconds(): string {\n  return String(Math.floor(Date.now() / 1000))\n}\n\n/**\n * Exposes functions that creates strings that represent a timestamp that\n * can be used in the line protocol. Micro and nano timestamps are emulated\n * depending on the js platform in use.\n */\nexport const currentTime = {\n  s: seconds as () => string,\n  ms: millis as () => string,\n  us: micros as () => string,\n  ns: nanos as () => string,\n  seconds: seconds as () => string,\n  millis: millis as () => string,\n  micros: micros as () => string,\n  nanos: nanos as () => string,\n}\n\n/**\n * dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions.\n */\nexport const dateToProtocolTimestamp = {\n  s: (d: Date): string => `${Math.floor(d.getTime() / 1000)}`,\n  ms: (d: Date): string => `${d.getTime()}`,\n  us: (d: Date): string => `${d.getTime()}000`,\n  ns: (d: Date): string => `${d.getTime()}000000`,\n}\n\n/**\n * convertTimeToNanos converts Point's timestamp to a string.\n * @param value - supported timestamp value\n * @returns line protocol value\n */\nexport function convertTimeToNanos(\n  value: string | number | Date | undefined\n): string | undefined {\n  if (value === undefined) {\n    return nanos()\n  } else if (typeof value === 'string') {\n    return value.length > 0 ? value : undefined\n  } else if (value instanceof Date) {\n    return `${value.getTime()}000000`\n  } else if (typeof value === 'number') {\n    return String(Math.floor(value))\n  } else {\n    return String(value)\n  }\n}\n","/**\n * Logging interface.\n */\nexport interface Logger {\n  error(message: string, err?: any): void\n  warn(message: string, err?: any): void\n}\n\n/**\n * Logger that logs to console.out\n */\nexport const consoleLogger: Logger = {\n  error(message, error) {\n    // eslint-disable-next-line no-console\n    console.error('ERROR: ' + message, error ? error : '')\n  },\n  warn(message, error) {\n    // eslint-disable-next-line no-console\n    console.warn('WARN: ' + message, error ? error : '')\n  },\n}\nlet provider: Logger = consoleLogger\n\nexport const Log: Logger = {\n  error(message, error) {\n    provider.error(message, error)\n  },\n  warn(message, error) {\n    provider.warn(message, error)\n  },\n}\n\n/**\n * Sets custom logger.\n * @param logger - logger to use\n * @returns previous logger\n */\nexport function setLogger(logger: Logger): Logger {\n  const previous = provider\n  provider = logger\n  return previous\n}\n","/** Property that offers a function that returns flux-sanitized value of an object.  */\nexport const FLUX_VALUE = Symbol('FLUX_VALUE')\n\n/**\n * A flux parameter can print its (sanitized) flux value.\n */\nexport interface FluxParameterLike {\n  [FLUX_VALUE](): string\n}\n\n/**\n * Represents a parameterized query.\n */\nexport interface ParameterizedQuery {\n  /**\n   * Returns flux query with sanitized parameters.\n   */\n  toString(): string\n}\n\nclass FluxParameter implements FluxParameterLike, ParameterizedQuery {\n  constructor(private fluxValue: string) {}\n  toString(): string {\n    return this.fluxValue\n  }\n  [FLUX_VALUE](): string {\n    return this.fluxValue\n  }\n}\n\n/**\n * Checks if the supplied object is FluxParameterLike\n * @param value - any value\n * @returns true if it is\n */\nfunction isFluxParameterLike(value: any): boolean {\n  return typeof value === 'object' && typeof value[FLUX_VALUE] === 'function'\n}\n\n/**\n * Escapes content of the supplied string so it can be wrapped into double qoutes\n * to become a [flux string literal](https://docs.influxdata.com/flux/latest/spec/lexical-elements/#string-literals).\n * @param value - string value\n * @returns sanitized string\n */\nfunction sanitizeString(value: any): string {\n  if (value === null || value === undefined) return ''\n  value = value.toString()\n  let retVal: any = undefined\n  let i = 0\n  function prepareRetVal(): void {\n    if (retVal === undefined) {\n      retVal = value.substring(0, i)\n    }\n  }\n  for (; i < value.length; i++) {\n    const c = value.charAt(i)\n    switch (c) {\n      case '\\r':\n        prepareRetVal()\n        retVal += '\\\\r'\n        break\n      case '\\n':\n        prepareRetVal()\n        retVal += '\\\\n'\n        break\n      case '\\t':\n        prepareRetVal()\n        retVal += '\\\\t'\n        break\n      case '\"':\n      case '\\\\':\n        prepareRetVal()\n        retVal = retVal + '\\\\' + c\n        break\n      case '$':\n        // escape ${\n        if (i + 1 < value.length && value.charAt(i + 1) === '{') {\n          prepareRetVal()\n          i++\n          retVal += '\\\\${'\n          break\n        }\n        // append $\n        if (retVal != undefined) {\n          retVal += c\n        }\n        break\n      default:\n        if (retVal != undefined) {\n          retVal += c\n        }\n    }\n  }\n  if (retVal !== undefined) {\n    return retVal\n  }\n  return value\n}\n\n/**\n * Creates a flux string literal.\n */\nexport function fluxString(value: any): FluxParameterLike {\n  return new FluxParameter(`\"${sanitizeString(value)}\"`)\n}\n\n/**\n * Sanitizes float value to avoid injections.\n * @param value - InfluxDB float literal\n * @returns sanitized float value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeFloat(value: any): string {\n  const val = Number(value)\n  if (!isFinite(val)) {\n    if (typeof value === 'number') {\n      return `float(v: \"${val}\")`\n    }\n    throw new Error(`not a flux float: ${value}`)\n  }\n  // try to return a flux float literal if possible\n  // https://docs.influxdata.com/flux/latest/data-types/basic/float/#float-syntax\n  const strVal = val.toString()\n  let hasDot = false\n  for (const c of strVal) {\n    if ((c >= '0' && c <= '9') || c == '-') continue\n    if (c === '.') {\n      hasDot = true\n      continue\n    }\n    return `float(v: \"${strVal}\")`\n  }\n  return hasDot ? strVal : strVal + '.0'\n}\n/**\n * Creates a flux float literal.\n */\nexport function fluxFloat(value: any): FluxParameterLike {\n  return new FluxParameter(sanitizeFloat(value))\n}\n\n/**\n * Sanitizes integer value to avoid injections.\n * @param value - InfluxDB integer literal\n * @returns sanitized integer value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeInteger(value: any): string {\n  // https://docs.influxdata.com/flux/latest/data-types/basic/int/\n  // Min value: -9223372036854775808\n  // Max value: 9223372036854775807\n  // \"9223372036854775807\".length === 19\n  const strVal = String(value)\n  const negative = strVal.startsWith('-')\n  const val = negative ? strVal.substring(1) : strVal\n  if (val.length === 0 || val.length > 19) {\n    throw new Error(`not a flux integer: ${strVal}`)\n  }\n  for (const c of val) {\n    if (c < '0' || c > '9') throw new Error(`not a flux integer: ${strVal}`)\n  }\n  if (val.length === 19) {\n    if (negative && val > '9223372036854775808') {\n      throw new Error(`flux integer out of bounds: ${strVal}`)\n    }\n    if (!negative && val > '9223372036854775807') {\n      throw new Error(`flux integer out of bounds: ${strVal}`)\n    }\n  }\n  return strVal\n}\n\n/**\n * Creates a flux integer literal.\n */\nexport function fluxInteger(value: any): FluxParameterLike {\n  return new FluxParameter(sanitizeInteger(value))\n}\n\nfunction sanitizeDateTime(value: any): string {\n  return `time(v: \"${sanitizeString(value)}\")`\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDateTime(value: any): FluxParameterLike {\n  return new FluxParameter(sanitizeDateTime(value))\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDuration(value: any): FluxParameterLike {\n  return new FluxParameter(`duration(v: \"${sanitizeString(value)}\")`)\n}\n\nfunction sanitizeRegExp(value: any): string {\n  if (value instanceof RegExp) {\n    return value.toString()\n  }\n  return new RegExp(value).toString()\n}\n\n/**\n * Creates flux regexp literal out of a regular expression. See\n * https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax\n * for details.\n */\nexport function fluxRegExp(value: any): FluxParameterLike {\n  // let the server decide if a regexp can be parsed\n  return new FluxParameter(sanitizeRegExp(value))\n}\n\n/**\n * Creates flux boolean literal.\n */\nexport function fluxBool(value: any): FluxParameterLike {\n  if (value === 'true' || value === 'false') {\n    return new FluxParameter(value)\n  }\n  return new FluxParameter((!!value).toString())\n}\n\n/**\n * Assumes that the supplied value is flux expression or literal that does not need sanitizing.\n *\n * @param value - any value\n * @returns the supplied value as-is\n */\nexport function fluxExpression(value: any): FluxParameterLike {\n  return new FluxParameter(String(value))\n}\n\n/**\n * Escapes content of the supplied parameter so that it can be safely embedded into flux query.\n * @param value - parameter value\n * @returns sanitized flux value or an empty string if it cannot be converted\n */\nexport function toFluxValue(value: any): string {\n  if (value === undefined) {\n    return ''\n  } else if (value === null) {\n    return 'null'\n  } else if (typeof value === 'boolean') {\n    return value.toString()\n  } else if (typeof value === 'string') {\n    return `\"${sanitizeString(value)}\"`\n  } else if (typeof value === 'number') {\n    if (Number.isSafeInteger(value)) {\n      return sanitizeInteger(value)\n    }\n    return sanitizeFloat(value)\n  } else if (typeof value === 'object') {\n    if (typeof value[FLUX_VALUE] === 'function') {\n      return value[FLUX_VALUE]()\n    } else if (value instanceof Date) {\n      return value.toISOString()\n    } else if (value instanceof RegExp) {\n      return sanitizeRegExp(value)\n    } else if (Array.isArray(value)) {\n      return `[${value.map(toFluxValue).join(',')}]`\n    }\n  } else if (typeof value === 'bigint') {\n    return `${value}.0`\n  }\n  // use toString value for unrecognized object, symbol\n  return toFluxValue(value.toString())\n}\n\n/**\n * Flux is a tagged template that sanitizes supplied parameters\n * to avoid injection attacks in flux.\n */\nexport function flux(\n  strings: TemplateStringsArray,\n  ...values: any\n): ParameterizedQuery {\n  if (strings.length == 1 && values.length === 0) {\n    return fluxExpression(strings[0]) // the simplest case\n  }\n  const parts = new Array<string>(strings.length + values.length)\n  let partIndex = 0\n  for (let i = 0; i < strings.length; i++) {\n    const text = strings[i]\n    parts[partIndex++] = text\n    if (i < values.length) {\n      const val = values[i]\n      let sanitized: string\n      if (\n        text.endsWith('\"') &&\n        i + 1 < strings.length &&\n        strings[i + 1].startsWith('\"')\n      ) {\n        // parameter is wrapped into flux double quotes\n        sanitized = sanitizeString(val)\n      } else {\n        sanitized = toFluxValue(val)\n        if (sanitized === '') {\n          // do not allow to insert empty strings, unless it is FluxParameterLike\n          if (!isFluxParameterLike(val)) {\n            throw new Error(\n              `Unsupported parameter literal '${val}' at index: ${i}, type: ${typeof val}`\n            )\n          }\n        }\n      }\n      parts[partIndex++] = sanitized\n    } else if (i < strings.length - 1) {\n      throw new Error('Too few parameters supplied!')\n    }\n  }\n  // return flux expression so that flux can be embedded into another flux as-is\n  return fluxExpression(parts.join(''))\n}\n","import {convertTimeToNanos} from './util/currentTime'\nimport {escape} from './util/escape'\n\n/**\n * Settings that control the way of how a {@link Point} is serialized\n * to a protocol line.\n */\nexport interface PointSettings {\n  /** default tags to add to every point */\n  defaultTags?: {[key: string]: string}\n  /** convertTime serializes Point's timestamp to a line protocol value */\n  convertTime?: (\n    value: string | number | Date | undefined\n  ) => string | undefined\n}\n\n/**\n * Point defines values of a single measurement.\n */\nexport class Point {\n  private name: string\n  private tags: {[key: string]: string} = {}\n  /** escaped field values */\n  public fields: {[key: string]: string} = {}\n  private time: string | number | Date | undefined\n\n  /**\n   * Create a new Point with specified a measurement name.\n   *\n   * @param measurementName - the measurement name\n   */\n  constructor(measurementName?: string) {\n    if (measurementName) this.name = measurementName\n  }\n\n  /**\n   * Sets point's measurement.\n   *\n   * @param name - measurement name\n   * @returns this\n   */\n  public measurement(name: string): Point {\n    this.name = name\n    return this\n  }\n\n  /**\n   * Adds a tag. The caller has to ensure that both name and value are not empty\n   * and do not end with backslash.\n   *\n   * @param name - tag name\n   * @param value - tag value\n   * @returns this\n   */\n  public tag(name: string, value: string): Point {\n    this.tags[name] = value\n    return this\n  }\n\n  /**\n   * Adds a boolean field.\n   *\n   * @param field - field name\n   * @param value - field value\n   * @returns this\n   */\n  public booleanField(name: string, value: boolean | any): Point {\n    this.fields[name] = value ? 'T' : 'F'\n    return this\n  }\n\n  /**\n   * Adds an integer field.\n   *\n   * @param name - field name\n   * @param value - field value\n   * @returns this\n   * @throws NaN or out of int64 range value is supplied\n   */\n  public intField(name: string, value: number | any): Point {\n    let val: number\n    if (typeof value === 'number') {\n      val = value\n    } else {\n      val = parseInt(String(value))\n    }\n    if (isNaN(val) || val <= -9223372036854776e3 || val >= 9223372036854776e3) {\n      throw new Error(`invalid integer value for field '${name}': '${value}'!`)\n    }\n    this.fields[name] = `${Math.floor(val)}i`\n    return this\n  }\n\n  /**\n   * Adds an unsigned integer field.\n   *\n   * @param name - field name\n   * @param value - field value\n   * @returns this\n   * @throws NaN out of range value is supplied\n   */\n  public uintField(name: string, value: number | any): Point {\n    if (typeof value === 'number') {\n      if (isNaN(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n        throw new Error(`uint value for field '${name}' out of range: ${value}`)\n      }\n      this.fields[name] = `${Math.floor(value as number)}u`\n    } else {\n      const strVal = String(value)\n      for (let i = 0; i < strVal.length; i++) {\n        const code = strVal.charCodeAt(i)\n        if (code < 48 || code > 57) {\n          throw new Error(\n            `uint value has an unsupported character at pos ${i}: ${value}`\n          )\n        }\n      }\n      if (\n        strVal.length > 20 ||\n        (strVal.length === 20 &&\n          strVal.localeCompare('18446744073709551615') > 0)\n      ) {\n        throw new Error(\n          `uint value for field '${name}' out of range: ${strVal}`\n        )\n      }\n      this.fields[name] = `${strVal}u`\n    }\n    return this\n  }\n\n  /**\n   * Adds a number field.\n   *\n   * @param name - field name\n   * @param value - field value\n   * @returns this\n   * @throws NaN/Infinity/-Infinity is supplied\n   */\n  public floatField(name: string, value: number | any): Point {\n    let val: number\n    if (typeof value === 'number') {\n      val = value\n    } else {\n      val = parseFloat(value)\n    }\n    if (!isFinite(val)) {\n      throw new Error(`invalid float value for field '${name}': ${value}`)\n    }\n\n    this.fields[name] = String(val)\n    return this\n  }\n\n  /**\n   * Adds a string field.\n   *\n   * @param name - field name\n   * @param value - field value\n   * @returns this\n   */\n  public stringField(name: string, value: string | any): Point {\n    if (value !== null && value !== undefined) {\n      if (typeof value !== 'string') value = String(value)\n      this.fields[name] = escape.quoted(value)\n    }\n    return this\n  }\n\n  /**\n   * Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string\n   * or an undefined value. An undefined value instructs to assign a local timestamp using\n   * the client's clock. An empty string can be used to let the server assign\n   * the timestamp. A number value represents time as a count of time units since epoch, the\n   * exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API\n   * that writes the point.\n   *\n   * Beware that the current time in nanoseconds can't precisely fit into a JS number,\n   * which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as\n   * a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds,\n   * BigInt's `toString()` returns the required high-precision string.\n   *\n   * Note that InfluxDB requires the timestamp to fit into int64 data type.\n   *\n   * @param value - point time\n   * @returns this\n   */\n  public timestamp(value: Date | number | string | undefined): Point {\n    this.time = value\n    return this\n  }\n\n  /**\n   * Creates an InfluxDB protocol line out of this instance.\n   * @param settings - settings control serialization of a point timestamp and can also add default tags,\n   * nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied.\n   * @returns an InfluxDB protocol line out of this instance\n   */\n  public toLineProtocol(settings?: Partial<PointSettings>): string | undefined {\n    if (!this.name) return undefined\n    let fieldsLine = ''\n    Object.keys(this.fields)\n      .sort()\n      .forEach((x) => {\n        if (x) {\n          const val = this.fields[x]\n          if (fieldsLine.length > 0) fieldsLine += ','\n          fieldsLine += `${escape.tag(x)}=${val}`\n        }\n      })\n    if (fieldsLine.length === 0) return undefined // no fields present\n    let tagsLine = ''\n    const tags =\n      settings && settings.defaultTags\n        ? {...settings.defaultTags, ...this.tags}\n        : this.tags\n    Object.keys(tags)\n      .sort()\n      .forEach((x) => {\n        if (x) {\n          const val = tags[x]\n          if (val) {\n            tagsLine += ','\n            tagsLine += `${escape.tag(x)}=${escape.tag(val)}`\n          }\n        }\n      })\n    let time = this.time\n    if (settings && settings.convertTime) {\n      time = settings.convertTime(time)\n    } else {\n      time = convertTimeToNanos(time)\n    }\n\n    return `${escape.measurement(this.name)}${tagsLine} ${fieldsLine}${\n      time !== undefined ? ' ' + time : ''\n    }`\n  }\n\n  toString(): string {\n    const line = this.toLineProtocol(undefined)\n    return line ? line : `invalid point: ${JSON.stringify(this, undefined)}`\n  }\n}\n","import {getRetryDelay, RetryDelayStrategy} from '../errors'\nimport {\n  RetryDelayStrategyOptions,\n  DEFAULT_RetryDelayStrategyOptions,\n} from '../options'\n\n/**\n * Applies a variant of exponential backoff with initial and max delay and a random\n * jitter delay. It also respects `retry delay` when specified together with an error.\n */\nexport class RetryStrategyImpl implements RetryDelayStrategy {\n  options: RetryDelayStrategyOptions\n  currentDelay: number | undefined\n\n  constructor(options?: Partial<RetryDelayStrategyOptions>) {\n    this.options = {...DEFAULT_RetryDelayStrategyOptions, ...options}\n    this.success()\n  }\n\n  nextDelay(error?: Error, failedAttempts?: number): number {\n    const delay = getRetryDelay(error)\n    if (delay && delay > 0) {\n      return delay + Math.round(Math.random() * this.options.retryJitter)\n    } else {\n      if (failedAttempts && failedAttempts > 0) {\n        // compute delay\n        if (this.options.randomRetry) {\n          // random delay between deterministic delays\n          let delay = Math.max(this.options.minRetryDelay, 1)\n          let nextDelay = delay * this.options.exponentialBase\n          for (let i = 1; i < failedAttempts; i++) {\n            delay = nextDelay\n            nextDelay = nextDelay * this.options.exponentialBase\n            if (nextDelay >= this.options.maxRetryDelay) {\n              nextDelay = this.options.maxRetryDelay\n              break\n            }\n          }\n          return (\n            delay +\n            Math.round(\n              Math.random() * (nextDelay - delay) +\n                Math.random() * this.options.retryJitter\n            )\n          )\n        }\n        // deterministric delay otherwise\n        let delay = Math.max(this.options.minRetryDelay, 1)\n        for (let i = 1; i < failedAttempts; i++) {\n          delay = delay * this.options.exponentialBase\n          if (delay >= this.options.maxRetryDelay) {\n            delay = this.options.maxRetryDelay\n            break\n          }\n        }\n        return delay + Math.round(Math.random() * this.options.retryJitter)\n      } else if (this.currentDelay) {\n        this.currentDelay = Math.min(\n          Math.max(this.currentDelay * this.options.exponentialBase, 1) +\n            Math.round(Math.random() * this.options.retryJitter),\n          this.options.maxRetryDelay\n        )\n      } else {\n        this.currentDelay =\n          this.options.minRetryDelay +\n          Math.round(Math.random() * this.options.retryJitter)\n      }\n      return this.currentDelay\n    }\n  }\n  success(): void {\n    this.currentDelay = undefined\n  }\n}\n\n/**\n * Creates a new instance of retry strategy.\n * @param options - retry options\n * @returns retry strategy implementation\n */\nexport function createRetryDelayStrategy(\n  options?: Partial<RetryDelayStrategyOptions>\n): RetryDelayStrategy {\n  return new RetryStrategyImpl(options)\n}\n","import {Log} from '../util/logger'\n\ninterface RetryItem {\n  lines: string[]\n  retryCount: number\n  retryTime: number\n  expires: number\n  next?: RetryItem\n}\n\ntype FindShrinkCandidateResult = [found: RetryItem, parent?: RetryItem]\n\nfunction findShrinkCandidate(first: RetryItem): FindShrinkCandidateResult {\n  let parent = undefined\n  let found = first\n  let currentParent = first\n  while (currentParent.next) {\n    if (currentParent.next.expires < found.expires) {\n      parent = currentParent\n      found = currentParent.next\n    }\n    currentParent = currentParent.next\n  }\n  return [found, parent]\n}\n\n/**\n * Retries lines up to a limit of max buffer size.\n */\nexport default class RetryBuffer {\n  first?: RetryItem\n  size = 0\n  closed = false\n  private _timeoutHandle: any = undefined\n\n  constructor(\n    private maxLines: number,\n    private retryLines: (\n      lines: string[],\n      retryCountdown: number,\n      started: number\n    ) => Promise<void>,\n    private onShrink: (entry: {\n      lines: string[]\n      retryCount: number\n      expires: number\n    }) => void = () => undefined\n  ) {}\n\n  addLines(\n    lines: string[],\n    retryCount: number,\n    delay: number,\n    expires: number\n  ): void {\n    if (this.closed) return\n    if (!lines.length) return\n    let retryTime = Date.now() + delay\n    if (expires < retryTime) {\n      retryTime = expires\n    }\n    // ensure at most maxLines are in the Buffer\n    if (this.first && this.size + lines.length > this.maxLines) {\n      const origSize = this.size\n      const newSize = origSize * 0.7 // reduce to 70 %\n      do {\n        // remove \"oldest\" item\n        const [found, parent] = findShrinkCandidate(this.first)\n        this.size -= found.lines.length\n        if (parent) {\n          parent.next = found.next\n        } else {\n          this.first = found.next\n          if (this.first) {\n            this.scheduleRetry(this.first.retryTime - Date.now())\n          }\n        }\n        found.next = undefined\n        this.onShrink(found)\n      } while (this.first && this.size + lines.length > newSize)\n      Log.error(\n        `RetryBuffer: ${\n          origSize - this.size\n        } oldest lines removed to keep buffer size under the limit of ${\n          this.maxLines\n        } lines.`\n      )\n    }\n    const toAdd: RetryItem = {\n      lines,\n      retryCount,\n      retryTime,\n      expires,\n    }\n    // insert sorted according to retryTime\n    let current: RetryItem | undefined = this.first\n    let parent = undefined\n    for (;;) {\n      if (!current || current.retryTime > retryTime) {\n        toAdd.next = current\n        if (parent) {\n          parent.next = toAdd\n        } else {\n          this.first = toAdd\n          this.scheduleRetry(retryTime - Date.now())\n        }\n        break\n      }\n      parent = current\n      current = current.next\n    }\n    this.size += lines.length\n  }\n\n  removeLines(): RetryItem | undefined {\n    if (this.first) {\n      const toRetry = this.first\n      this.first = this.first.next\n      toRetry.next = undefined\n      this.size -= toRetry.lines.length\n      return toRetry\n    }\n    return undefined\n  }\n\n  scheduleRetry(delay: number): void {\n    if (this._timeoutHandle) {\n      clearTimeout(this._timeoutHandle)\n    }\n    this._timeoutHandle = setTimeout(\n      () => {\n        const toRetry = this.removeLines()\n        if (toRetry) {\n          this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n            .catch(() => {\n              /* error is already logged, it must be caught */\n            })\n            .finally(() => {\n              // schedule next retry execution\n              if (this.first) {\n                this.scheduleRetry(this.first.retryTime - Date.now())\n              }\n            })\n        } else {\n          this._timeoutHandle = undefined\n        }\n      },\n      Math.max(delay, 0)\n    )\n  }\n\n  async flush(): Promise<void> {\n    let toRetry\n    while ((toRetry = this.removeLines())) {\n      await this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n    }\n  }\n\n  close(): number {\n    if (this._timeoutHandle) {\n      clearTimeout(this._timeoutHandle)\n      this._timeoutHandle = undefined\n    }\n    this.closed = true\n    return this.size\n  }\n}\n","/**\n * Utf8Length returns an expected length of a string when UTF-8 encoded.\n * @param s - input string\n * @returns expected count of bytes\n */\nexport default function utf8Length(s: string): number {\n  let retVal = s.length\n  // extends the size with code points (https://en.wikipedia.org/wiki/UTF-8#Encoding)\n  for (let i = 0; i < s.length; i++) {\n    const code = s.charCodeAt(i)\n    /* istanbul ignore else - JS does not count with 4-bytes UNICODE characters at the moment */\n    if (code < 0x80) {\n      continue\n    } else if (code >= 0x80 && code <= 0x7ff) {\n      retVal++\n    } else if (code >= 0x800 && code <= 0xffff) {\n      if (code >= 0xd800 && code <= 0xdfff) {\n        // node.js represents unicode characters above 0xffff by two UTF-16 surrogate halves\n        // see https://en.wikipedia.org/wiki/UTF-8#Codepage_layout\n        retVal++\n      } else {\n        retVal += 2\n      }\n    } else {\n      // never happens in node.js 14, the situation can vary in the futures or in deno/browsers\n      retVal += 3\n    }\n  }\n  return retVal\n}\n","import WriteApi from '../WriteApi'\nimport {\n  DEFAULT_WriteOptions,\n  WriteOptions,\n  WritePrecisionType,\n} from '../options'\nimport {Transport, SendOptions} from '../transport'\nimport {Headers} from '../results'\nimport {Log} from '../util/logger'\nimport {HttpError, RetryDelayStrategy} from '../errors'\nimport {Point} from '../Point'\nimport {currentTime, dateToProtocolTimestamp} from '../util/currentTime'\nimport {createRetryDelayStrategy} from './retryStrategy'\nimport RetryBuffer from './RetryBuffer'\nimport utf8Length from '../util/utf8Length'\n\nclass WriteBuffer {\n  length = 0\n  bytes = -1\n  lines: string[]\n\n  constructor(\n    private maxChunkRecords: number,\n    private maxBatchBytes: number,\n    private flushFn: (lines: string[]) => Promise<void>,\n    private scheduleSend: () => void\n  ) {\n    this.lines = new Array<string>(maxChunkRecords)\n  }\n\n  add(record: string): void {\n    const size = utf8Length(record)\n    if (this.length === 0) {\n      this.scheduleSend()\n    } else if (this.bytes + size + 1 >= this.maxBatchBytes) {\n      // the new size already exceeds maxBatchBytes, send it\n      this.flush().catch((_e) => {\n        // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n      })\n    }\n    this.lines[this.length] = record\n    this.length++\n    this.bytes += size + 1\n    if (\n      this.length >= this.maxChunkRecords ||\n      this.bytes >= this.maxBatchBytes\n    ) {\n      this.flush().catch((_e) => {\n        // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n      })\n    }\n  }\n  flush(): Promise<void> {\n    const lines = this.reset()\n    if (lines.length > 0) {\n      return this.flushFn(lines)\n    } else {\n      return Promise.resolve()\n    }\n  }\n  reset(): string[] {\n    const retVal = this.lines.slice(0, this.length)\n    this.length = 0\n    this.bytes = -1 // lines are joined with \\n\n    return retVal\n  }\n}\n\nexport default class WriteApiImpl implements WriteApi {\n  public path: string\n\n  private writeBuffer: WriteBuffer\n  private closed = false\n  private writeOptions: WriteOptions\n  private sendOptions: SendOptions\n  private _timeoutHandle: any = undefined\n  private currentTime: () => string\n  private dateToProtocolTimestamp: (d: Date) => string\n\n  retryBuffer: RetryBuffer\n  retryStrategy: RetryDelayStrategy\n\n  constructor(\n    private transport: Transport,\n    org: string,\n    bucket: string,\n    precision: WritePrecisionType,\n    writeOptions?: Partial<WriteOptions>\n  ) {\n    this.path = `/api/v2/write?org=${encodeURIComponent(\n      org\n    )}&bucket=${encodeURIComponent(bucket)}&precision=${precision}`\n    if (writeOptions?.consistency) {\n      this.path += `&consistency=${encodeURIComponent(\n        writeOptions.consistency\n      )}`\n    }\n    this.writeOptions = {\n      ...DEFAULT_WriteOptions,\n      ...writeOptions,\n    }\n    this.currentTime = currentTime[precision]\n    this.dateToProtocolTimestamp = dateToProtocolTimestamp[precision]\n    if (this.writeOptions.defaultTags) {\n      this.useDefaultTags(this.writeOptions.defaultTags)\n    }\n    this.sendOptions = {\n      method: 'POST',\n      headers: {\n        'content-type': 'text/plain; charset=utf-8',\n        ...writeOptions?.headers,\n      },\n      gzipThreshold: this.writeOptions.gzipThreshold,\n    }\n\n    const scheduleNextSend = (): void => {\n      if (this.writeOptions.flushInterval > 0) {\n        this._clearFlushTimeout()\n        /* istanbul ignore else manually reviewed, hard to reproduce */\n        if (!this.closed) {\n          this._timeoutHandle = setTimeout(\n            () =>\n              this.sendBatch(\n                this.writeBuffer.reset(),\n                this.writeOptions.maxRetries\n              ).catch((_e) => {\n                // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n              }),\n            this.writeOptions.flushInterval\n          )\n        }\n      }\n    }\n    // write buffer\n    this.writeBuffer = new WriteBuffer(\n      this.writeOptions.batchSize,\n      this.writeOptions.maxBatchBytes,\n      (lines) => {\n        this._clearFlushTimeout()\n        return this.sendBatch(lines, this.writeOptions.maxRetries)\n      },\n      scheduleNextSend\n    )\n    this.sendBatch = this.sendBatch.bind(this)\n    // retry buffer\n    this.retryStrategy = createRetryDelayStrategy(this.writeOptions)\n    this.retryBuffer = new RetryBuffer(\n      this.writeOptions.maxBufferLines,\n      this.sendBatch,\n      this.writeOptions.writeRetrySkipped\n    )\n  }\n\n  sendBatch(\n    lines: string[],\n    retryAttempts: number,\n    expires: number = Date.now() + this.writeOptions.maxRetryTime\n  ): Promise<void> {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const self: WriteApiImpl = this\n    const failedAttempts = self.writeOptions.maxRetries + 1 - retryAttempts\n    if (!this.closed && lines.length > 0) {\n      if (expires <= Date.now()) {\n        const error = new Error('Max retry time exceeded.')\n        const onRetry = self.writeOptions.writeFailed.call(\n          self,\n          error,\n          lines,\n          failedAttempts,\n          expires\n        )\n        if (onRetry) {\n          return onRetry\n        }\n        Log.error(\n          `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n          error\n        )\n        return Promise.reject(error)\n      }\n      return new Promise<void>((resolve, reject) => {\n        let responseStatusCode: number | undefined\n        let headers: Headers | undefined\n        const callbacks = {\n          responseStarted(_headers: Headers, statusCode?: number): void {\n            responseStatusCode = statusCode\n            headers = _headers\n          },\n          error(error: Error): void {\n            // call the writeFailed listener and check if we can retry\n            const onRetry = self.writeOptions.writeFailed.call(\n              self,\n              error,\n              lines,\n              failedAttempts,\n              expires\n            )\n            if (onRetry) {\n              onRetry.then(resolve, reject)\n              return\n            }\n            // ignore informational message about the state of InfluxDB\n            // enterprise cluster, if present\n            if (\n              error instanceof HttpError &&\n              error.json &&\n              typeof error.json.error === 'string' &&\n              error.json.error.includes('hinted handoff queue not empty')\n            ) {\n              Log.warn('Write to InfluxDB returns: ' + error.json.error)\n              responseStatusCode = 204\n              callbacks.complete()\n              return\n            }\n            // retry if possible\n            if (\n              !self.closed &&\n              retryAttempts > 0 &&\n              (!(error instanceof HttpError) ||\n                (error as HttpError).statusCode >= 429)\n            ) {\n              Log.warn(\n                `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n                error\n              )\n              self.retryBuffer.addLines(\n                lines,\n                retryAttempts - 1,\n                self.retryStrategy.nextDelay(error, failedAttempts),\n                expires\n              )\n              reject(error)\n              return\n            }\n            Log.error(`Write to InfluxDB failed.`, error)\n            reject(error)\n          },\n          complete(): void {\n            // InfluxDB v3 returns 201 for partial success\n            // older implementations of transport do not report status code\n            if (\n              responseStatusCode == 204 ||\n              responseStatusCode == 201 ||\n              responseStatusCode == undefined\n            ) {\n              self.writeOptions.writeSuccess.call(self, lines)\n              self.retryStrategy.success()\n              resolve()\n            } else {\n              const message = `204 HTTP response status code expected, but ${responseStatusCode} returned`\n              const error = new HttpError(\n                responseStatusCode,\n                message,\n                undefined,\n                '0',\n                undefined,\n                undefined,\n                headers\n              )\n              error.message = message\n              callbacks.error(error)\n            }\n          },\n        }\n        this.transport.send(\n          this.path,\n          lines.join('\\n'),\n          this.sendOptions,\n          callbacks\n        )\n      })\n    } else {\n      return Promise.resolve()\n    }\n  }\n\n  private _clearFlushTimeout(): void {\n    if (this._timeoutHandle !== undefined) {\n      clearTimeout(this._timeoutHandle)\n      this._timeoutHandle = undefined\n    }\n  }\n\n  writeRecord(record: string): void {\n    if (this.closed) {\n      throw new Error('writeApi: already closed!')\n    }\n    this.writeBuffer.add(record)\n  }\n  writeRecords(records: ArrayLike<string>): void {\n    if (this.closed) {\n      throw new Error('writeApi: already closed!')\n    }\n    for (let i = 0; i < records.length; i++) {\n      this.writeBuffer.add(records[i])\n    }\n  }\n  writePoint(point: Point): void {\n    if (this.closed) {\n      throw new Error('writeApi: already closed!')\n    }\n    const line = point.toLineProtocol(this)\n    if (line) this.writeBuffer.add(line)\n  }\n  writePoints(points: ArrayLike<Point>): void {\n    if (this.closed) {\n      throw new Error('writeApi: already closed!')\n    }\n    for (let i = 0; i < points.length; i++) {\n      const line = points[i].toLineProtocol(this)\n      if (line) this.writeBuffer.add(line)\n    }\n  }\n  async flush(withRetryBuffer?: boolean): Promise<void> {\n    await this.writeBuffer.flush()\n    if (withRetryBuffer) {\n      return await this.retryBuffer.flush()\n    }\n  }\n  close(): Promise<void> {\n    const retVal = this.writeBuffer.flush().finally(() => {\n      const remaining = this.retryBuffer.close()\n      if (remaining) {\n        Log.error(\n          `Retry buffer closed with ${remaining} items that were not written to InfluxDB!`,\n          null\n        )\n      }\n      this.closed = true\n    })\n    return retVal\n  }\n  dispose(): number {\n    this._clearFlushTimeout()\n    this.closed = true\n    return this.retryBuffer.close() + this.writeBuffer.length\n  }\n\n  // PointSettings\n  defaultTags: {[key: string]: string} | undefined\n  useDefaultTags(tags: {[key: string]: string}): WriteApi {\n    this.defaultTags = tags\n    return this\n  }\n  convertTime(value: string | number | Date | undefined): string | undefined {\n    if (value === undefined) {\n      return this.currentTime()\n    } else if (typeof value === 'string') {\n      return value.length > 0 ? value : undefined\n    } else if (value instanceof Date) {\n      return this.dateToProtocolTimestamp(value)\n    } else if (typeof value === 'number') {\n      return String(Math.floor(value))\n    } else {\n      return String(value)\n    }\n  }\n}\n","import {CommunicationObserver, Headers} from '../results'\n\ntype CompleteObserver = Omit<\n  Required<CommunicationObserver<any>>,\n  'useCancellable' | 'useResume'\n> &\n  Pick<CommunicationObserver<any>, 'useResume' | 'useCancellable'>\n\nexport default function completeCommunicationObserver(\n  callbacks: Partial<CommunicationObserver<any>> = {}\n): CompleteObserver {\n  let state = 0\n  const retVal: CompleteObserver = {\n    next: (data: any): void | boolean => {\n      if (\n        state === 0 &&\n        callbacks.next &&\n        data !== null &&\n        data !== undefined\n      ) {\n        return callbacks.next(data)\n      }\n    },\n    error: (error: Error): void => {\n      /* istanbul ignore else propagate error at most once */\n      if (state === 0) {\n        state = 1\n        /* istanbul ignore else safety check */\n        if (callbacks.error) callbacks.error(error)\n      }\n    },\n    complete: (): void => {\n      if (state === 0) {\n        state = 2\n        /* istanbul ignore else safety check */\n        if (callbacks.complete) callbacks.complete()\n      }\n    },\n    responseStarted: (headers: Headers, statusCode?: number): void => {\n      if (callbacks.responseStarted)\n        callbacks.responseStarted(headers, statusCode)\n    },\n  }\n  if (callbacks.useCancellable) {\n    retVal.useCancellable = callbacks.useCancellable.bind(callbacks)\n  }\n  if (callbacks.useResume) {\n    retVal.useResume = callbacks.useResume.bind(callbacks)\n  }\n  return retVal\n}\n","import {Transport, SendOptions} from '../../transport'\nimport {ConnectionOptions} from '../../options'\nimport {AbortError, HttpError} from '../../errors'\nimport completeCommunicationObserver from '../completeCommunicationObserver'\nimport {Log} from '../../util/logger'\nimport {\n  ChunkCombiner,\n  CommunicationObserver,\n  createTextDecoderCombiner,\n  Headers,\n  ResponseStartedFn,\n} from '../../results'\n\nfunction getResponseHeaders(response: Response): Headers {\n  const headers: Headers = {}\n  response.headers.forEach((value: string, key: string) => {\n    const previous = headers[key]\n    if (previous === undefined) {\n      headers[key] = value\n    } else if (Array.isArray(previous)) {\n      previous.push(value)\n    } else {\n      headers[key] = [previous, value]\n    }\n  })\n  return headers\n}\n\n/**\n * Transport layer that use browser fetch.\n */\nexport default class FetchTransport implements Transport {\n  chunkCombiner: ChunkCombiner = createTextDecoderCombiner()\n  private defaultHeaders: {[key: string]: string}\n  private url: string\n  constructor(private connectionOptions: ConnectionOptions) {\n    this.defaultHeaders = {\n      'content-type': 'application/json; charset=utf-8',\n      // 'User-Agent': `influxdb-client-js/${CLIENT_LIB_VERSION}`, // user-agent can hardly be customized https://github.com/influxdata/influxdb-client-js/issues/262\n      ...connectionOptions.headers,\n    }\n    if (this.connectionOptions.token) {\n      this.defaultHeaders['Authorization'] =\n        'Token ' + this.connectionOptions.token\n    }\n    this.url = String(this.connectionOptions.url)\n    if (this.url.endsWith('/')) {\n      this.url = this.url.substring(0, this.url.length - 1)\n    }\n    // https://github.com/influxdata/influxdb-client-js/issues/263\n    // don't allow /api/v2 suffix to avoid future problems\n    if (this.url.endsWith('/api/v2')) {\n      this.url = this.url.substring(0, this.url.length - '/api/v2'.length)\n      Log.warn(\n        `Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`\n      )\n    }\n  }\n  send(\n    path: string,\n    body: string,\n    options: SendOptions,\n    callbacks?: Partial<CommunicationObserver<Uint8Array>> | undefined\n  ): void {\n    const observer = completeCommunicationObserver(callbacks)\n    let cancelled = false\n    let signal = (options as any).signal\n    let pausePromise: Promise<void> | undefined\n    const resumeQuickly = () => {}\n    let resume = resumeQuickly\n    if (callbacks && callbacks.useCancellable) {\n      const controller = new AbortController()\n      if (!signal) {\n        signal = controller.signal\n        options = {...options, signal}\n      }\n      // resume data reading so that it can exit on abort signal\n      signal.addEventListener('abort', () => {\n        resume()\n      })\n      callbacks.useCancellable({\n        cancel() {\n          cancelled = true\n          controller.abort()\n        },\n        isCancelled() {\n          return cancelled || signal.aborted\n        },\n      })\n    }\n    this.fetch(path, body, options)\n      .then(async (response) => {\n        if (callbacks?.responseStarted) {\n          observer.responseStarted(\n            getResponseHeaders(response),\n            response.status\n          )\n        }\n        await this.throwOnErrorResponse(response)\n        if (response.body) {\n          const reader = response.body.getReader()\n          let chunk: ReadableStreamReadResult<Uint8Array>\n          do {\n            if (pausePromise) {\n              await pausePromise\n            }\n            if (cancelled) {\n              break\n            }\n            chunk = await reader.read()\n            if (observer.next(chunk.value) === false) {\n              const useResume = observer.useResume\n              if (!useResume) {\n                const msg = 'Unable to pause, useResume is not configured!'\n                await reader.cancel(msg)\n                return Promise.reject(new Error(msg))\n              }\n              pausePromise = new Promise((resolve) => {\n                resume = () => {\n                  resolve()\n                  pausePromise = undefined\n                  resume = resumeQuickly\n                }\n                useResume(resume)\n              })\n            }\n          } while (!chunk.done)\n        } else if (response.arrayBuffer) {\n          const buffer = await response.arrayBuffer()\n          observer.next(new Uint8Array(buffer))\n        } else {\n          const text = await response.text()\n          observer.next(new TextEncoder().encode(text))\n        }\n      })\n      .catch((e) => {\n        if (!cancelled) {\n          observer.error(e)\n        }\n      })\n      .finally(() => observer.complete())\n  }\n  private async throwOnErrorResponse(response: Response): Promise<void> {\n    if (response.status >= 300) {\n      let text = ''\n      try {\n        text = await response.text()\n        if (!text) {\n          const headerError = response.headers.get('x-influxdb-error')\n          if (headerError) {\n            text = headerError\n          }\n        }\n      } catch (e) {\n        Log.warn('Unable to receive error body', e)\n\n        throw new HttpError(\n          response.status,\n          response.statusText,\n          undefined,\n          response.headers.get('retry-after'),\n          response.headers.get('content-type'),\n          undefined,\n          getResponseHeaders(response)\n        )\n      }\n      throw new HttpError(\n        response.status,\n        response.statusText,\n        text,\n        response.headers.get('retry-after'),\n        response.headers.get('content-type'),\n        undefined,\n        getResponseHeaders(response)\n      )\n    }\n  }\n\n  async *iterate(\n    path: string,\n    body: string,\n    options: SendOptions\n  ): AsyncIterableIterator<Uint8Array> {\n    const response = await this.fetch(path, body, options)\n    await this.throwOnErrorResponse(response)\n    if (response.body) {\n      const reader = response.body.getReader()\n      for (;;) {\n        const {value, done} = await reader.read()\n        if (done) {\n          break\n        }\n        if (options.signal?.aborted) {\n          await response.body.cancel()\n          throw new AbortError()\n        }\n        yield value\n      }\n    } else if (response.arrayBuffer) {\n      const buffer = await response.arrayBuffer()\n      yield new Uint8Array(buffer)\n    } else {\n      const text = await response.text()\n      yield new TextEncoder().encode(text)\n    }\n  }\n\n  async request(\n    path: string,\n    body: any,\n    options: SendOptions,\n    responseStarted?: ResponseStartedFn\n  ): Promise<any> {\n    const response = await this.fetch(path, body, options)\n    const {headers} = response\n    const responseContentType = headers.get('content-type') || ''\n    if (responseStarted) {\n      responseStarted(getResponseHeaders(response), response.status)\n    }\n\n    await this.throwOnErrorResponse(response)\n    const responseType = options.headers?.accept ?? responseContentType\n    if (responseType.includes('json')) {\n      return await response.json()\n    } else if (\n      responseType.includes('text') ||\n      responseType.startsWith('application/csv')\n    ) {\n      return await response.text()\n    }\n  }\n\n  private fetch(\n    path: string,\n    body: any,\n    options: SendOptions\n  ): Promise<Response> {\n    const {method, headers, ...other} = options\n    const url = `${this.url}${path}`\n    const request: RequestInit = {\n      method: method,\n      body:\n        method === 'GET' || method === 'HEAD'\n          ? undefined\n          : typeof body === 'string'\n            ? body\n            : JSON.stringify(body),\n      headers: {\n        ...this.defaultHeaders,\n        ...headers,\n      },\n      credentials: 'omit' as const,\n      // override with custom transport options\n      ...this.connectionOptions.transportOptions,\n      // allow to specify custom options, such as signal, in SendOptions\n      ...other,\n    }\n    this.requestDecorator(request, options, url)\n    return fetch(url, request)\n  }\n\n  /**\n   * RequestDecorator allows to modify requests before sending.\n   *\n   * The following example shows a function that adds gzip\n   * compression of requests using pako.js.\n   *\n   * ```ts\n   * const client = new InfluxDB({url: 'http://a'})\n   * client.transport.requestDecorator = function(request, options) {\n   *   const body = request.body\n   *   if (\n   *     typeof body === 'string' &&\n   *     options.gzipThreshold !== undefined &&\n   *     body.length > options.gzipThreshold\n   *   ) {\n   *     request.headers['content-encoding'] = 'gzip'\n   *     request.body = pako.gzip(body)\n   *   }\n   * }\n   * ```\n   */\n  public requestDecorator: (\n    request: RequestInit,\n    options: SendOptions,\n    url: string\n  ) => void = function () {}\n}\n","import {Observable} from '../observable'\nimport QueryApi, {QueryOptions} from '../QueryApi'\nimport {Transport} from '../transport'\nimport {\n  CommunicationObserver,\n  FluxResultObserver,\n  FluxTableMetaData,\n  Row,\n  AnnotatedCSVResponse,\n  IterableResultExecutor,\n} from '../results'\nimport {ParameterizedQuery} from '../query/flux'\nimport {APIExecutor} from '../results/ObservableQuery'\n\nconst DEFAULT_dialect: any = {\n  header: true,\n  delimiter: ',',\n  quoteChar: '\"',\n  commentPrefix: '#',\n  annotations: ['datatype', 'group', 'default'],\n}\n\nexport class QueryApiImpl implements QueryApi {\n  private options: QueryOptions\n  constructor(\n    private transport: Transport,\n    private createCSVResponse: (\n      executor: APIExecutor,\n      iterableResultExecutor: IterableResultExecutor\n    ) => AnnotatedCSVResponse,\n    org: string | QueryOptions\n  ) {\n    this.options = typeof org === 'string' ? {org} : org\n  }\n\n  with(options: Partial<QueryOptions>): QueryApi {\n    return new QueryApiImpl(this.transport, this.createCSVResponse, {\n      ...this.options,\n      ...options,\n    })\n  }\n\n  response(query: string | ParameterizedQuery): AnnotatedCSVResponse {\n    const {org, type, gzip, headers} = this.options\n    const path = `/api/v2/query?org=${encodeURIComponent(org)}`\n    const body = JSON.stringify(\n      this.decorateRequest({\n        query: query.toString(),\n        dialect: DEFAULT_dialect,\n        type,\n      })\n    )\n    const options = {\n      method: 'POST',\n      headers: {\n        'content-type': 'application/json; encoding=utf-8',\n        'accept-encoding': gzip ? 'gzip' : 'identity',\n        ...headers,\n      },\n    }\n    return this.createCSVResponse(\n      (consumer) => this.transport.send(path, body, options, consumer),\n      () => this.transport.iterate(path, body, options)\n    )\n  }\n\n  iterateLines(query: string | ParameterizedQuery): AsyncIterable<string> {\n    return this.response(query).iterateLines()\n  }\n  iterateRows(query: string | ParameterizedQuery): AsyncIterable<Row> {\n    return this.response(query).iterateRows()\n  }\n  lines(query: string | ParameterizedQuery): Observable<string> {\n    return this.response(query).lines()\n  }\n\n  rows(query: string | ParameterizedQuery): Observable<Row> {\n    return this.response(query).rows()\n  }\n\n  queryLines(\n    query: string | ParameterizedQuery,\n    consumer: CommunicationObserver<string>\n  ): void {\n    return this.response(query).consumeLines(consumer)\n  }\n\n  queryRows(\n    query: string | ParameterizedQuery,\n    consumer: FluxResultObserver<string[]>\n  ): void {\n    return this.response(query).consumeRows(consumer)\n  }\n\n  collectRows<T>(\n    query: string | ParameterizedQuery,\n    rowMapper?: (\n      values: string[],\n      tableMeta: FluxTableMetaData\n    ) => T | undefined\n  ): Promise<Array<T>> {\n    return this.response(query).collectRows(rowMapper)\n  }\n\n  collectLines(query: string | ParameterizedQuery): Promise<Array<string>> {\n    return this.response(query).collectLines()\n  }\n\n  queryRaw(query: string | ParameterizedQuery): Promise<string> {\n    const {org, type, gzip, headers} = this.options\n    return this.transport.request(\n      `/api/v2/query?org=${encodeURIComponent(org)}`,\n      JSON.stringify(\n        this.decorateRequest({\n          query: query.toString(),\n          dialect: DEFAULT_dialect,\n          type,\n        })\n      ),\n      {\n        method: 'POST',\n        headers: {\n          accept: 'text/csv',\n          'accept-encoding': gzip ? 'gzip' : 'identity',\n          'content-type': 'application/json; encoding=utf-8',\n          ...headers,\n        },\n      }\n    )\n  }\n\n  private decorateRequest(request: any): any {\n    if (typeof this.options.now === 'function') {\n      request.now = this.options.now()\n    }\n    // https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery requires type\n    request.type = this.options.type ?? 'flux'\n    return request\n  }\n}\n\nexport default QueryApiImpl\n","import {\n  CommunicationObserver,\n  FluxResultObserver,\n  FluxTableMetaData,\n  Row,\n  linesToTables,\n  ChunkCombiner,\n  chunksToLines,\n  chunksToLinesIterable,\n  linesToRowsIterable,\n} from '../results'\nimport {Observable} from '../observable'\nimport {\n  AnnotatedCSVResponse,\n  IterableResultExecutor,\n} from './AnnotatedCSVResponse'\nimport ObservableQuery, {APIExecutor} from './ObservableQuery'\n\nexport function defaultRowMapping(\n  values: string[],\n  tableMeta: FluxTableMetaData\n): Record<string, any> {\n  return tableMeta.toObject(values)\n}\n\n/**\n * AnnotatedCsvResponseImpl is an implementation AnnotatedCsvResponse\n * that uses the supplied executor to supply a response data stream.\n */\nexport class AnnotatedCSVResponseImpl implements AnnotatedCSVResponse {\n  constructor(\n    private executor: APIExecutor,\n    private iterableResultExecutor: IterableResultExecutor,\n    private chunkCombiner: ChunkCombiner\n  ) {}\n  iterateLines(): AsyncIterable<string> {\n    return chunksToLinesIterable(this.iterableResultExecutor())\n  }\n  iterateRows(): AsyncIterable<Row> {\n    return linesToRowsIterable(\n      chunksToLinesIterable(this.iterableResultExecutor())\n    )\n  }\n  lines(): Observable<string> {\n    return new ObservableQuery(this.executor, (observer) =>\n      chunksToLines(observer, this.chunkCombiner)\n    )\n  }\n\n  rows(): Observable<Row> {\n    return new ObservableQuery(this.executor, (observer) => {\n      return chunksToLines(\n        linesToTables({\n          next(values, tableMeta) {\n            observer.next({values, tableMeta})\n          },\n          error(e) {\n            observer.error(e)\n          },\n          complete() {\n            observer.complete()\n          },\n        }),\n        this.chunkCombiner\n      )\n    })\n  }\n\n  consumeLines(consumer: CommunicationObserver<string>): void {\n    this.executor(chunksToLines(consumer, this.chunkCombiner))\n  }\n\n  consumeRows(consumer: FluxResultObserver<string[]>): void {\n    this.executor(chunksToLines(linesToTables(consumer), this.chunkCombiner))\n  }\n\n  collectRows<T>(\n    rowMapper: (\n      values: string[],\n      tableMeta: FluxTableMetaData\n    ) => T | undefined = defaultRowMapping as (\n      values: string[],\n      tableMeta: FluxTableMetaData\n    ) => T | undefined\n  ): Promise<Array<T>> {\n    const retVal: Array<T> = []\n    return new Promise((resolve, reject) => {\n      this.consumeRows({\n        next(values: string[], tableMeta: FluxTableMetaData): void {\n          const toAdd = rowMapper.call(this, values, tableMeta)\n          if (toAdd !== undefined) {\n            retVal.push(toAdd)\n          }\n        },\n        error(error: Error): void {\n          reject(error)\n        },\n        complete(): void {\n          resolve(retVal)\n        },\n      })\n    })\n  }\n\n  collectLines(): Promise<Array<string>> {\n    const retVal: Array<string> = []\n    return new Promise((resolve, reject) => {\n      this.consumeLines({\n        next(line: string): void {\n          retVal.push(line)\n        },\n        error(error: Error): void {\n          reject(error)\n        },\n        complete(): void {\n          resolve(retVal)\n        },\n      })\n    })\n  }\n}\n","import WriteApi from './WriteApi'\nimport {ClientOptions, WriteOptions, WritePrecisionType} from './options'\nimport WriteApiImpl from './impl/WriteApiImpl'\nimport {IllegalArgumentError} from './errors'\nimport {Transport} from './transport'\n// replaced by ./impl/browser/FetchTransport in browser builds\nimport TransportImpl from './impl/browser/FetchTransport'\nimport QueryApi, {QueryOptions} from './QueryApi'\nimport QueryApiImpl from './impl/QueryApiImpl'\nimport {\n  AnnotatedCSVResponse,\n  APIExecutor,\n  IterableResultExecutor,\n} from './results'\nimport {AnnotatedCSVResponseImpl} from './results/AnnotatedCSVResponseImpl'\n\n/**\n * InfluxDB entry point that configures communication with InfluxDB server\n * and provide APIs to write and query data.\n */\nexport default class InfluxDB {\n  private _options: ClientOptions\n  readonly transport: Transport\n  readonly processCSVResponse: (\n    executor: APIExecutor,\n    iterableResultExecutor: IterableResultExecutor\n  ) => AnnotatedCSVResponse\n\n  /**\n   * Creates influxdb client options from an options object or url.\n   * @param options - client options\n   */\n  constructor(options: ClientOptions | string) {\n    if (typeof options === 'string') {\n      this._options = {url: options}\n    } else if (options !== null && typeof options === 'object') {\n      this._options = Object.assign({}, options)\n    } else {\n      throw new IllegalArgumentError('No url or configuration specified!')\n    }\n    const url = this._options.url\n    if (typeof url !== 'string')\n      throw new IllegalArgumentError('No url specified!')\n    if (url.endsWith('/')) this._options.url = url.substring(0, url.length - 1)\n    this.transport = this._options.transport ?? new TransportImpl(this._options)\n    delete this._options.token\n    this.processCSVResponse = (\n      executor: APIExecutor,\n      iterableResultExecutor: IterableResultExecutor\n    ): AnnotatedCSVResponse =>\n      new AnnotatedCSVResponseImpl(\n        executor,\n        iterableResultExecutor,\n        this.transport.chunkCombiner\n      )\n  }\n\n  /**\n   * Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed\n   * in order to flush the remaining data and close already scheduled retry executions.\n   *\n   * @remarks\n   * Use {@link WriteOptions} to customize retry strategy options, data chunking\n   * and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults.\n   *\n   * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example},\n   * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example},\n   * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}.\n   *\n   * @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably.\n   * @param bucket - The destination bucket for writes.\n   * @param precision - Timestamp precision for line items.\n   * @param writeOptions - Custom write options.\n   * @returns WriteApi instance\n   */\n  getWriteApi(\n    org: string,\n    bucket: string,\n    precision: WritePrecisionType = 'ns',\n    writeOptions?: Partial<WriteOptions>\n  ): WriteApi {\n    return new WriteApiImpl(\n      this.transport,\n      org,\n      bucket,\n      precision,\n      writeOptions ?? this._options.writeOptions\n    )\n  }\n\n  /**\n   * Creates QueryApi for the supplied organization .\n   *\n   * @remarks\n   * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example},\n   * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example},\n   * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example},\n   * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example},\n   *\n   * @param org - organization or query options\n   * @returns QueryApi instance\n   */\n  getQueryApi(org: string | QueryOptions): QueryApi {\n    return new QueryApiImpl(this.transport, this.processCSVResponse, org)\n  }\n}\n","import {\n  Table,\n  FromFluxResult,\n  ColumnType,\n  FluxDataType,\n  ColumnData,\n} from '@influxdata/giraffe'\nimport {\n  stringToLines,\n  linesToTables,\n  ColumnType as ClientColumnType,\n  FluxTableMetaData,\n  FluxResultObserver,\n  Cancellable,\n} from '@influxdata/influxdb-client'\n\n/** A type of a function that creates a new giraffe table of a specified length */\nexport type GiraffeTableFactory = (length: number) => Table\n\n/**\n * Stores data and metadata of a result column.\n */\ninterface Column {\n  /** column name */\n  name: string\n  /** giraffe column type */\n  type: ColumnType\n  /** flux data type */\n  fluxDataType: FluxDataType\n  /** column data */\n  data: ColumnData\n  /** convert result row to column value */\n  toValue: (row: string[]) => number | string | boolean | null\n  /** when true, it is a no-data column to indicate that multiple columns of the same label exist (distinguished also by column type) */\n  multipleTypes?: true\n  /** group key membership of this column */\n  group?: boolean\n}\n\nfunction createResult(\n  tableLength: number,\n  columns: Record<string, Column>,\n  tableFactory: GiraffeTableFactory,\n  {computeFluxGroupKeyUnion, computeResultColumnNames}: TableOptions\n): FromFluxResult {\n  let table = tableFactory(tableLength)\n  const fluxGroupKeyUnion: string[] = []\n  const resultColumnNames = new Set<string>()\n  Object.keys(columns).forEach((key) => {\n    const col = columns[key]\n    if (!col.multipleTypes) {\n      ;(col.data as any).length = tableLength // extend the array length, required (and tested)\n      table = table.addColumn(\n        key,\n        col.fluxDataType,\n        col.type,\n        col.data,\n        col.name\n      )\n      if (computeFluxGroupKeyUnion && col.group) {\n        fluxGroupKeyUnion.push(key)\n      }\n      if (computeResultColumnNames && col.name === 'result') {\n        col.data.forEach((x) => resultColumnNames.add(x as string))\n      }\n    }\n  })\n\n  return {\n    table,\n    fluxGroupKeyUnion,\n    resultColumnNames: Array.from(resultColumnNames),\n  }\n}\n\n/**\n * AcceptRowFunction allows to accept/reject specific rows or terminate processing.\n * @param row - CSV result data row\n * @param tableMeta - CSV table metadata with column descriptors\n * @returns true to accept row, false to skip row, undefined means stop processing\n **/\nexport type AcceptRowFunction = (\n  row: string[],\n  tableMeta: FluxTableMetaData\n) => true | false | undefined\n\n/**\n * Contains parameters that optimize/drive creation of the query result Table.\n */\nexport interface TableOptions {\n  /**\n   * Accept allows to accept/reject specific rows or terminate processing.\n   **/\n  accept?: AcceptRowFunction | AcceptRowFunction[]\n  /**\n   * Sets maximum table length, QUERY_MAX_TABLE_LENGTH when undefined.\n   */\n  maxTableLength?: number\n\n  /** column keys to collect in the table, undefined means all columns */\n  columns?: string[]\n\n  /** compute also fluxGroupKeyUnion */\n  computeFluxGroupKeyUnion?: boolean\n\n  /** compute also resultColumnNames */\n  computeResultColumnNames?: boolean\n}\n\n/**\n * QUERY_MAX_TABLE_LENGTH is a default max table length,\n * it can be overriden in TableOptions.\n */\nexport const QUERY_MAX_TABLE_LENGTH = 100_000\n\n/**\n * Creates an accept function that stops processing\n * if the table reaches the specified max rows.\n * @param size - maximum processed rows\n * @returns AcceptRowFunction that enforces that most max rows are processed\n */\nexport function acceptMaxTableLength(max: number): AcceptRowFunction {\n  let size = 0\n  return (): true | undefined => {\n    if (size >= max) {\n      // eslint-disable-next-line no-console\n      console.log(\n        `csv2Table: max table length ${max} reached, processing stopped`\n      )\n      return undefined\n    }\n    size++\n    return true\n  }\n}\n\n/**\n * Creates a single accept function for the TableOptions supplied.\n * @param options - table options\n * @returns accept function\n */\nfunction createAcceptRowFunction(options: TableOptions): AcceptRowFunction {\n  const maxTableLength =\n    options.maxTableLength === undefined\n      ? QUERY_MAX_TABLE_LENGTH\n      : options.maxTableLength\n  const acceptors: AcceptRowFunction[] = []\n  if (options.accept) {\n    if (Array.isArray(options.accept)) {\n      acceptors.push(...options.accept)\n    } else {\n      acceptors.push(options.accept)\n    }\n  }\n  acceptors.push(acceptMaxTableLength(maxTableLength))\n\n  return (\n    row: string[],\n    tableMeta: FluxTableMetaData\n  ): true | false | undefined => {\n    for (let i = 0; i < acceptors.length; i++) {\n      const retVal = acceptors[i](row, tableMeta)\n      if (retVal === undefined || retVal === false) {\n        return retVal\n      }\n    }\n    return true\n  }\n}\n\n/**\n * Creates a function that returns a column value from row data.\n *\n * @param rowIndex - index of a string value in the row data\n * @param type - column type\n * @param def - default value\n * @returns column value to store in a table\n */\nfunction toValueFn(\n  rowIndex: number,\n  type: ColumnType,\n  def: string\n): (row: string[]) => number | string | boolean | null {\n  switch (type) {\n    case 'boolean':\n      return (row: string[]): boolean =>\n        (row[rowIndex] === '' ? def : row[rowIndex]) === 'true'\n    case 'number':\n      return (row: string[]): number | null => {\n        const val = row[rowIndex] === '' ? def : row[rowIndex]\n        return val === '' ? null : Number(val)\n      }\n    case 'time':\n      return (row: string[]): number =>\n        Date.parse(row[rowIndex] === '' ? def : row[rowIndex])\n    default:\n      return (row: string[]): string =>\n        row[rowIndex] === '' ? def : row[rowIndex]\n  }\n}\n\n/**\n * Converts between influxdb-client and giraffe columns types.\n *\n * @param clientType - `@influxdata/influxdb-client` column type\n * @returns `@influxdata/giraffe` column type\n */\nfunction toGiraffeColumnType(clientType: ClientColumnType): ColumnType {\n  // from: 'boolean' | 'unsignedLong' | 'long' | 'double' | 'string' | 'base64Binary' | 'dateTime:RFC3339' | 'duration'\n  // to:   'number' | 'string' | 'time' | 'boolean'\n  switch (clientType) {\n    case 'boolean':\n      return 'boolean'\n    case 'unsignedLong':\n    case 'long':\n    case 'double':\n      return 'number'\n    default:\n      return clientType && clientType.startsWith('dateTime') ? 'time' : 'string'\n  }\n}\n\n/**\n * Creates influxdb-client-js's FluxResultObserver that collects row results to a Table instance\n * @param resolve - called when the Table is collected\n * @param reject - called upon error\n * @param tableOptions - tableOptions allow to filter or even stop the processing of rows, or restrict the columns to collect\n * @returns FluxResultObserver that collects table data from result rows\n */\nexport function createCollector(\n  resolve: (value: FromFluxResult) => void,\n  reject: (reason?: any) => void,\n  tableFactory: GiraffeTableFactory,\n  tableOptions: TableOptions = {}\n): FluxResultObserver<string[]> {\n  const {columns: onlyColumns} = tableOptions\n  const accept = createAcceptRowFunction(tableOptions)\n  const columns: Record<string, Column> = {}\n  let dataColumns: Column[]\n  let lastTableMeta: FluxTableMetaData | undefined = undefined\n  let tableSize = 0\n  let cancellable: Cancellable\n  return {\n    next(row: string[], tableMeta: FluxTableMetaData): void {\n      switch (accept(row, tableMeta)) {\n        case true:\n          break\n        case false:\n          return\n        default:\n          cancellable?.cancel()\n          return\n      }\n      if (tableMeta !== lastTableMeta) {\n        dataColumns = []\n        for (const metaCol of tableMeta.columns) {\n          const type = toGiraffeColumnType(metaCol.dataType)\n          if (onlyColumns && !onlyColumns.includes(metaCol.label)) {\n            continue // exclude this column\n          }\n\n          // handle the rare situation of having columns with the same name, but different type\n          let columnKey = metaCol.label\n          let existingColumn = columns[columnKey]\n          if (existingColumn) {\n            if (existingColumn.multipleTypes) {\n              // multiple column types of the same name already found\n              // use type-specific column key\n              columnKey = `${metaCol.label} (${type})`\n              existingColumn = columns[columnKey]\n            } else if (existingColumn.type !== type) {\n              // move the existing key to a type-specific key\n              columns[`${existingColumn.name} (${existingColumn.type})`] =\n                existingColumn\n              // create a multiType (virtual) column\n              columns[metaCol.label] = {\n                name: metaCol.label,\n                multipleTypes: true,\n                // other values are not used\n              } as Column\n              columnKey = `${metaCol.label} (${type})`\n              existingColumn = columns[columnKey]\n            }\n          }\n          const column = {\n            name: metaCol.label,\n            fluxDataType: metaCol.dataType as FluxDataType,\n            type,\n            data: existingColumn ? existingColumn.data : [],\n            group: existingColumn?.group || metaCol.group,\n            toValue: toValueFn(metaCol.index, type, metaCol.defaultValue),\n          }\n\n          dataColumns.push(column)\n          columns[columnKey] = column\n        }\n        lastTableMeta = tableMeta\n      }\n      for (let i = 0; i < dataColumns.length; i++) {\n        const column = dataColumns[i]\n        // cast is required because of wrong type definition in Giraffe\n        column.data[tableSize] = column.toValue(row) as\n          | string\n          | number\n          | boolean\n      }\n      tableSize++\n    },\n    complete(): void {\n      resolve(createResult(tableSize, columns, tableFactory, tableOptions))\n    },\n    error(e: Error): void {\n      if (e.name === 'AbortError') {\n        // eslint-disable-next-line no-console\n        console.log('queryTable: request aborted:', e)\n        resolve(createResult(tableSize, columns, tableFactory, tableOptions))\n      }\n      reject(e)\n    },\n    useCancellable(val: Cancellable): void {\n      cancellable = val\n    },\n  }\n}\n\n/**\n * Transforms annotated CSV query response to Giraffe's FromFluxResult.\n *\n * @param csv - annotated CSV flux query response\n * @param tableFactory - creates a new Giraffe table\n * @param tableOptions - tableOptions allows to filter or even stop the processing of rows, specify maximum rows or restrict the columns to collect\n * @returns a new FromFluxResult instance\n */\nexport function csvToFromFluxResult(\n  csv: string,\n  tableFactory: GiraffeTableFactory,\n  tableOptions?: TableOptions\n): FromFluxResult {\n  let result: FromFluxResult | undefined\n  let error: Error | undefined = undefined\n  const collector = createCollector(\n    (r) => (result = r),\n    /* istanbul ignore next because error is never thrown */\n    (e) => (error = e),\n    tableFactory,\n    {\n      computeFluxGroupKeyUnion: true,\n      computeResultColumnNames: true,\n      ...tableOptions,\n    }\n  )\n  stringToLines(csv, linesToTables(collector))\n  /* istanbul ignore if error is never thrown */\n  if (error) {\n    throw error\n  } else {\n    return result as FromFluxResult\n  }\n}\n\n/**\n * Transforms annotated CSV query response to Giraffe's Table.\n *\n * @param csv - annotated CSV flux query response\n * @param tableFactory - creates a new Giraffe table\n * @param tableOptions - tableOptions allows to filter or even stop the processing of rows, specify maximum rows or restrict the columns to collect.\n * @returns a new Table instance\n */\nexport function csvToTable(\n  csv: string,\n  tableFactory: GiraffeTableFactory,\n  tableOptions?: TableOptions\n): Table {\n  return csvToFromFluxResult(csv, tableFactory, {\n    computeFluxGroupKeyUnion: false,\n    ...tableOptions,\n  }).table\n}\n","import {ParameterizedQuery, QueryApi} from '@influxdata/influxdb-client'\nimport {Table, FromFluxResult} from '@influxdata/giraffe'\nimport {createCollector, GiraffeTableFactory, TableOptions} from './csvToTable'\n\n/**\n * Executes a flux query and collects results into a Giraffe's Table.\n *\n * @param queryApi - InfluxDB client's QueryApi instance\n * @param query - query to execute\n * @param tableFactory - creates a new Giraffe table\n * @param tableOptions - tableOptions allows to filter or even stop the processing of rows, specify maximum rows or restrict the columns to collect.\n * @returns Promise with query results\n */\nexport function queryToTable(\n  queryApi: QueryApi,\n  query: string | ParameterizedQuery,\n  tableFactory: GiraffeTableFactory,\n  tableOptions?: TableOptions\n): Promise<Table> {\n  return new Promise<FromFluxResult>((resolve, reject) => {\n    queryApi.queryRows(\n      query,\n      createCollector(resolve, reject, tableFactory, tableOptions)\n    )\n  }).then((result) => result.table)\n}\n\n/**\n * Executes a flux query and iterrativelly collects results into a Giraffe's FromFluxResult.\n *\n * @param queryApi - InfluxDB client's QueryApi instance\n * @param query - query to execute\n * @param tableFactory - creates a new Giraffe table\n * @param tableOptions - tableOptions allows to filter or even stop the processing of rows, specify maximum rows or restrict the columns to collect\n * @returns a Promise with query results\n */\nexport function queryToFromFluxResult(\n  queryApi: QueryApi,\n  query: string | ParameterizedQuery,\n  tableFactory: GiraffeTableFactory,\n  tableOptions?: TableOptions\n): Promise<FromFluxResult> {\n  return new Promise<FromFluxResult>((resolve, reject) => {\n    queryApi.queryRows(\n      query,\n      createCollector(resolve, reject, tableFactory, {\n        ...tableOptions,\n        computeFluxGroupKeyUnion: true,\n      })\n    )\n  })\n}\n"],"mappings":"AGGO,IAAMA,EAAN,KAAmB,CAAnB,aAAA,CAKL,KAAQ,OAAS,EAAA,CAKjB,IAAI,OAAiB,CACnB,OAAO,KAAK,MACd,CACA,IAAI,MAAMC,EAAc,CAClBA,GAAO,CAAC,KAAK,eACf,KAAK,aAAe,IAAI,MAAM,EAAE,GAElC,KAAK,OAASA,CAChB,CAKA,WAA0B,CACxB,OAAA,KAAK,MAAQ,GACN,IACT,CAQA,UAAUC,EAA2C,CACnD,GAAIA,GAAS,KACX,OAAA,KAAK,gBAAkB,EAChB,CAAC,EAEV,IAAIC,EAAa,EACbC,EAAa,EACXC,EAAS,KAAK,OAAS,KAAK,aAAe,CAAC,EAC9CC,EAAQ,EACZ,QAASC,EAAI,EAAGA,EAAIL,EAAK,OAAQK,IAAK,CACpC,IAAMC,EAAIN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EAC5B,CAAC,CACH,CACF,CAAC,CACH","names":["LineSplitter","val","line","quoteCount","startIndex","values","count","i","c","start","end","identity","x","typeSerializers","FluxTableColumnImpl","row","_a","UNKNOWN_COLUMN","newFluxTableColumn","IllegalArgumentError","_IllegalArgumentError","message","FluxTableMetaDataImpl","columns","col","i","label","errorOnMissingColumn","IllegalArgumentError","UNKNOWN_COLUMN","row","acc","column","createFluxTableMetaData","linesToTables","consumer","splitter","LineSplitter","expectMeta","firstColumnIndex","lastMeta","retVal","error","line","values","size","newFluxTableColumn","stringToLines","source","target","quoted","start","index","c","end","symbolObservable","QuerySubscription","observer","executor","value","e","_a","noop","completeObserver","next","error","complete","ObservableQuery","decorator","observerOrNext","createEscaper","characters","replacements","value","retVal","from","i","found","createQuotedEscaper","escaper","escape","useProcessHrtime","use","lastMillis","FLUX_VALUE","FluxParameter","fluxValue","createResult","tableLength","columns","tableFactory","computeFluxGroupKeyUnion","computeResultColumnNames","table","fluxGroupKeyUnion","resultColumnNames","key","col","x","QUERY_MAX_TABLE_LENGTH","acceptMaxTableLength","max","size","createAcceptRowFunction","options","maxTableLength","acceptors","row","tableMeta","i","retVal","toValueFn","rowIndex","type","def","val","toGiraffeColumnType","clientType","createCollector","resolve","reject","tableOptions","onlyColumns","accept","dataColumns","lastTableMeta","tableSize","cancellable","metaCol","columnKey","existingColumn","column","e","csvToFromFluxResult","csv","result","error","collector","r","pt","W","csvToTable","queryToTable","queryApi","query","tableFactory","tableOptions","resolve","reject","createCollector","result","queryToFromFluxResult"]}