code:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.print = print;

var _ast = require("@webassemblyjs/ast");

var _long = _interopRequireDefault(require("@xtuc/long"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var compact = false;
var space = " ";

var quote = function quote(str) {
  return "\"".concat(str, "\"");
};

function indent(nb) {
  return Array(nb).fill(space + space).join("");
} // TODO(sven): allow arbitrary ast nodes

function print(n) {
  if (n.type === "Program") {
    return printProgram(n, 0);
  } else {
    throw new Error("Unsupported node in print of type: " + String(n.type));
  }
}

function printProgram(n, depth) {
  return n.body.reduce(function (acc, child) {
    if (child.type === "Module") {
      acc += printModule(child, depth + 1);
    }

    if (child.type === "Func") {
      acc += printFunc(child, depth + 1);
    }

    if (child.type === "BlockComment") {
      acc += printBlockComment(child);
    }

    if (child.type === "LeadingComment") {
      acc += printLeadingComment(child);
    }

    if (compact === false) {
      acc += "\n";
    }

    return acc;
  }, "");
}

function printTypeInstruction(n) {
  var out = "";
  out += "(";
  out += "type";
  out += space;

  if (n.id != null) {
    out += printIndex(n.id);
    out += space;
  }

  out += "(";
  out += "func";
  n.functype.params.forEach(function (param) {
    out += space;
    out += "(";
    out += "param";
    out += space;
    out += printFuncParam(param);
    out += ")";
  });
  n.functype.results.forEach(function (result) {
    out += space;
    out += "(";
    out += "result";
    out += space;
    out += result;
    out += ")";
  });
  out += ")"; // func

  out += ")";
  return out;
}

function printModule(n, depth) {
  var out = "(";
  out += "module";

  if (typeof n.id === "string") {
    out += space;
    out += n.id;
  }

  if (compact === false) {
    out += "\n";
  } else {
    out += space;
  }

  n.fields.forEach(function (field) {
    if (compact === false) {
      out += indent(depth);
    }

    switch (field.type) {
      case "Func":
        {
          out += printFunc(field, depth + 1);
          break;
        }

      case "TypeInstruction":
        {
          out += printTypeInstruction(field);
          break;
        }

      case "Table":
        {
          out += printTable(field);
          break;
        }

      case "Global":
        {
          out += printGlobal(field, depth + 1);
          break;
        }

      case "ModuleExport":
        {
          out += printModuleExport(field);
          break;
        }

      case "ModuleImport":
        {
          out += printModuleImport(field);
          break;
        }

      case "Memory":
        {
          out += printMemory(field);
          break;
        }

      case "BlockComment":
        {
          out += printBlockComment(field);
          break;
        }

      case "LeadingComment":
        {
          out += printLeadingComment(field);
          break;
        }

      case "Start":
        {
          out += printStart(field);
          break;
        }

      case "Elem":
        {
          out += printElem(field, depth);
          break;
        }

      case "Data":
        {
          out += printData(field, depth);
          break;
        }

      default:
        throw new Error("Unsupported node in printModule: " + String(field.type));
    }

    if (compact === false) {
      out += "\n";
    }
  });
  out += ")";
  return out;
}

function printData(n, depth) {
  var out = "";
  out += "(";
  out += "data";
  out += space;
  out += printIndex(n.memoryIndex);
  out += space;
  out += printInstruction(n.offset, depth);
  out += space;
  out += '"';
  n.init.values.forEach(function (_byte) {
    // Avoid non-displayable characters
    if (_byte <= 31 || _byte == 34 || _byte == 92 || _byte >= 127) {
      out += "\\";
      out += ("00" + _byte.toString(16)).substr(-2);
    } else if (_byte > 255) {
      throw new Error("Unsupported byte in data segment: " + _byte);
    } else {
      out += String.fromCharCode(_byte);
    }
  });
  out += '"';
  out += ")";
  return out;
}

function printElem(n, depth) {
  var out = "";
  out += "(";
  out += "elem";
  out += space;
  out += printIndex(n.table);

  var _n$offset = _slicedToArray(n.offset, 1),
      firstOffset = _n$offset[0];

  out += space;
  out += "(";
  out += "offset";
  out += space;
  out += printInstruction(firstOffset, depth);
  out += ")";
  n.funcs.forEach(function (func) {
    out += space;
    out += printIndex(func);
  });
  out += ")";
  return out;
}

function printStart(n) {
  var out = "";
  out += "(";
  out += "start";
  out += space;
  out += printIndex(n.index);
  out += ")";
  return out;
}

function printLeadingComment(n) {
  // Don't print leading comments in compact mode
  if (compact === true) {
    return "";
  }

  var out = "";
  out += ";;";
  out += n.value;
  out += "\n";
  return out;
}

function printBlockComment(n) {
  // Don't print block comments in compact mode
  if (compact === true) {
    return "";
  }

  var out = "";
  out += "(;";
  out += n.value;
  out += ";)";
  out += "\n";
  return out;
}

function printSignature(n) {
  var out = "";
  n.params.forEach(function (param) {
    out += space;
    out += "(";
    out += "param";
    out += space;
    out += printFuncParam(param);
    out += ")";
  });
  n.results.forEach(function (result) {
    out += space;
    out += "(";
    out += "result";
    out += space;
    out += result;
    out += ")";
  });
  return out;
}

function printModuleImportDescr(n) {
  var out = "";

  if (n.type === "FuncImportDescr") {
    out += "(";
    out += "func";

    if ((0, _ast.isAnonymous)(n.id) === false) {
      out += space;
      out += printIdentifier(n.id);
    }

    out += printSignature(n.signature);
    out += ")";
  }

  if (n.type === "GlobalType") {
    out += "(";
    out += "global";
    out += space;
    out += printGlobalType(n);
    out += ")";
  }

  if (n.type === "Table") {
    out += printTable(n);
  }

  return out;
}

function printModuleImport(n) {
  var out = "";
  out += "(";
  out += "import";
  out += space;
  out += quote(n.module);
  out += space;
  out += quote(n.name);
  out += space;
  out += printModuleImportDescr(n.descr);
  out += ")";
  return out;
}

function printGlobalType(n) {
  var out = "";

  if (n.mutability === "var") {
    out += "(";
    out += "mut";
    out += space;
    out += n.valtype;
    out += ")";
  } else {
    out += n.valtype;
  }

  return out;
}

function printGlobal(n, depth) {
  var out = "";
  out += "(";
  out += "global";
  out += space;

  if (n.name != null && (0, _ast.isAnonymous)(n.name) === false) {
    out += printIdentifier(n.name);
    out += space;
  }

  out += printGlobalType(n.globalType);
  out += space;
  n.init.forEach(function (i) {
    out += printInstruction(i, depth + 1);
  });
  out += ")";
  return out;
}

function printTable(n) {
  var out = "";
  out += "(";
  out += "table";
  out += space;

  if (n.name != null && (0, _ast.isAnonymous)(n.name) === false) {
    out += printIdentifier(n.name);
    out += space;
  }

  out += printLimit(n.limits);
  out += space;
  out += n.elementType;
  out += ")";
  return out;
}

function printFuncParam(n) {
  var out = "";

  if (typeof n.id === "string") {
    out += "$" + n.id;
    out += space;
  }

  out += n.valtype;
  return out;
}

function printFunc(n, depth) {
  var out = "";
  out += "(";
  out += "func";

  if (n.name != null) {
    if (n.name.type === "Identifier" && (0, _ast.isAnonymous)(n.name) === false) {
      out += space;
      out += printIdentifier(n.name);
    }
  }

  if (n.signature.type === "Signature") {
    out += printSignature(n.signature);
  } else {
    var index = n.signature;
    out += space;
    out += "(";
    out += "type";
    out += space;
    out += printIndex(index);
    out += ")";
  }

  if (n.body.length > 0) {
    // func is empty since we ignore the default end instruction
    if (n.body.length === 1 && n.body[0].id === "end") {
      out += ")";
      return out;
    }

    if (compact === false) {
      out += "\n";
    }

    n.body.forEach(function (i) {
      if (i.id !== "end") {
        out += indent(depth);
        out += printInstruction(i, depth);

        if (compact === false) {
          out += "\n";
        }
      }
    });
    out += indent(depth - 1) + ")";
  } else {
    out += ")";
  }

  return out;
}

function printInstruction(n, depth) {
  switch (n.type) {
    case "Instr":
      // $FlowIgnore
      return printGenericInstruction(n, depth + 1);

    case "BlockInstruction":
      // $FlowIgnore
      return printBlockInstruction(n, depth + 1);

    case "IfInstruction":
      // $FlowIgnore
      return printIfInstruction(n, depth + 1);

    case "CallInstruction":
      // $FlowIgnore
      return printCallInstruction(n, depth + 1);

    case "CallIndirectInstruction":
      // $FlowIgnore
      return printCallIndirectIntruction(n, depth + 1);

    case "LoopInstruction":
      // $FlowIgnore
      return printLoopInstruction(n, depth + 1);

    default:
      throw new Error("Unsupported instruction: " + JSON.stringify(n.type));
  }
}

function printCallIndirectIntruction(n, depth) {
  var out = "";
  out += "(";
  out += "call_indirect";

  if (n.signature.type === "Signature") {
    out += printSignature(n.signature);
  } else if (n.signature.type === "Identifier") {
    out += space;
    out += "(";
    out += "type";
    out += space;
    out += printIdentifier(n.signature);
    out += ")";
  } else {
    throw new Error("CallIndirectInstruction: unsupported signature " + JSON.stringify(n.signature.type));
  }

  out += space;

  if (n.intrs != null) {
    // $FlowIgnore
    n.intrs.forEach(function (i, index) {
      // $FlowIgnore
      out += printInstruction(i, depth + 1); // $FlowIgnore

      if (index !== n.intrs.length - 1) {
        out += space;
      }
    });
  }

  out += ")";
  return out;
}

function printLoopInstruction(n, depth) {
  var out = "";
  out += "(";
  out += "loop";

  if (n.label != null && (0, _ast.isAnonymous)(n.label) === false) {
    out += space;
    out += printIdentifier(n.label);
  }

  if (typeof n.resulttype === "string") {
    out += space;
    out += "(";
    out += "result";
    out += space;
    out += n.resulttype;
    out += ")";
  }

  if (n.instr.length > 0) {
    n.instr.forEach(function (e) {
      if (compact === false) {
        out += "\n";
      }

      out += indent(depth);
      out += printInstruction(e, depth + 1);
    });

    if (compact === false) {
      out += "\n";
      out += indent(depth - 1);
    }
  }

  out += ")";
  return out;
}

function printCallInstruction(n, depth) {
  var out = "";
  out += "(";
  out += "call";
  out += space;
  out += printIndex(n.index);

  if (_typeof(n.instrArgs) === "object") {
    // $FlowIgnore
    n.instrArgs.forEach(function (arg) {
      out += space;
      out += printFuncInstructionArg(arg, depth + 1);
    });
  }

  out += ")";
  return out;
}

function printIfInstruction(n, depth) {
  var out = "";
  out += "(";
  out += "if";

  if (n.testLabel != null && (0, _ast.isAnonymous)(n.testLabel) === false) {
    out += space;
    out += printIdentifier(n.testLabel);
  }

  if (typeof n.result === "string") {
    out += space;
    out += "(";
    out += "result";
    out += space;
    out += n.result;
    out += ")";
  }

  if (n.test.length > 0) {
    out += space;
    n.test.forEach(function (i) {
      out += printInstruction(i, depth + 1);
    });
  }

  if (n.consequent.length > 0) {
    if (compact === false) {
      out += "\n";
    }

    out += indent(depth);
    out += "(";
    out += "then";
    depth++;
    n.consequent.forEach(function (i) {
      if (compact === false) {
        out += "\n";
      }

      out += indent(depth);
      out += printInstruction(i, depth + 1);
    });
    depth--;

    if (compact === false) {
      out += "\n";
      out += indent(depth);
    }

    out += ")";
  } else {
    if (compact === false) {
      out += "\n";
      out += indent(depth);
    }

    out += "(";
    out += "then";
    out += ")";
  }

  if (n.alternate.length > 0) {
    if (compact === false) {
      out += "\n";
    }

    out += indent(depth);
    out += "(";
    out += "else";
    depth++;
    n.alternate.forEach(function (i) {
      if (compact === false) {
        out += "\n";
      }

      out += indent(depth);
      out += printInstruction(i, depth + 1);
    });
    depth--;

    if (compact === false) {
      out += "\n";
      out += indent(depth);
    }

    out += ")";
  } else {
    if (compact === false) {
      out += "\n";
      out += indent(depth);
    }

    out += "(";
    out += "else";
    out += ")";
  }

  if (compact === false) {
    out += "\n";
    out += indent(depth - 1);
  }

  out += ")";
  return out;
}

function printBlockInstruction(n, depth) {
  var out = "";
  out += "(";
  out += "block";

  if (n.label != null && (0, _ast.isAnonymous)(n.label) === false) {
    out += space;
    out += printIdentifier(n.label);
  }

  if (typeof n.result === "string") {
    out += space;
    out += "(";
    out += "result";
    out += space;
    out += n.result;
    out += ")";
  }

  if (n.instr.length > 0) {
    n.instr.forEach(function (i) {
      if (compact === false) {
        out += "\n";
      }

      out += indent(depth);
      out += printInstruction(i, depth + 1);
    });

    if (compact === false) {
      out += "\n";
    }

    out += indent(depth - 1);
    out += ")";
  } else {
    out += ")";
  }

  return out;
}

function printGenericInstruction(n, depth) {
  var out = "";
  out += "(";

  if (typeof n.object === "string") {
    out += n.object;
    out += ".";
  }

  out += n.id;
  n.args.forEach(function (arg) {
    out += space;
    out += printFuncInstructionArg(arg, depth + 1);
  });

  if (n.namedArgs !== undefined) {
    for (var key in n.namedArgs) {
      out += space + key + "=";
      out += printFuncInstructionArg(n.namedArgs[key], depth + 1);
    }
  }

  out += ")";
  return out;
}

function printLongNumberLiteral(n) {
  if (typeof n.raw === "string") {
    return n.raw;
  }

  var _n$value = n.value,
      low = _n$value.low,
      high = _n$value.high;
  var v = new _long["default"](low, high);
  return v.toString();
}

function printFloatLiteral(n) {
  if (typeof n.raw === "string") {
    return n.raw;
  }

  return String(n.value);
}

function printFuncInstructionArg(n, depth) {
  var out = "";

  if (n.type === "NumberLiteral") {
    out += printNumberLiteral(n);
  }

  if (n.type === "LongNumberLiteral") {
    out += printLongNumberLiteral(n);
  }

  if (n.type === "Identifier" && (0, _ast.isAnonymous)(n) === false) {
    out += printIdentifier(n);
  }

  if (n.type === "ValtypeLiteral") {
    out += n.name;
  }

  if (n.type === "FloatLiteral") {
    out += printFloatLiteral(n);
  }

  if ((0, _ast.isInstruction)(n)) {
    out += printInstruction(n, depth + 1);
  }

  return out;
}

function printNumberLiteral(n) {
  if (typeof n.raw === "string") {
    return n.raw;
  }

  return String(n.value);
}

function printModuleExport(n) {
  var out = "";
  out += "(";
  out += "export";
  out += space;
  out += quote(n.name);

  if (n.descr.exportType === "Func") {
    out += space;
    out += "(";
    out += "func";
    out += space;
    out += printIndex(n.descr.id);
    out += ")";
  } else if (n.descr.exportType === "Global") {
    out += space;
    out += "(";
    out += "global";
    out += space;
    out += printIndex(n.descr.id);
    out += ")";
  } else if (n.descr.exportType === "Memory") {
    out += space;
    out += "(";
    out += "memory";
    out += space;
    out += printIndex(n.descr.id);
    out += ")";
  } else if (n.descr.exportType === "Table") {
    out += space;
    out += "(";
    out += "table";
    out += space;
    out += printIndex(n.descr.id);
    out += ")";
  } else {
    throw new Error("printModuleExport: unknown type: " + n.descr.exportType);
  }

  out += ")";
  return out;
}

function printIdentifier(n) {
  return "$" + n.value;
}

function printIndex(n) {
  if (n.type === "Identifier") {
    return printIdentifier(n);
  } else if (n.type === "NumberLiteral") {
    return printNumberLiteral(n);
  } else {
    throw new Error("Unsupported index: " + n.type);
  }
}

function printMemory(n) {
  var out = "";
  out += "(";
  out += "memory";

  if (n.id != null) {
    out += space;
    out += printIndex(n.id);
    out += space;
  }

  out += printLimit(n.limits);
  out += ")";
  return out;
}

function printLimit(n) {
  var out = "";
  out += n.min + "";

  if (n.max != null) {
    out += space;
    out += String(n.max);

    if (n.shared === true) {
      out += " shared";
    }
  }

  return out;
}


@webassemblyjs/wast-printer

description: WebAssembly text format printer

keywords: webassembly javascript ast compiler printer wast

test: mocha

author: Sven Sauleau

license: MIT

type: git

access: public

license: mit


code:
# ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]

[travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg
[travis-url]: https://travis-ci.org/feross/ieee754
[npm-image]: https://img.shields.io/npm/v/ieee754.svg
[npm-url]: https://npmjs.org/package/ieee754
[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg
[downloads-url]: https://npmjs.org/package/ieee754
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[standard-url]: https://standardjs.com

[![saucelabs][saucelabs-image]][saucelabs-url]

[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg
[saucelabs-url]: https://saucelabs.com/u/ieee754

### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object.

## install

```
npm install ieee754
```

## methods

`var ieee754 = require('ieee754')`

The `ieee754` object has the following functions:

```
ieee754.read = function (buffer, offset, isLE, mLen, nBytes)
ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes)
```

The arguments mean the following:

- buffer = the buffer
- offset = offset into the buffer
- value = value to set (only for `write`)
- isLe = is little endian?
- mLen = mantissa length
- nBytes = number of bytes

## what is ieee754?

The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point).

## license

BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc.


code:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.read = read;
exports.write = write;

function read(buffer, offset, isLE, mLen, nBytes) {
  var e, m;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var nBits = -7;
  var i = isLE ? nBytes - 1 : 0;
  var d = isLE ? -1 : 1;
  var s = buffer[offset + i];
  i += d;
  e = s & (1 << -nBits) - 1;
  s >>= -nBits;
  nBits += eLen;

  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & (1 << -nBits) - 1;
  e >>= -nBits;
  nBits += mLen;

  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : (s ? -1 : 1) * Infinity;
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }

  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}

function write(buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  var i = isLE ? 0 : nBytes - 1;
  var d = isLE ? 1 : -1;
  var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  value = Math.abs(value);

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);

    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }

    if (e + eBias >= 1) {
      value += rt / c;
    } else {
      value += rt * Math.pow(2, 1 - eBias);
    }

    if (value * c >= 2) {
      e++;
      c /= 2;
    }

    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = (value * c - 1) * Math.pow(2, mLen);
      e = e + eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = e << mLen | m;
  eLen += mLen;

  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128;
}


code:
export function read(buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

export function write(buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


description: Read/write IEEE754 floating point numbers from/to a Buffer or array-like object

keywords:
IEEE 754
buffer
convert
floating point
ieee754

test: standard && npm run test-node && npm run test-browser

test-browser: airtap -- test/*.js

test-browser-local: airtap --local -- test/*.js

test-node: tape test/*.js

prepublish: babel --plugins @babel/plugin-transform-modules-commonjs index.js -o dist/index.cjs.js


code:
long.js
=======

A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library)
for stand-alone use and extended with unsigned support.

[![npm](https://img.shields.io/npm/v/long.svg)](https://www.npmjs.com/package/long) [![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js)

Background
----------

As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers
whose magnitude is no greater than 253 are representable in the Number type", which is "representing the
doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic".
The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)
in JavaScript is 253-1.

Example: 264-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**.

Furthermore, bitwise operators in JavaScript "deal only with integers in the range −231 through
231−1, inclusive, or in the range 0 through 232−1, inclusive. These operators accept any value of
the Number type but first convert each such value to one of 232 integer values."

In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full
64 bits. This is where long.js comes into play.

Usage
-----

The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available.

```javascript
var Long = require("long");

var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF);

console.log(longVal.toString());
...
```

API
---

### Constructor

* new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)

  Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs.

### Fields

* Long#**low**: `number`

  The low 32 bits as a signed value.

* Long#**high**: `number`

  The high 32 bits as a signed value.

* Long#**unsigned**: `boolean`

  Whether unsigned or not.

### Constants

* Long.**ZERO**: `Long`

  Signed zero.

* Long.**ONE**: `Long`

  Signed one.

* Long.**NEG_ONE**: `Long`

  Signed negative one.

* Long.**UZERO**: `Long`

  Unsigned zero.

* Long.**UONE**: `Long`

  Unsigned one.

* Long.**MAX_VALUE**: `Long`

  Maximum signed value.

* Long.**MIN_VALUE**: `Long`

  Minimum signed value.

* Long.**MAX_UNSIGNED_VALUE**: `Long`

  Maximum unsigned value.

### Utility

* Long.**isLong**(obj: `*`): `boolean`

  Tests if the specified object is a Long.

* Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`

  Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits.

* Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`

  Creates a Long from its byte representation.

* Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`

  Creates a Long from its little endian byte representation.

* Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`

  Creates a Long from its big endian byte representation.

* Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`

  Returns a Long representing the given 32 bit integer value.

* Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`

  Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.

* Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)

  Long.**fromString**(str: `string`, radix: `number`)

  Returns a Long representation of the given string, written using the specified radix.

* Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`

  Converts the specified value to a Long using the appropriate from* function for its type.

### Methods

* Long#**add**(addend: `Long | number | string`): `Long`

  Returns the sum of this and the specified Long.

* Long#**and**(other: `Long | number | string`): `Long`

  Returns the bitwise AND of this Long and the specified.

* Long#**compare**/**comp**(other: `Long | number | string`): `number`

  Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater.

* Long#**divide**/**div**(divisor: `Long | number | string`): `Long`

  Returns this Long divided by the specified.

* Long#**equals**/**eq**(other: `Long | number | string`): `boolean`

  Tests if this Long's value equals the specified's.

* Long#**getHighBits**(): `number`

  Gets the high 32 bits as a signed integer.

* Long#**getHighBitsUnsigned**(): `number`

  Gets the high 32 bits as an unsigned integer.

* Long#**getLowBits**(): `number`

  Gets the low 32 bits as a signed integer.

* Long#**getLowBitsUnsigned**(): `number`

  Gets the low 32 bits as an unsigned integer.

* Long#**getNumBitsAbs**(): `number`

  Gets the number of bits needed to represent the absolute value of this Long.

* Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`

  Tests if this Long's value is greater than the specified's.

* Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`

  Tests if this Long's value is greater than or equal the specified's.

* Long#**isEven**(): `boolean`

  Tests if this Long's value is even.

* Long#**isNegative**(): `boolean`

  Tests if this Long's value is negative.

* Long#**isOdd**(): `boolean`

  Tests if this Long's value is odd.

* Long#**isPositive**(): `boolean`

  Tests if this Long's value is positive.

* Long#**isZero**/**eqz**(): `boolean`

  Tests if this Long's value equals zero.

* Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`

  Tests if this Long's value is less than the specified's.

* Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`

  Tests if this Long's value is less than or equal the specified's.

* Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`

  Returns this Long modulo the specified.

* Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`

  Returns the product of this and the specified Long.

* Long#**negate**/**neg**(): `Long`

  Negates this Long's value.

* Long#**not**(): `Long`

  Returns the bitwise NOT of this Long.

* Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`

  Tests if this Long's value differs from the specified's.

* Long#**or**(other: `Long | number | string`): `Long`

  Returns the bitwise OR of this Long and the specified.

* Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`

  Returns this Long with bits shifted to the left by the given amount.

* Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`

  Returns this Long with bits arithmetically shifted to the right by the given amount.

* Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`

  Returns this Long with bits logically shifted to the right by the given amount.

* Long#**rotateLeft**/**rotl**(numBits: `Long | number | string`): `Long`

  Returns this Long with bits rotated to the left by the given amount.

* Long#**rotateRight**/**rotr**(numBits: `Long | number | string`): `Long`

  Returns this Long with bits rotated to the right by the given amount.

* Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`

  Returns the difference of this and the specified Long.

* Long#**toBytes**(le?: `boolean`): `number[]`

  Converts this Long to its byte representation.

* Long#**toBytesLE**(): `number[]`

  Converts this Long to its little endian byte representation.

* Long#**toBytesBE**(): `number[]`

  Converts this Long to its big endian byte representation.

* Long#**toInt**(): `number`

  Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.

* Long#**toNumber**(): `number`

  Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).

* Long#**toSigned**(): `Long`

  Converts this Long to signed.

* Long#**toString**(radix?: `number`): `string`

  Converts the Long to a string written in the specified radix.

* Long#**toUnsigned**(): `Long`

  Converts this Long to unsigned.

* Long#**xor**(other: `Long | number | string`): `Long`

  Returns the bitwise XOR of this Long and the given one.

WebAssembly support
-------------------

[WebAssembly](http://webassembly.org) supports 64-bit integer arithmetic out of the box, hence a [tiny WebAssembly module](./src/wasm.wat) is used to compute operations like multiplication, division and remainder more efficiently (slow operations like division are around twice as fast), falling back to floating point based computations in JavaScript where WebAssembly is not yet supported, e.g., in older versions of node.

Building
--------

To build an UMD bundle to `dist/long.js`, run:

```
$> npm install
$> npm run build
```

Running the [tests](./tests):

```
$> npm test
```


code:
export = Long;
export as namespace Long;

declare namespace Long { }

declare class Long {
    /**
     * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as signed integers. See the from* functions below for more convenient ways of constructing Longs.
     */
    constructor(low: number, high?: number, unsigned?: boolean);

    /**
     * Maximum unsigned value.
     */
    static MAX_UNSIGNED_VALUE: Long;

    /**
     * Maximum signed value.
     */
    static MAX_VALUE: Long;

    /**
     * Minimum signed value.
     */
    static MIN_VALUE: Long;

    /**
     * Signed negative one.
     */
    static NEG_ONE: Long;

    /**
     * Signed one.
     */
    static ONE: Long;

    /**
     * Unsigned one.
     */
    static UONE: Long;

    /**
     * Unsigned zero.
     */
    static UZERO: Long;

    /**
     * Signed zero
     */
    static ZERO: Long;

    /**
     * The high 32 bits as a signed value.
     */
    high: number;

    /**
     * The low 32 bits as a signed value.
     */
    low: number;

    /**
     * Whether unsigned or not.
     */
    unsigned: boolean;

    /**
     * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits.
     */
    static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;

    /**
     * Returns a Long representing the given 32 bit integer value.
     */
    static fromInt(value: number, unsigned?: boolean): Long;

    /**
     * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
     */
    static fromNumber(value: number, unsigned?: boolean): Long;

    /**
     * Returns a Long representation of the given string, written using the specified radix.
     */
    static fromString(str: string, unsigned?: boolean | number, radix?: number): Long;

    /**
     * Creates a Long from its byte representation.
     */
    static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long;

    /**
     * Creates a Long from its little endian byte representation.
     */
    static fromBytesLE(bytes: number[], unsigned?: boolean): Long;

    /**
     * Creates a Long from its big endian byte representation.
     */
    static fromBytesBE(bytes: number[], unsigned?: boolean): Long;

    /**
     * Tests if the specified object is a Long.
     */
    static isLong(obj: any): obj is Long;

    /**
     * Converts the specified value to a Long.
     */
    static fromValue(val: Long | number | string | {low: number, high: number, unsigned: boolean}, unsigned?: boolean): Long;

    /**
     * Returns the sum of this and the specified Long.
     */
    add(addend: number | Long | string): Long;

    /**
     * Returns the bitwise AND of this Long and the specified.
     */
    and(other: Long | number | string): Long;

    /**
     * Compares this Long's value with the specified's.
     */
    compare(other: Long | number | string): number;

    /**
     * Compares this Long's value with the specified's.
     */
    comp(other: Long | number | string): number;

    /**
     * Returns this Long divided by the specified.
     */
    divide(divisor: Long | number | string): Long;

    /**
     * Returns this Long divided by the specified.
     */
    div(divisor: Long | number | string): Long;

    /**
     * Tests if this Long's value equals the specified's.
     */
    equals(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value equals the specified's.
     */
    eq(other: Long | number | string): boolean;

    /**
     * Gets the high 32 bits as a signed integer.
     */
    getHighBits(): number;

    /**
     * Gets the high 32 bits as an unsigned integer.
     */
    getHighBitsUnsigned(): number;

    /**
     * Gets the low 32 bits as a signed integer.
     */
    getLowBits(): number;

    /**
     * Gets the low 32 bits as an unsigned integer.
     */
    getLowBitsUnsigned(): number;

    /**
     * Gets the number of bits needed to represent the absolute value of this Long.
     */
    getNumBitsAbs(): number;

    /**
     * Tests if this Long's value is greater than the specified's.
     */
    greaterThan(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is greater than the specified's.
     */
    gt(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is greater than or equal the specified's.
     */
    greaterThanOrEqual(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is greater than or equal the specified's.
     */
    gte(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is greater than or equal the specified's.
     */
    ge(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is even.
     */
    isEven(): boolean;

    /**
     * Tests if this Long's value is negative.
     */
    isNegative(): boolean;

    /**
     * Tests if this Long's value is odd.
     */
    isOdd(): boolean;

    /**
     * Tests if this Long's value is positive.
     */
    isPositive(): boolean;

    /**
     * Tests if this Long's value equals zero.
     */
    isZero(): boolean;

    /**
     * Tests if this Long's value equals zero.
     */
    eqz(): boolean;

    /**
     * Tests if this Long's value is less than the specified's.
     */
    lessThan(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is less than the specified's.
     */
    lt(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is less than or equal the specified's.
     */
    lessThanOrEqual(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is less than or equal the specified's.
     */
    lte(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value is less than or equal the specified's.
     */
    le(other: Long | number | string): boolean;

    /**
     * Returns this Long modulo the specified.
     */
    modulo(other: Long | number | string): Long;

    /**
     * Returns this Long modulo the specified.
     */
    mod(other: Long | number | string): Long;

    /**
     * Returns this Long modulo the specified.
     */
    rem(other: Long | number | string): Long;

    /**
     * Returns the product of this and the specified Long.
     */
    multiply(multiplier: Long | number | string): Long;

    /**
     * Returns the product of this and the specified Long.
     */
    mul(multiplier: Long | number | string): Long;

    /**
     * Negates this Long's value.
     */
    negate(): Long;

    /**
     * Negates this Long's value.
     */
    neg(): Long;

    /**
     * Returns the bitwise NOT of this Long.
     */
    not(): Long;

    /**
     * Tests if this Long's value differs from the specified's.
     */
    notEquals(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value differs from the specified's.
     */
    neq(other: Long | number | string): boolean;

    /**
     * Tests if this Long's value differs from the specified's.
     */
    ne(other: Long | number | string): boolean;

    /**
     * Returns the bitwise OR of this Long and the specified.
     */
    or(other: Long | number | string): Long;

    /**
     * Returns this Long with bits shifted to the left by the given amount.
     */
    shiftLeft(numBits: number | Long): Long;

    /**
     * Returns this Long with bits shifted to the left by the given amount.
     */
    shl(numBits: number | Long): Long;

    /**
     * Returns this Long with bits arithmetically shifted to the right by the given amount.
     */
    shiftRight(numBits: number | Long): Long;

    /**
     * Returns this Long with bits arithmetically shifted to the right by the given amount.
     */
    shr(numBits: number | Long): Long;

    /**
     * Returns this Long with bits logically shifted to the right by the given amount.
     */
    shiftRightUnsigned(numBits: number | Long): Long;

    /**
     * Returns this Long with bits logically shifted to the right by the given amount.
     */
    shru(numBits: number | Long): Long;

    /**
     * Returns this Long with bits logically shifted to the right by the given amount.
     */
    shr_u(numBits: number | Long): Long;

    /**
     * Returns this Long with bits rotated to the left by the given amount.
     */
    rotateLeft(numBits: number | Long): Long;

    /**
     * Returns this Long with bits rotated to the left by the given amount.
     */
    rotl(numBits: number | Long): Long;

    /**
     * Returns this Long with bits rotated to the right by the given amount.
     */
    rotateRight(numBits: number | Long): Long;

    /**
     * Returns this Long with bits rotated to the right by the given amount.
     */
    rotr(numBits: number | Long): Long;

    /**
     * Returns the difference of this and the specified Long.
     */
    subtract(subtrahend: number | Long | string): Long;

    /**
     * Returns the difference of this and the specified Long.
     */
    sub(subtrahend: number | Long |string): Long;

    /**
     * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
     */
    toInt(): number;

    /**
     * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
     */
    toNumber(): number;

    /**
     * Converts this Long to its byte representation.
     */

    toBytes(le?: boolean): number[];

    /**
     * Converts this Long to its little endian byte representation.
     */

    toBytesLE(): number[];

    /**
     * Converts this Long to its big endian byte representation.
     */

    toBytesBE(): number[];

    /**
     * Converts this Long to signed.
     */
    toSigned(): Long;

    /**
     * Converts the Long to a string written in the specified radix.
     */
    toString(radix?: number): string;

    /**
     * Converts this Long to unsigned.
     */
    toUnsigned(): Long;

    /**
     * Returns the bitwise XOR of this Long and the given one.
     */
    xor(other: Long | number | string): Long;
}


code: module.exports = require("./src/long");


@xtuc/long

author: Daniel Wirtz <dcode@dcode.io>

description: A Long class for representing a 64-bit two's-complement integer value.

build: webpack

test: node tests


code:
1.3.8 / 2022-02-02
==================

  * deps: mime-types@~2.1.34
    - deps: mime-db@~1.51.0
  * deps: negotiator@0.6.3

1.3.7 / 2019-04-29
==================

  * deps: negotiator@0.6.2
    - Fix sorting charset, encoding, and language with extra parameters

1.3.6 / 2019-04-28
==================

  * deps: mime-types@~2.1.24
    - deps: mime-db@~1.40.0

1.3.5 / 2018-02-28
==================

  * deps: mime-types@~2.1.18
    - deps: mime-db@~1.33.0

1.3.4 / 2017-08-22
==================

  * deps: mime-types@~2.1.16
    - deps: mime-db@~1.29.0

1.3.3 / 2016-05-02
==================

  * deps: mime-types@~2.1.11
    - deps: mime-db@~1.23.0
  * deps: negotiator@0.6.1
    - perf: improve `Accept` parsing speed
    - perf: improve `Accept-Charset` parsing speed
    - perf: improve `Accept-Encoding` parsing speed
    - perf: improve `Accept-Language` parsing speed

1.3.2 / 2016-03-08
==================

  * deps: mime-types@~2.1.10
    - Fix extension of `application/dash+xml`
    - Update primary extension for `audio/mp4`
    - deps: mime-db@~1.22.0

1.3.1 / 2016-01-19
==================

  * deps: mime-types@~2.1.9
    - deps: mime-db@~1.21.0

1.3.0 / 2015-09-29
==================

  * deps: mime-types@~2.1.7
    - deps: mime-db@~1.19.0
  * deps: negotiator@0.6.0
    - Fix including type extensions in parameters in `Accept` parsing
    - Fix parsing `Accept` parameters with quoted equals
    - Fix parsing `Accept` parameters with quoted semicolons
    - Lazy-load modules from main entry point
    - perf: delay type concatenation until needed
    - perf: enable strict mode
    - perf: hoist regular expressions
    - perf: remove closures getting spec properties
    - perf: remove a closure from media type parsing
    - perf: remove property delete from media type parsing

1.2.13 / 2015-09-06
===================

  * deps: mime-types@~2.1.6
    - deps: mime-db@~1.18.0

1.2.12 / 2015-07-30
===================

  * deps: mime-types@~2.1.4
    - deps: mime-db@~1.16.0

1.2.11 / 2015-07-16
===================

  * deps: mime-types@~2.1.3
    - deps: mime-db@~1.15.0

1.2.10 / 2015-07-01
===================

  * deps: mime-types@~2.1.2
    - deps: mime-db@~1.14.0

1.2.9 / 2015-06-08
==================

  * deps: mime-types@~2.1.1
    - perf: fix deopt during mapping

1.2.8 / 2015-06-07
==================

  * deps: mime-types@~2.1.0
    - deps: mime-db@~1.13.0
  * perf: avoid argument reassignment & argument slice
  * perf: avoid negotiator recursive construction
  * perf: enable strict mode
  * perf: remove unnecessary bitwise operator

1.2.7 / 2015-05-10
==================

  * deps: negotiator@0.5.3
    - Fix media type parameter matching to be case-insensitive

1.2.6 / 2015-05-07
==================

  * deps: mime-types@~2.0.11
    - deps: mime-db@~1.9.1
  * deps: negotiator@0.5.2
    - Fix comparing media types with quoted values
    - Fix splitting media types with quoted commas

1.2.5 / 2015-03-13
==================

  * deps: mime-types@~2.0.10
    - deps: mime-db@~1.8.0

1.2.4 / 2015-02-14
==================

  * Support Node.js 0.6
  * deps: mime-types@~2.0.9
    - deps: mime-db@~1.7.0
  * deps: negotiator@0.5.1
    - Fix preference sorting to be stable for long acceptable lists

1.2.3 / 2015-01-31
==================

  * deps: mime-types@~2.0.8
    - deps: mime-db@~1.6.0

1.2.2 / 2014-12-30
==================

  * deps: mime-types@~2.0.7
    - deps: mime-db@~1.5.0

1.2.1 / 2014-12-30
==================

  * deps: mime-types@~2.0.5
    - deps: mime-db@~1.3.1

1.2.0 / 2014-12-19
==================

  * deps: negotiator@0.5.0
    - Fix list return order when large accepted list
    - Fix missing identity encoding when q=0 exists
    - Remove dynamic building of Negotiator class

1.1.4 / 2014-12-10
==================

  * deps: mime-types@~2.0.4
    - deps: mime-db@~1.3.0

1.1.3 / 2014-11-09
==================

  * deps: mime-types@~2.0.3
    - deps: mime-db@~1.2.0

1.1.2 / 2014-10-14
==================

  * deps: negotiator@0.4.9
    - Fix error when media type has invalid parameter

1.1.1 / 2014-09-28
==================

  * deps: mime-types@~2.0.2
    - deps: mime-db@~1.1.0
  * deps: negotiator@0.4.8
    - Fix all negotiations to be case-insensitive
    - Stable sort preferences of same quality according to client order

1.1.0 / 2014-09-02
==================

  * update `mime-types`

1.0.7 / 2014-07-04
==================

  * Fix wrong type returned from `type` when match after unknown extension

1.0.6 / 2014-06-24
==================

  * deps: negotiator@0.4.7

1.0.5 / 2014-06-20
==================

 * fix crash when unknown extension given

1.0.4 / 2014-06-19
==================

  * use `mime-types`

1.0.3 / 2014-06-11
==================

  * deps: negotiator@0.4.6
    - Order by specificity when quality is the same

1.0.2 / 2014-05-29
==================

  * Fix interpretation when header not in request
  * deps: pin negotiator@0.4.5

1.0.1 / 2014-01-18
==================

  * Identity encoding isn't always acceptable
  * deps: negotiator@~0.4.0

1.0.0 / 2013-12-27
==================

  * Genesis


code:
# accepts

[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]

Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.

In addition to negotiator, it allows:

- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
  as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`

## Installation

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```sh
$ npm install accepts
```

## API

```js
var accepts = require('accepts')
```

### accepts(req)

Create a new `Accepts` object for the given `req`.

#### .charset(charsets)

Return the first accepted charset. If nothing in `charsets` is accepted,
then `false` is returned.

#### .charsets()

Return the charsets that the request accepts, in the order of the client's
preference (most preferred first).

#### .encoding(encodings)

Return the first accepted encoding. If nothing in `encodings` is accepted,
then `false` is returned.

#### .encodings()

Return the encodings that the request accepts, in the order of the client's
preference (most preferred first).

#### .language(languages)

Return the first accepted language. If nothing in `languages` is accepted,
then `false` is returned.

#### .languages()

Return the languages that the request accepts, in the order of the client's
preference (most preferred first).

#### .type(types)

Return the first accepted type (and it is returned as the same text as what
appears in the `types` array). If nothing in `types` is accepted, then `false`
is returned.

The `types` array can contain full MIME types or file extensions. Any value
that is not a full MIME types is passed to `require('mime-types').lookup`.

#### .types()

Return the types that the request accepts, in the order of the client's
preference (most preferred first).

## Examples

### Simple type negotiation

This simple example shows how to use `accepts` to return a different typed
respond body based on what the client wants to accept. The server lists it's
preferences in order and will get back the best match between the client and
server.

```js
var accepts = require('accepts')
var http = require('http')

function app (req, res) {
  var accept = accepts(req)

  // the order of this list is significant; should be server preferred order
  switch (accept.type(['json', 'html'])) {
    case 'json':
      res.setHeader('Content-Type', 'application/json')
      res.write('{"hello":"world!"}')
      break
    case 'html':
      res.setHeader('Content-Type', 'text/html')
      res.write('<b>hello, world!</b>')
      break
    default:
      // the fallback is text/plain, so no need to specify it above
      res.setHeader('Content-Type', 'text/plain')
      res.write('hello, world!')
      break
  }

  res.end()
}

http.createServer(app).listen(3000)
```

You can test this out with the cURL program:
```sh
curl -I -H'Accept: text/html' http://localhost:3000/
```

## License

[MIT](LICENSE)

[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
[node-version-image]: https://badgen.net/npm/node/accepts
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
[npm-url]: https://npmjs.org/package/accepts
[npm-version-image]: https://badgen.net/npm/v/accepts


code:
/*!
 * accepts
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict'

/**
 * Module dependencies.
 * @private
 */

var Negotiator = require('negotiator')
var mime = require('mime-types')

/**
 * Module exports.
 * @public
 */

module.exports = Accepts

/**
 * Create a new Accepts object for the given req.
 *
 * @param {object} req
 * @public
 */

function Accepts (req) {
  if (!(this instanceof Accepts)) {
    return new Accepts(req)
  }

  this.headers = req.headers
  this.negotiator = new Negotiator(req)
}

/**
 * Check if the given `type(s)` is acceptable, returning
 * the best match when true, otherwise `undefined`, in which
 * case you should respond with 406 "Not Acceptable".
 *
 * The `type` value may be a single mime type string
 * such as "application/json", the extension name
 * such as "json" or an array `["json", "html", "text/plain"]`. When a list
 * or array is given the _best_ match, if any is returned.
 *
 * Examples:
 *
 *     // Accept: text/html
 *     this.types('html');
 *     // => "html"
 *
 *     // Accept: text/*, application/json
 *     this.types('html');
 *     // => "html"
 *     this.types('text/html');
 *     // => "text/html"
 *     this.types('json', 'text');
 *     // => "json"
 *     this.types('application/json');
 *     // => "application/json"
 *
 *     // Accept: text/*, application/json
 *     this.types('image/png');
 *     this.types('png');
 *     // => undefined
 *
 *     // Accept: text/*;q=.5, application/json
 *     this.types(['html', 'json']);
 *     this.types('html', 'json');
 *     // => "json"
 *
 * @param {String|Array} types...
 * @return {String|Array|Boolean}
 * @public
 */

Accepts.prototype.type =
Accepts.prototype.types = function (types_) {
  var types = types_

  // support flattened arguments
  if (types && !Array.isArray(types)) {
    types = new Array(arguments.length)
    for (var i = 0; i < types.length; i++) {
      types[i] = arguments[i]
    }
  }

  // no types, return all requested types
  if (!types || types.length === 0) {
    return this.negotiator.mediaTypes()
  }

  // no accept header, return first given type
  if (!this.headers.accept) {
    return types[0]
  }

  var mimes = types.map(extToMime)
  var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
  var first = accepts[0]

  return first
    ? types[mimes.indexOf(first)]
    : false
}

/**
 * Return accepted encodings or best fit based on `encodings`.
 *
 * Given `Accept-Encoding: gzip, deflate`
 * an array sorted by quality is returned:
 *
 *     ['gzip', 'deflate']
 *
 * @param {String|Array} encodings...
 * @return {String|Array}
 * @public
 */

Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings_) {
  var encodings = encodings_

  // support flattened arguments
  if (encodings && !Array.isArray(encodings)) {
    encodings = new Array(arguments.length)
    for (var i = 0; i < encodings.length; i++) {
      encodings[i] = arguments[i]
    }
  }

  // no encodings, return all requested encodings
  if (!encodings || encodings.length === 0) {
    return this.negotiator.encodings()
  }

  return this.negotiator.encodings(encodings)[0] || false
}

/**
 * Return accepted charsets or best fit based on `charsets`.
 *
 * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
 * an array sorted by quality is returned:
 *
 *     ['utf-8', 'utf-7', 'iso-8859-1']
 *
 * @param {String|Array} charsets...
 * @return {String|Array}
 * @public
 */

Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets_) {
  var charsets = charsets_

  // support flattened arguments
  if (charsets && !Array.isArray(charsets)) {
    charsets = new Array(arguments.length)
    for (var i = 0; i < charsets.length; i++) {
      charsets[i] = arguments[i]
    }
  }

  // no charsets, return all requested charsets
  if (!charsets || charsets.length === 0) {
    return this.negotiator.charsets()
  }

  return this.negotiator.charsets(charsets)[0] || false
}

/**
 * Return accepted languages or best fit based on `langs`.
 *
 * Given `Accept-Language: en;q=0.8, es, pt`
 * an array sorted by quality is returned:
 *
 *     ['es', 'pt', 'en']
 *
 * @param {String|Array} langs...
 * @return {Array|String}
 * @public
 */

Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (languages_) {
  var languages = languages_

  // support flattened arguments
  if (languages && !Array.isArray(languages)) {
    languages = new Array(arguments.length)
    for (var i = 0; i < languages.length; i++) {
      languages[i] = arguments[i]
    }
  }

  // no languages, return all requested languages
  if (!languages || languages.length === 0) {
    return this.negotiator.languages()
  }

  return this.negotiator.languages(languages)[0] || false
}

/**
 * Convert extnames to mime.
 *
 * @param {String} type
 * @return {String}
 * @private
 */

function extToMime (type) {
  return type.indexOf('/') === -1
    ? mime.lookup(type)
    : type
}

/**
 * Check if mime is valid.
 *
 * @param {String} type
 * @return {String}
 * @private
 */

function validMime (type) {
  return typeof type === 'string'
}


accepts

description: Higher-level content negotiation

contributors: Douglas Christopher Wilson <doug@somethingdoug.com>

contributors: Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)

repository: jshttp/accepts

lint: eslint .

test: mocha --reporter spec --check-leaks --bail test/

test-ci: nyc --reporter=lcov --reporter=text npm test

test-cov: nyc --reporter=html --reporter=text npm test

keywords: content negotiation accept accepts


code:
# Support for import attributes in acorn

## Install

```
yarn add acorn-import-attributes
```

## Usage

This module provides a plugin that can be used to extend the Acorn Parser class:

```js
const {Parser} = require('acorn');
const {importAttributes} = require('acorn-import-attributes');
Parser.extend(importAttributes).parse('...');
```

## License

This plugin is released under an MIT License.


code:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.importAttributesOrAssertions = exports.importAttributes = exports.importAssertions = void 0;
var _acorn = _interopRequireWildcard(require("acorn"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
const leftCurlyBrace = "{".charCodeAt(0);
const space = " ".charCodeAt(0);
const withKeyword = "with";
const assertKeyword = "assert";
const FUNC_STATEMENT = 1,
  FUNC_HANGING_STATEMENT = 2,
  FUNC_NULLABLE_ID = 4;
const importAttributes = exports.importAttributes = plugin({
  keyword: "with"
});
const importAssertions = exports.importAssertions = plugin({
  keyword: "assert"
});
const importAttributesOrAssertions = exports.importAttributesOrAssertions = plugin({
  keyword: "with-assert"
});
function plugin(options) {
  return function (Parser) {
    return pluginImpl(options, Parser);
  };
}
function pluginImpl(options, Parser) {
  // Use supplied version acorn version if present, to avoid
  // reference mismatches due to different acorn versions. This
  // allows this plugin to be used with Rollup which supplies
  // its own internal version of acorn and thereby sidesteps
  // the package manager.
  const acorn = Parser.acorn || _acorn;
  const {
    tokTypes: tt,
    TokenType
  } = acorn;
  const {
    keyword
  } = options;
  const isWithKeyword = keyword.includes(withKeyword);
  const isAssertKeyword = keyword.includes(assertKeyword);
  const isWithOrAssertKeyword = isWithKeyword && isAssertKeyword;
  return class extends Parser {
    constructor(...args) {
      super(...args);
      this.withToken = isWithKeyword && new TokenType(withKeyword);
      this.assertToken = isAssertKeyword && new TokenType(assertKeyword);
    }
    _codeAt(i) {
      return this.input.charCodeAt(i);
    }
    _eat(t) {
      if (this.type !== t) {
        this.unexpected();
      }
      this.next();
    }
    _matchKeywordToken() {
      return isWithOrAssertKeyword && (this.type === this.withToken || this.type === this.assertToken) || isWithKeyword && this.type === this.withToken || isAssertKeyword && this.type === this.assertToken;
    }
    _getProperty() {
      if (isWithOrAssertKeyword) {
        return this.type === this.withToken ? "attributes" : "assertions";
      }
      return isWithKeyword ? "attributes" : "assertions";
    }
    readToken(code) {
      let i = 0;
      let keyword;
      let token;
      if (isWithOrAssertKeyword) {
        if (this.input.slice(this.pos, this.pos + withKeyword.length) === withKeyword) {
          keyword = withKeyword;
          token = this.withToken;
        } else if (this.input.slice(this.pos, this.pos + assertKeyword.length) === assertKeyword) {
          keyword = assertKeyword;
          token = this.assertToken;
        } else {
          return super.readToken(code);
        }
        i += keyword.length;
      } else {
        keyword = isWithKeyword ? withKeyword : assertKeyword;
        token = isWithKeyword ? this.withToken : this.assertToken;
        for (; i < keyword.length; i++) {
          if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
            return super.readToken(code);
          }
        }
      }

      // ensure that the keyword is at the correct location
      // ie `with{...` or `with {...`
      for (;; i++) {
        if (this._codeAt(this.pos + i) === leftCurlyBrace) {
          // Found '{'
          break;
        } else if (this._codeAt(this.pos + i) === space) {
          // white space is allowed between `with` and `{`, so continue.
          continue;
        } else {
          return super.readToken(code);
        }
      }

      // If we're inside a dynamic import expression we'll parse
      // the `with` keyword as a standard object property name
      // ie `import(""./foo.json", { with: { type: "json" } })`
      if (this.type.label === "{") {
        return super.readToken(code);
      }
      this.pos += keyword.length;
      return this.finishToken(token);
    }
    parseDynamicImport(node) {
      this.next(); // skip `(`

      // Parse node.source.
      node.source = this.parseMaybeAssign();
      if (this.eat(tt.comma)) {
        const expr = this.parseExpression();
        node.arguments = [expr];
      }
      this._eat(tt.parenR);
      return this.finishNode(node, "ImportExpression");
    }

    // ported from acorn/src/statement.js pp.parseExport
    parseExport(node, exports) {
      this.next();
      // export * from '...'
      if (this.eat(tt.star)) {
        if (this.options.ecmaVersion >= 11) {
          if (this.eatContextual("as")) {
            node.exported = this.parseIdent(true);
            this.checkExport(exports, node.exported.name, this.lastTokStart);
          } else {
            node.exported = null;
          }
        }
        this.expectContextual("from");
        if (this.type !== tt.string) {
          this.unexpected();
        }
        node.source = this.parseExprAtom();
        if (this._matchKeywordToken()) {
          const property = this._getProperty();
          this.next();
          const attributes = this.parseImportAttributes();
          if (attributes) {
            node[property] = attributes;
          }
        }
        this.semicolon();
        return this.finishNode(node, "ExportAllDeclaration");
      }
      if (this.eat(tt._default)) {
        // export default ...
        this.checkExport(exports, "default", this.lastTokStart);
        var isAsync;
        if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
          var fNode = this.startNode();
          this.next();
          if (isAsync) {
            this.next();
          }
          node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
        } else if (this.type === tt._class) {
          var cNode = this.startNode();
          node.declaration = this.parseClass(cNode, "nullableID");
        } else {
          node.declaration = this.parseMaybeAssign();
          this.semicolon();
        }
        return this.finishNode(node, "ExportDefaultDeclaration");
      }
      // export var|const|let|function|class ...
      if (this.shouldParseExportStatement()) {
        node.declaration = this.parseStatement(null);
        if (node.declaration.type === "VariableDeclaration") {
          this.checkVariableExport(exports, node.declaration.declarations);
        } else {
          this.checkExport(exports, node.declaration.id.name, node.declaration.id.start);
        }
        node.specifiers = [];
        node.source = null;
      } else {
        // export { x, y as z } [from '...']
        node.declaration = null;
        node.specifiers = this.parseExportSpecifiers(exports);
        if (this.eatContextual("from")) {
          if (this.type !== tt.string) {
            this.unexpected();
          }
          node.source = this.parseExprAtom();
          if (this._matchKeywordToken()) {
            const property = this._getProperty();
            this.next();
            const attributes = this.parseImportAttributes();
            if (attributes) {
              node[property] = attributes;
            }
          }
        } else {
          for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
            // check for keywords used as local names
            var spec = list[i];
            this.checkUnreserved(spec.local);
            // check if export is defined
            this.checkLocalExport(spec.local);
          }
          node.source = null;
        }
        this.semicolon();
      }
      return this.finishNode(node, "ExportNamedDeclaration");
    }
    parseImport(node) {
      this.next();
      // import '...'
      if (this.type === tt.string) {
        node.specifiers = [];
        node.source = this.parseExprAtom();
      } else {
        node.specifiers = this.parseImportSpecifiers();
        this.expectContextual("from");
        node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
      }
      if (this._matchKeywordToken()) {
        const property = this._getProperty();
        this.next();
        const attributes = this.parseImportAttributes();
        if (attributes) {
          node[property] = attributes;
        }
      }
      this.semicolon();
      return this.finishNode(node, "ImportDeclaration");
    }
    parseImportAttributes() {
      this._eat(tt.braceL);
      const attrs = this.parsewithEntries();
      this._eat(tt.braceR);
      return attrs;
    }
    parsewithEntries() {
      const attrs = [];
      const attrNames = new Set();
      do {
        if (this.type === tt.braceR) {
          break;
        }
        const node = this.startNode();

        // parse withionKey : IdentifierName, StringLiteral
        let withionKeyNode;
        if (this.type === tt.string) {
          withionKeyNode = this.parseLiteral(this.value);
        } else {
          withionKeyNode = this.parseIdent(true);
        }
        this.next();
        node.key = withionKeyNode;

        // check if we already have an entry for an attribute
        // if a duplicate entry is found, throw an error
        // for now this logic will come into play only when someone declares `type` twice
        if (attrNames.has(node.key.name)) {
          this.raise(this.pos, "Duplicated key in attributes");
        }
        attrNames.add(node.key.name);
        if (this.type !== tt.string) {
          this.raise(this.pos, "Only string is supported as an attribute value");
        }
        node.value = this.parseLiteral(this.value);
        attrs.push(this.finishNode(node, "ImportAttribute"));
      } while (this.eat(tt.comma));
      return attrs;
    }
  };
}


code:
import * as _acorn from "acorn";

const leftCurlyBrace = "{".charCodeAt(0);
const space = " ".charCodeAt(0);

const withKeyword = "with";
const assertKeyword = "assert";
const FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4

export const importAttributes = plugin({ keyword: "with" });
export const importAssertions = plugin({ keyword: "assert" });
export const importAttributesOrAssertions = plugin({ keyword: "with-assert" })

function plugin(options) {
  return function(Parser) {
    return pluginImpl(options, Parser);
  };
}

function pluginImpl(options, Parser) {
  // Use supplied version acorn version if present, to avoid
  // reference mismatches due to different acorn versions. This
  // allows this plugin to be used with Rollup which supplies
  // its own internal version of acorn and thereby sidesteps
  // the package manager.
  const acorn = Parser.acorn || _acorn;
  const { tokTypes: tt, TokenType } = acorn;
  const { keyword } = options;
  const isWithKeyword = keyword.includes(withKeyword);
  const isAssertKeyword = keyword.includes(assertKeyword);
  const isWithOrAssertKeyword = isWithKeyword && isAssertKeyword;

  return class extends Parser {
    constructor(...args) {
      super(...args);
      this.withToken = isWithKeyword && new TokenType(withKeyword);
      this.assertToken = isAssertKeyword && new TokenType(assertKeyword);
    }

    _codeAt(i) {
      return this.input.charCodeAt(i);
    }

    _eat(t) {
      if (this.type !== t) {
        this.unexpected();
      }
      this.next();
    }

    _matchKeywordToken() {
      return (isWithOrAssertKeyword && (this.type === this.withToken || this.type === this.assertToken))
        || (isWithKeyword && this.type === this.withToken)
        || (isAssertKeyword && this.type === this.assertToken)
    }

    _getProperty() {
      if (isWithOrAssertKeyword) {
        return this.type === this.withToken ? "attributes" : "assertions";
      }
      return isWithKeyword ? "attributes" : "assertions";
    }

    readToken(code) {
      let i = 0;
      let keyword;
      let token;
      if (isWithOrAssertKeyword) {
        if (this.input.slice(this.pos, this.pos + withKeyword.length) === withKeyword) {
          keyword = withKeyword;
          token = this.withToken;
        } else if (this.input.slice(this.pos, this.pos + assertKeyword.length) === assertKeyword) {
          keyword = assertKeyword;
          token = this.assertToken;
        } else {
          return super.readToken(code);
        }
        i += keyword.length;
      } else {
        keyword = isWithKeyword ? withKeyword : assertKeyword;
        token = isWithKeyword ? this.withToken : this.assertToken;
        for (; i < keyword.length; i++) {
          if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
            return super.readToken(code);
          }
        }
      }

      // ensure that the keyword is at the correct location
      // ie `with{...` or `with {...`
      for (;; i++) {
        if (this._codeAt(this.pos + i) === leftCurlyBrace) {
          // Found '{'
          break;
        } else if (this._codeAt(this.pos + i) === space) {
          // white space is allowed between `with` and `{`, so continue.
          continue;
        } else {
          return super.readToken(code);
        }
      }

      // If we're inside a dynamic import expression we'll parse
      // the `with` keyword as a standard object property name
      // ie `import(""./foo.json", { with: { type: "json" } })`
      if (this.type.label === "{") {
        return super.readToken(code);
      }

      this.pos += keyword.length;
      return this.finishToken(token);
    }

    parseDynamicImport(node) {
      this.next(); // skip `(`

      // Parse node.source.
      node.source = this.parseMaybeAssign();

      if (this.eat(tt.comma)) {
        const expr = this.parseExpression();
        node.arguments = [expr];
      }
      this._eat(tt.parenR);
      return this.finishNode(node, "ImportExpression");
    }

    // ported from acorn/src/statement.js pp.parseExport
    parseExport(node, exports) {
      this.next();
      // export * from '...'
      if (this.eat(tt.star)) {
        if (this.options.ecmaVersion >= 11) {
          if (this.eatContextual("as")) {
            node.exported = this.parseIdent(true);
            this.checkExport(exports, node.exported.name, this.lastTokStart);
          } else {
            node.exported = null;
          }
        }
        this.expectContextual("from");
        if (this.type !== tt.string) { this.unexpected(); }
        node.source = this.parseExprAtom();

        if (this._matchKeywordToken()) {
          const property = this._getProperty();
          this.next();
          const attributes = this.parseImportAttributes();
          if (attributes) {
            node[property] = attributes;
          }
        }

        this.semicolon();
        return this.finishNode(node, "ExportAllDeclaration")
      }
      if (this.eat(tt._default)) { // export default ...
        this.checkExport(exports, "default", this.lastTokStart);
        var isAsync;
        if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
          var fNode = this.startNode();
          this.next();
          if (isAsync) { this.next(); }
          node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
        } else if (this.type === tt._class) {
          var cNode = this.startNode();
          node.declaration = this.parseClass(cNode, "nullableID");
        } else {
          node.declaration = this.parseMaybeAssign();
          this.semicolon();
        }
        return this.finishNode(node, "ExportDefaultDeclaration")
      }
      // export var|const|let|function|class ...
      if (this.shouldParseExportStatement()) {
        node.declaration = this.parseStatement(null);
        if (node.declaration.type === "VariableDeclaration")
          { this.checkVariableExport(exports, node.declaration.declarations); }
        else
          { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
        node.specifiers = [];
        node.source = null;
      } else { // export { x, y as z } [from '...']
        node.declaration = null;
        node.specifiers = this.parseExportSpecifiers(exports);
        if (this.eatContextual("from")) {
          if (this.type !== tt.string) { this.unexpected(); }
          node.source = this.parseExprAtom();

          if (this._matchKeywordToken()) {
            const property = this._getProperty();
            this.next();
            const attributes = this.parseImportAttributes();
            if (attributes) {
              node[property] = attributes;
            }
          }
        } else {
          for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
            // check for keywords used as local names
            var spec = list[i];

            this.checkUnreserved(spec.local);
            // check if export is defined
            this.checkLocalExport(spec.local);
          }

          node.source = null;
        }
        this.semicolon();
      }
      return this.finishNode(node, "ExportNamedDeclaration")
    }

    parseImport(node) {
      this.next();
      // import '...'
      if (this.type === tt.string) {
        node.specifiers = [];
        node.source = this.parseExprAtom();
      } else {
        node.specifiers = this.parseImportSpecifiers();
        this.expectContextual("from");
        node.source =
          this.type === tt.string ? this.parseExprAtom() : this.unexpected();
      }

      if (this._matchKeywordToken()) {
        const property = this._getProperty();
        this.next();
        const attributes = this.parseImportAttributes();
        if (attributes) {
          node[property] = attributes;
        }
      }
      this.semicolon();
      return this.finishNode(node, "ImportDeclaration");
    }

    parseImportAttributes() {
      this._eat(tt.braceL);
      const attrs = this.parsewithEntries();
      this._eat(tt.braceR);
      return attrs;
    }

    parsewithEntries() {
      const attrs = [];
      const attrNames = new Set();

      do {
        if (this.type === tt.braceR) {
          break;
        }

        const node = this.startNode();

        // parse withionKey : IdentifierName, StringLiteral
        let withionKeyNode;
        if (this.type === tt.string) {
          withionKeyNode = this.parseLiteral(this.value);
        } else {
          withionKeyNode = this.parseIdent(true);
        }
        this.next();
        node.key = withionKeyNode;

        // check if we already have an entry for an attribute
        // if a duplicate entry is found, throw an error
        // for now this logic will come into play only when someone declares `type` twice
        if (attrNames.has(node.key.name)) {
          this.raise(this.pos, "Duplicated key in attributes");
        }
        attrNames.add(node.key.name);

        if (this.type !== tt.string) {
          this.raise(
            this.pos,
            "Only string is supported as an attribute value"
          );
        }

        node.value = this.parseLiteral(this.value);

        attrs.push(this.finishNode(node, "ImportAttribute"));
      } while (this.eat(tt.comma));

      return attrs;
    }
  };
}


acorn-import-attributes

description: Support for import attributes in acorn

build: babel ./src --out-dir ./lib && node post-build.js

prepublishOnly: npm run build

test: mocha ./test/index.js

test:test262: node run_test262.js

watch: babel ./src --out-dir ./lib --watch

author: Sven Sauleau <sven@sauleau.com>

files: lib src


code:
# Acorn-JSX

[![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx)
[![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx)

This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript.

It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools.

## Transpiler

Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood.

## Usage

Requiring this module provides you with an Acorn plugin that you can use like this:

```javascript
var acorn = require("acorn");
var jsx = require("acorn-jsx");
acorn.Parser.extend(jsx()).parse("my(<jsx/>, 'code');");
```

Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in `<namespace:Object.Property />`, so it was deprecated in `acorn-jsx@3.0`. If you still want to opt-in to support of such constructions, you can pass the following option:

```javascript
acorn.Parser.extend(jsx({ allowNamespacedObjects: true }))
```

Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely:

```javascript
acorn.Parser.extend(jsx({ allowNamespaces: false }))
```

Note that by default `allowNamespaces` is enabled for spec compliancy.

## License

This plugin is issued under the [MIT license](./LICENSE).


code:
import { Parser } from 'acorn'

declare const jsx: (options?: jsx.Options) => (BaseParser: typeof Parser) => typeof Parser;

declare namespace jsx {
  interface Options {
    allowNamespacedObjects?: boolean;
    allowNamespaces?: boolean;
  }
}

export = jsx;


code:
'use strict';

const XHTMLEntities = require('./xhtml');

const hexNumber = /^[\da-fA-F]+$/;
const decimalNumber = /^\d+$/;

// The map to `acorn-jsx` tokens from `acorn` namespace objects.
const acornJsxMap = new WeakMap();

// Get the original tokens for the given `acorn` namespace object.
function getJsxTokens(acorn) {
  acorn = acorn.Parser.acorn || acorn;
  let acornJsx = acornJsxMap.get(acorn);
  if (!acornJsx) {
    const tt = acorn.tokTypes;
    const TokContext = acorn.TokContext;
    const TokenType = acorn.TokenType;
    const tc_oTag = new TokContext('<tag', false);
    const tc_cTag = new TokContext('</tag', false);
    const tc_expr = new TokContext('<tag>...</tag>', true, true);
    const tokContexts = {
      tc_oTag: tc_oTag,
      tc_cTag: tc_cTag,
      tc_expr: tc_expr
    };
    const tokTypes = {
      jsxName: new TokenType('jsxName'),
      jsxText: new TokenType('jsxText', {beforeExpr: true}),
      jsxTagStart: new TokenType('jsxTagStart', {startsExpr: true}),
      jsxTagEnd: new TokenType('jsxTagEnd')
    };

    tokTypes.jsxTagStart.updateContext = function() {
      this.context.push(tc_expr); // treat as beginning of JSX expression
      this.context.push(tc_oTag); // start opening tag context
      this.exprAllowed = false;
    };
    tokTypes.jsxTagEnd.updateContext = function(prevType) {
      let out = this.context.pop();
      if (out === tc_oTag && prevType === tt.slash || out === tc_cTag) {
        this.context.pop();
        this.exprAllowed = this.curContext() === tc_expr;
      } else {
        this.exprAllowed = true;
      }
    };

    acornJsx = { tokContexts: tokContexts, tokTypes: tokTypes };
    acornJsxMap.set(acorn, acornJsx);
  }

  return acornJsx;
}

// Transforms JSX element name to string.

function getQualifiedJSXName(object) {
  if (!object)
    return object;

  if (object.type === 'JSXIdentifier')
    return object.name;

  if (object.type === 'JSXNamespacedName')
    return object.namespace.name + ':' + object.name.name;

  if (object.type === 'JSXMemberExpression')
    return getQualifiedJSXName(object.object) + '.' +
    getQualifiedJSXName(object.property);
}

module.exports = function(options) {
  options = options || {};
  return function(Parser) {
    return plugin({
      allowNamespaces: options.allowNamespaces !== false,
      allowNamespacedObjects: !!options.allowNamespacedObjects
    }, Parser);
  };
};

// This is `tokTypes` of the peer dep.
// This can be different instances from the actual `tokTypes` this plugin uses.
Object.defineProperty(module.exports, "tokTypes", {
  get: function get_tokTypes() {
    return getJsxTokens(require("acorn")).tokTypes;
  },
  configurable: true,
  enumerable: true
});

function plugin(options, Parser) {
  const acorn = Parser.acorn || require("acorn");
  const acornJsx = getJsxTokens(acorn);
  const tt = acorn.tokTypes;
  const tok = acornJsx.tokTypes;
  const tokContexts = acorn.tokContexts;
  const tc_oTag = acornJsx.tokContexts.tc_oTag;
  const tc_cTag = acornJsx.tokContexts.tc_cTag;
  const tc_expr = acornJsx.tokContexts.tc_expr;
  const isNewLine = acorn.isNewLine;
  const isIdentifierStart = acorn.isIdentifierStart;
  const isIdentifierChar = acorn.isIdentifierChar;

  return class extends Parser {
    // Expose actual `tokTypes` and `tokContexts` to other plugins.
    static get acornJsx() {
      return acornJsx;
    }

    // Reads inline JSX contents token.
    jsx_readToken() {
      let out = '', chunkStart = this.pos;
      for (;;) {
        if (this.pos >= this.input.length)
          this.raise(this.start, 'Unterminated JSX contents');
        let ch = this.input.charCodeAt(this.pos);

        switch (ch) {
        case 60: // '<'
        case 123: // '{'
          if (this.pos === this.start) {
            if (ch === 60 && this.exprAllowed) {
              ++this.pos;
              return this.finishToken(tok.jsxTagStart);
            }
            return this.getTokenFromCode(ch);
          }
          out += this.input.slice(chunkStart, this.pos);
          return this.finishToken(tok.jsxText, out);

        case 38: // '&'
          out += this.input.slice(chunkStart, this.pos);
          out += this.jsx_readEntity();
          chunkStart = this.pos;
          break;

        case 62: // '>'
        case 125: // '}'
          this.raise(
            this.pos,
            "Unexpected token `" + this.input[this.pos] + "`. Did you mean `" +
              (ch === 62 ? ">" : "}") + "` or " + "`{\"" + this.input[this.pos] + "\"}" + "`?"
          );

        default:
          if (isNewLine(ch)) {
            out += this.input.slice(chunkStart, this.pos);
            out += this.jsx_readNewLine(true);
            chunkStart = this.pos;
          } else {
            ++this.pos;
          }
        }
      }
    }

    jsx_readNewLine(normalizeCRLF) {
      let ch = this.input.charCodeAt(this.pos);
      let out;
      ++this.pos;
      if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
        ++this.pos;
        out = normalizeCRLF ? '\n' : '\r\n';
      } else {
        out = String.fromCharCode(ch);
      }
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }

      return out;
    }

    jsx_readString(quote) {
      let out = '', chunkStart = ++this.pos;
      for (;;) {
        if (this.pos >= this.input.length)
          this.raise(this.start, 'Unterminated string constant');
        let ch = this.input.charCodeAt(this.pos);
        if (ch === quote) break;
        if (ch === 38) { // '&'
          out += this.input.slice(chunkStart, this.pos);
          out += this.jsx_readEntity();
          chunkStart = this.pos;
        } else if (isNewLine(ch)) {
          out += this.input.slice(chunkStart, this.pos);
          out += this.jsx_readNewLine(false);
          chunkStart = this.pos;
        } else {
          ++this.pos;
        }
      }
      out += this.input.slice(chunkStart, this.pos++);
      return this.finishToken(tt.string, out);
    }

    jsx_readEntity() {
      let str = '', count = 0, entity;
      let ch = this.input[this.pos];
      if (ch !== '&')
        this.raise(this.pos, 'Entity must start with an ampersand');
      let startPos = ++this.pos;
      while (this.pos < this.input.length && count++ < 10) {
        ch = this.input[this.pos++];
        if (ch === ';') {
          if (str[0] === '#') {
            if (str[1] === 'x') {
              str = str.substr(2);
              if (hexNumber.test(str))
                entity = String.fromCharCode(parseInt(str, 16));
            } else {
              str = str.substr(1);
              if (decimalNumber.test(str))
                entity = String.fromCharCode(parseInt(str, 10));
            }
          } else {
            entity = XHTMLEntities[str];
          }
          break;
        }
        str += ch;
      }
      if (!entity) {
        this.pos = startPos;
        return '&';
      }
      return entity;
    }

    // Read a JSX identifier (valid tag or attribute name).
    //
    // Optimized version since JSX identifiers can't contain
    // escape characters and so can be read as single slice.
    // Also assumes that first character was already checked
    // by isIdentifierStart in readToken.

    jsx_readWord() {
      let ch, start = this.pos;
      do {
        ch = this.input.charCodeAt(++this.pos);
      } while (isIdentifierChar(ch) || ch === 45); // '-'
      return this.finishToken(tok.jsxName, this.input.slice(start, this.pos));
    }

    // Parse next token as JSX identifier

    jsx_parseIdentifier() {
      let node = this.startNode();
      if (this.type === tok.jsxName)
        node.name = this.value;
      else if (this.type.keyword)
        node.name = this.type.keyword;
      else
        this.unexpected();
      this.next();
      return this.finishNode(node, 'JSXIdentifier');
    }

    // Parse namespaced identifier.

    jsx_parseNamespacedName() {
      let startPos = this.start, startLoc = this.startLoc;
      let name = this.jsx_parseIdentifier();
      if (!options.allowNamespaces || !this.eat(tt.colon)) return name;
      var node = this.startNodeAt(startPos, startLoc);
      node.namespace = name;
      node.name = this.jsx_parseIdentifier();
      return this.finishNode(node, 'JSXNamespacedName');
    }

    // Parses element name in any form - namespaced, member
    // or single identifier.

    jsx_parseElementName() {
      if (this.type === tok.jsxTagEnd) return '';
      let startPos = this.start, startLoc = this.startLoc;
      let node = this.jsx_parseNamespacedName();
      if (this.type === tt.dot && node.type === 'JSXNamespacedName' && !options.allowNamespacedObjects) {
        this.unexpected();
      }
      while (this.eat(tt.dot)) {
        let newNode = this.startNodeAt(startPos, startLoc);
        newNode.object = node;
        newNode.property = this.jsx_parseIdentifier();
        node = this.finishNode(newNode, 'JSXMemberExpression');
      }
      return node;
    }

    // Parses any type of JSX attribute value.

    jsx_parseAttributeValue() {
      switch (this.type) {
      case tt.braceL:
        let node = this.jsx_parseExpressionContainer();
        if (node.expression.type === 'JSXEmptyExpression')
          this.raise(node.start, 'JSX attributes must only be assigned a non-empty expression');
        return node;

      case tok.jsxTagStart:
      case tt.string:
        return this.parseExprAtom();

      default:
        this.raise(this.start, 'JSX value should be either an expression or a quoted JSX text');
      }
    }

    // JSXEmptyExpression is unique type since it doesn't actually parse anything,
    // and so it should start at the end of last read token (left brace) and finish
    // at the beginning of the next one (right brace).

    jsx_parseEmptyExpression() {
      let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);
      return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc);
    }

    // Parses JSX expression enclosed into curly brackets.

    jsx_parseExpressionContainer() {
      let node = this.startNode();
      this.next();
      node.expression = this.type === tt.braceR
        ? this.jsx_parseEmptyExpression()
        : this.parseExpression();
      this.expect(tt.braceR);
      return this.finishNode(node, 'JSXExpressionContainer');
    }

    // Parses following JSX attribute name-value pair.

    jsx_parseAttribute() {
      let node = this.startNode();
      if (this.eat(tt.braceL)) {
        this.expect(tt.ellipsis);
        node.argument = this.parseMaybeAssign();
        this.expect(tt.braceR);
        return this.finishNode(node, 'JSXSpreadAttribute');
      }
      node.name = this.jsx_parseNamespacedName();
      node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
      return this.finishNode(node, 'JSXAttribute');
    }

    // Parses JSX opening tag starting after '<'.

    jsx_parseOpeningElementAt(startPos, startLoc) {
      let node = this.startNodeAt(startPos, startLoc);
      node.attributes = [];
      let nodeName = this.jsx_parseElementName();
      if (nodeName) node.name = nodeName;
      while (this.type !== tt.slash && this.type !== tok.jsxTagEnd)
        node.attributes.push(this.jsx_parseAttribute());
      node.selfClosing = this.eat(tt.slash);
      this.expect(tok.jsxTagEnd);
      return this.finishNode(node, nodeName ? 'JSXOpeningElement' : 'JSXOpeningFragment');
    }

    // Parses JSX closing tag starting after '</'.

    jsx_parseClosingElementAt(startPos, startLoc) {
      let node = this.startNodeAt(startPos, startLoc);
      let nodeName = this.jsx_parseElementName();
      if (nodeName) node.name = nodeName;
      this.expect(tok.jsxTagEnd);
      return this.finishNode(node, nodeName ? 'JSXClosingElement' : 'JSXClosingFragment');
    }

    // Parses entire JSX element, including it's opening tag
    // (starting after '<'), attributes, contents and closing tag.

    jsx_parseElementAt(startPos, startLoc) {
      let node = this.startNodeAt(startPos, startLoc);
      let children = [];
      let openingElement = this.jsx_parseOpeningElementAt(startPos, startLoc);
      let closingElement = null;

      if (!openingElement.selfClosing) {
        contents: for (;;) {
          switch (this.type) {
          case tok.jsxTagStart:
            startPos = this.start; startLoc = this.startLoc;
            this.next();
            if (this.eat(tt.slash)) {
              closingElement = this.jsx_parseClosingElementAt(startPos, startLoc);
              break contents;
            }
            children.push(this.jsx_parseElementAt(startPos, startLoc));
            break;

          case tok.jsxText:
            children.push(this.parseExprAtom());
            break;

          case tt.braceL:
            children.push(this.jsx_parseExpressionContainer());
            break;

          default:
            this.unexpected();
          }
        }
        if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
          this.raise(
            closingElement.start,
            'Expected corresponding JSX closing tag for <' + getQualifiedJSXName(openingElement.name) + '>');
        }
      }
      let fragmentOrElement = openingElement.name ? 'Element' : 'Fragment';

      node['opening' + fragmentOrElement] = openingElement;
      node['closing' + fragmentOrElement] = closingElement;
      node.children = children;
      if (this.type === tt.relational && this.value === "<") {
        this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag");
      }
      return this.finishNode(node, 'JSX' + fragmentOrElement);
    }

    // Parse JSX text

    jsx_parseText() {
      let node = this.parseLiteral(this.value);
      node.type = "JSXText";
      return node;
    }

    // Parses entire JSX element from current position.

    jsx_parseElement() {
      let startPos = this.start, startLoc = this.startLoc;
      this.next();
      return this.jsx_parseElementAt(startPos, startLoc);
    }

    parseExprAtom(refShortHandDefaultPos) {
      if (this.type === tok.jsxText)
        return this.jsx_parseText();
      else if (this.type === tok.jsxTagStart)
        return this.jsx_parseElement();
      else
        return super.parseExprAtom(refShortHandDefaultPos);
    }

    readToken(code) {
      let context = this.curContext();

      if (context === tc_expr) return this.jsx_readToken();

      if (context === tc_oTag || context === tc_cTag) {
        if (isIdentifierStart(code)) return this.jsx_readWord();

        if (code == 62) {
          ++this.pos;
          return this.finishToken(tok.jsxTagEnd);
        }

        if ((code === 34 || code === 39) && context == tc_oTag)
          return this.jsx_readString(code);
      }

      if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) {
        ++this.pos;
        return this.finishToken(tok.jsxTagStart);
      }
      return super.readToken(code);
    }

    updateContext(prevType) {
      if (this.type == tt.braceL) {
        var curContext = this.curContext();
        if (curContext == tc_oTag) this.context.push(tokContexts.b_expr);
        else if (curContext == tc_expr) this.context.push(tokContexts.b_tmpl);
        else super.updateContext(prevType);
        this.exprAllowed = true;
      } else if (this.type === tt.slash && prevType === tok.jsxTagStart) {
        this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore
        this.context.push(tc_cTag); // reconsider as closing tag context
        this.exprAllowed = false;
      } else {
        return super.updateContext(prevType);
      }
    }
  };
}


acorn-jsx

description: Modern, fast React.js JSX parser

test: node test/run.js