UNPKG

@rwesa/payu-ble

Version:

A flexible, smart Bluetooth Low Energy challenge system for secure device connections

1,321 lines (1,313 loc) 298 kB
import { promises, statSync, createReadStream } from 'fs'; import { basename } from 'path'; import Stream, { pipeline as pipeline$1, PassThrough } from 'stream'; import { promisify, deprecate, types } from 'util'; import { Buffer as Buffer$1 } from 'buffer'; import http from 'http'; import { isIP } from 'net'; import { format } from 'url'; import https from 'https'; import zlib from 'zlib'; import { exec } from 'child_process'; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __typeError = (msg) => { throw TypeError(msg); }; var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x2)(function(x2) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x2 + '" is not supported'); }); var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); // node_modules/lodash.debounce/index.js var require_lodash = __commonJS({ "node_modules/lodash.debounce/index.js"(exports, module) { var FUNC_ERROR_TEXT = "Expected a function"; var NAN = 0 / 0; var symbolTag = "[object Symbol]"; var reTrim = /^\s+|\s+$/g; var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; var reIsBinary = /^0b[01]+$/i; var reIsOctal = /^0o[0-7]+$/i; var freeParseInt = parseInt; var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal || freeSelf || Function("return this")(); var objectProto = Object.prototype; var objectToString = objectProto.toString; var nativeMax = Math.max; var nativeMin = Math.min; var now = function() { return root.Date.now(); }; function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = "maxWait" in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = "trailing" in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = void 0; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { lastInvokeTime = time; timerId = setTimeout(timerExpired, wait); return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall; return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = void 0; if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = void 0; return result; } function cancel() { if (timerId !== void 0) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = void 0; } function flush() { return timerId === void 0 ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === void 0) { return leadingEdge(lastCallTime); } if (maxing) { timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === void 0) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } function isObject(value) { var type = typeof value; return !!value && (type == "object" || type == "function"); } function isObjectLike(value) { return !!value && typeof value == "object"; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; } function toNumber(value) { if (typeof value == "number") { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == "function" ? value.valueOf() : value; value = isObject(other) ? other + "" : other; } if (typeof value != "string") { return value === 0 ? value : +value; } value = value.replace(reTrim, ""); var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } module.exports = debounce; } }); // node_modules/file-uri-to-path/index.js var require_file_uri_to_path = __commonJS({ "node_modules/file-uri-to-path/index.js"(exports, module) { var sep = __require("path").sep || "/"; module.exports = fileUriToPath; function fileUriToPath(uri) { if ("string" != typeof uri || uri.length <= 7 || "file://" != uri.substring(0, 7)) { throw new TypeError("must pass in a file:// URI to convert to a file path"); } var rest = decodeURI(uri.substring(7)); var firstSlash = rest.indexOf("/"); var host = rest.substring(0, firstSlash); var path = rest.substring(firstSlash + 1); if ("localhost" == host) host = ""; if (host) { host = sep + sep + host; } path = path.replace(/^(.+)\|/, "$1:"); if (sep == "\\") { path = path.replace(/\//g, "\\"); } if (/^.+\:/.test(path)) ; else { path = sep + path; } return host + path; } } }); // node_modules/bindings/bindings.js var require_bindings = __commonJS({ "node_modules/bindings/bindings.js"(exports, module) { var fs2 = __require("fs"); var path = __require("path"); var fileURLToPath = require_file_uri_to_path(); var join = path.join; var dirname = path.dirname; var exists = fs2.accessSync && function(path2) { try { fs2.accessSync(path2); } catch (e2) { return false; } return true; } || fs2.existsSync || path.existsSync; var defaults = { arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ", compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled", platform: process.platform, arch: process.arch, nodePreGyp: "node-v" + process.versions.modules + "-" + process.platform + "-" + process.arch, version: process.versions.node, bindings: "bindings.node", try: [ // node-gyp's linked version in the "build" dir ["module_root", "build", "bindings"], // node-waf and gyp_addon (a.k.a node-gyp) ["module_root", "build", "Debug", "bindings"], ["module_root", "build", "Release", "bindings"], // Debug files, for development (legacy behavior, remove for node v0.9) ["module_root", "out", "Debug", "bindings"], ["module_root", "Debug", "bindings"], // Release files, but manually compiled (legacy behavior, remove for node v0.9) ["module_root", "out", "Release", "bindings"], ["module_root", "Release", "bindings"], // Legacy from node-waf, node <= 0.4.x ["module_root", "build", "default", "bindings"], // Production "Release" buildtype binary (meh...) ["module_root", "compiled", "version", "platform", "arch", "bindings"], // node-qbs builds ["module_root", "addon-build", "release", "install-root", "bindings"], ["module_root", "addon-build", "debug", "install-root", "bindings"], ["module_root", "addon-build", "default", "install-root", "bindings"], // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch} ["module_root", "lib", "binding", "nodePreGyp", "bindings"] ] }; function bindings(opts) { if (typeof opts == "string") { opts = { bindings: opts }; } else if (!opts) { opts = {}; } Object.keys(defaults).map(function(i3) { if (!(i3 in opts)) opts[i3] = defaults[i3]; }); if (!opts.module_root) { opts.module_root = exports.getRoot(exports.getFileName()); } if (path.extname(opts.bindings) != ".node") { opts.bindings += ".node"; } var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; var tries = [], i2 = 0, l = opts.try.length, n, b, err; for (; i2 < l; i2++) { n = join.apply( null, opts.try[i2].map(function(p) { return opts[p] || p; }) ); tries.push(n); try { b = opts.path ? requireFunc.resolve(n) : requireFunc(n); if (!opts.path) { b.path = n; } return b; } catch (e2) { if (e2.code !== "MODULE_NOT_FOUND" && e2.code !== "QUALIFIED_PATH_RESOLUTION_FAILED" && !/not find/i.test(e2.message)) { throw e2; } } } err = new Error( "Could not locate the bindings file. Tried:\n" + tries.map(function(a) { return opts.arrow + a; }).join("\n") ); err.tries = tries; throw err; } module.exports = exports = bindings; exports.getFileName = function getFileName(calling_file) { var origPST = Error.prepareStackTrace, origSTL = Error.stackTraceLimit, dummy = {}, fileName; Error.stackTraceLimit = 10; Error.prepareStackTrace = function(e2, st) { for (var i2 = 0, l = st.length; i2 < l; i2++) { fileName = st[i2].getFileName(); if (fileName !== __filename) { if (calling_file) { if (fileName !== calling_file) { return; } } else { return; } } } }; Error.captureStackTrace(dummy); dummy.stack; Error.prepareStackTrace = origPST; Error.stackTraceLimit = origSTL; var fileSchema = "file://"; if (fileName.indexOf(fileSchema) === 0) { fileName = fileURLToPath(fileName); } return fileName; }; exports.getRoot = function getRoot(file) { var dir = dirname(file), prev; while (true) { if (dir === ".") { dir = process.cwd(); } if (exists(join(dir, "package.json")) || exists(join(dir, "node_modules"))) { return dir; } if (prev === dir) { throw new Error( 'Could not find module root given file: "' + file + '". Do you have a `package.json` file? ' ); } prev = dir; dir = join(dir, ".."); } }; } }); // node_modules/epoll/epoll.js var require_epoll = __commonJS({ "node_modules/epoll/epoll.js"(exports, module) { module.exports = ((_) => { const osType = __require("os").type(); if (osType === "Linux") { return require_bindings()("epoll.node"); } console.warn(`Warning: epoll is built for Linux and not intended for usage on ${osType}.`); return { Epoll: {} }; })(); } }); // node_modules/onoff/onoff.js var require_onoff = __commonJS({ "node_modules/onoff/onoff.js"(exports, module) { var fs2 = __require("fs"); var debounce = require_lodash(); var Epoll = require_epoll().Epoll; var GPIO_ROOT_PATH = "/sys/class/gpio/"; var HIGH_BUF = Buffer.from("1"); var LOW_BUF = Buffer.from("0"); var HIGH = 1; var LOW = 0; var exportGpio = (gpio) => { if (!fs2.existsSync(gpio._gpioPath)) { fs2.writeFileSync(GPIO_ROOT_PATH + "export", "" + gpio._gpio); return false; } return true; }; var waitForGpioAccessPermission = (gpio, direction, edge, gpioPreviouslyExported) => { let permissionRequiredPaths = [ gpio._gpioPath + "value" ]; if (gpioPreviouslyExported === false) { permissionRequiredPaths.push(gpio._gpioPath + "direction"); permissionRequiredPaths.push(gpio._gpioPath + "active_low"); if (edge && direction === "in") { permissionRequiredPaths.push(gpio._gpioPath + "edge"); } } permissionRequiredPaths.forEach((path) => { let tries = 0; while (true) { try { tries += 1; const fd = fs2.openSync(path, "r+"); fs2.closeSync(fd); break; } catch (e2) { if (tries === 1e4) { throw e2; } } } }); }; var configureGpio = (gpio, direction, edge, options, gpioPreviouslyExported) => { const throwIfNeeded = (err) => { if (gpioPreviouslyExported === false) { throw err; } }; try { if (typeof options.activeLow === "boolean") { gpio.setActiveLow(options.activeLow); } } catch (err) { throwIfNeeded(err); } try { const reconfigureDirection = typeof options.reconfigureDirection === "boolean" ? options.reconfigureDirection : true; const requestedDirection = direction === "high" || direction === "low" ? "out" : direction; if (reconfigureDirection || gpio.direction() !== requestedDirection) { gpio.setDirection(direction); } } catch (err) { throwIfNeeded(err); } try { if (edge && direction === "in") { gpio.setEdge(edge); } } catch (err) { throwIfNeeded(err); } }; var configureInterruptHandler = (gpio) => { const pollerEventHandler = (err, fd, events) => { const value = gpio.readSync(); if (value === LOW && gpio._fallingEnabled || value === HIGH && gpio._risingEnabled) { gpio._listeners.slice(0).forEach((callback) => { callback(err, value); }); } }; gpio.readSync(); if (gpio._debounceTimeout > 0) { const db = debounce(pollerEventHandler, gpio._debounceTimeout); gpio._poller = new Epoll((err, fd, events) => { gpio.readSync(); db(err, fd, events); }); } else { gpio._poller = new Epoll(pollerEventHandler); } }; var Gpio2 = class { constructor(gpio, direction, edge, options) { if (typeof edge === "object" && !options) { options = edge; edge = void 0; } options = options || {}; this._gpio = gpio; this._gpioPath = GPIO_ROOT_PATH + "gpio" + this._gpio + "/"; this._debounceTimeout = options.debounceTimeout || 0; this._readBuffer = Buffer.alloc(16); this._readSyncBuffer = Buffer.alloc(16); this._listeners = []; const gpioPreviouslyExported = exportGpio(this); waitForGpioAccessPermission( this, direction, edge, gpioPreviouslyExported ); configureGpio(this, direction, edge, options, gpioPreviouslyExported); this._valueFd = fs2.openSync(this._gpioPath + "value", "r+"); configureInterruptHandler(this); } read(callback) { const readValue = (callback2) => { fs2.read(this._valueFd, this._readBuffer, 0, 1, 0, (err, bytes, buf) => { if (typeof callback2 === "function") { if (err) { return callback2(err); } callback2(null, convertBufferToBit(buf)); } }); }; if (callback) { readValue(callback); } else { return new Promise((resolve, reject) => { readValue((err, value) => { if (err) { reject(err); } else { resolve(value); } }); }); } } readSync() { fs2.readSync(this._valueFd, this._readSyncBuffer, 0, 1, 0); return convertBufferToBit(this._readSyncBuffer); } write(value, callback) { const writeValue = (value2, callback2) => { const writeBuffer = convertBitToBuffer(value2); fs2.write( this._valueFd, writeBuffer, 0, writeBuffer.length, 0, callback2 ); }; if (callback) { writeValue(value, callback); } else { return new Promise((resolve, reject) => { writeValue(value, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } } writeSync(value) { const writeBuffer = convertBitToBuffer(value); fs2.writeSync(this._valueFd, writeBuffer, 0, writeBuffer.length, 0); } watch(callback) { this._listeners.push(callback); if (this._listeners.length === 1) { this._poller.add(this._valueFd, Epoll.EPOLLPRI); } } unwatch(callback) { if (this._listeners.length > 0) { if (typeof callback !== "function") { this._listeners = []; } else { this._listeners = this._listeners.filter((listener) => { return callback !== listener; }); } if (this._listeners.length === 0) { this._poller.remove(this._valueFd); } } } unwatchAll() { this.unwatch(); } direction() { return fs2.readFileSync(this._gpioPath + "direction").toString().trim(); } setDirection(direction) { fs2.writeFileSync(this._gpioPath + "direction", direction); } edge() { return fs2.readFileSync(this._gpioPath + "edge").toString().trim(); } setEdge(edge) { fs2.writeFileSync(this._gpioPath + "edge", edge); this._risingEnabled = edge === "both" || edge === "rising"; this._fallingEnabled = edge === "both" || edge === "falling"; } activeLow() { return convertBufferToBoolean( fs2.readFileSync(this._gpioPath + "active_low") ); } setActiveLow(invert) { fs2.writeFileSync( this._gpioPath + "active_low", convertBooleanToBuffer(!!invert) ); } unexport() { this.unwatchAll(); fs2.closeSync(this._valueFd); try { fs2.writeFileSync(GPIO_ROOT_PATH + "unexport", "" + this._gpio); } catch (ignore) { } } static get accessible() { let fd; try { fd = fs2.openSync(GPIO_ROOT_PATH + "export", fs2.constants.O_WRONLY); } catch (e2) { return false; } finally { if (fd) { fs2.closeSync(fd); } } return true; } }; var convertBitToBuffer = (bit) => convertBooleanToBuffer(bit === HIGH); var convertBufferToBit = (buffer) => convertBufferToBoolean(buffer) ? HIGH : LOW; var convertBooleanToBuffer = (boolean) => boolean ? HIGH_BUF : LOW_BUF; var convertBufferToBoolean = (buffer) => buffer[0] === HIGH_BUF[0]; Gpio2.HIGH = HIGH; Gpio2.LOW = LOW; module.exports.Gpio = Gpio2; } }); // node_modules/data-uri-to-buffer/dist/index.js function dataUriToBuffer(uri) { if (!/^data:/i.test(uri)) { throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); } uri = uri.replace(/\r?\n/g, ""); const firstComma = uri.indexOf(","); if (firstComma === -1 || firstComma <= 4) { throw new TypeError("malformed data: URI"); } const meta = uri.substring(5, firstComma).split(";"); let charset = ""; let base64 = false; const type = meta[0] || "text/plain"; let typeFull = type; for (let i2 = 1; i2 < meta.length; i2++) { if (meta[i2] === "base64") { base64 = true; } else if (meta[i2]) { typeFull += `;${meta[i2]}`; if (meta[i2].indexOf("charset=") === 0) { charset = meta[i2].substring(8); } } } if (!meta[0] && !charset.length) { typeFull += ";charset=US-ASCII"; charset = "US-ASCII"; } const encoding = base64 ? "base64" : "ascii"; const data = unescape(uri.substring(firstComma + 1)); const buffer = Buffer.from(data, encoding); buffer.type = type; buffer.typeFull = typeFull; buffer.charset = charset; return buffer; } var dist_default; var init_dist = __esm({ "node_modules/data-uri-to-buffer/dist/index.js"() { dist_default = dataUriToBuffer; } }); // node_modules/web-streams-polyfill/dist/ponyfill.es2018.js var require_ponyfill_es2018 = __commonJS({ "node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports, module) { (function(global2, factory) { typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); })(exports, function(exports2) { function noop2() { return void 0; } function typeIsObject(x2) { return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; } const rethrowAssertionErrorRejection = noop2; function setFunctionName(fn, name) { try { Object.defineProperty(fn, "name", { value: name, configurable: true }); } catch (_a5) { } } const originalPromise = Promise; const originalPromiseThen = Promise.prototype.then; const originalPromiseReject = Promise.reject.bind(originalPromise); function newPromise(executor) { return new originalPromise(executor); } function promiseResolvedWith(value) { return newPromise((resolve) => resolve(value)); } function promiseRejectedWith(reason) { return originalPromiseReject(reason); } function PerformPromiseThen(promise, onFulfilled, onRejected) { return originalPromiseThen.call(promise, onFulfilled, onRejected); } function uponPromise(promise, onFulfilled, onRejected) { PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection); } function uponFulfillment(promise, onFulfilled) { uponPromise(promise, onFulfilled); } function uponRejection(promise, onRejected) { uponPromise(promise, void 0, onRejected); } function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); } function setPromiseIsHandledToTrue(promise) { PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection); } let _queueMicrotask = (callback) => { if (typeof queueMicrotask === "function") { _queueMicrotask = queueMicrotask; } else { const resolvedPromise = promiseResolvedWith(void 0); _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb); } return _queueMicrotask(callback); }; function reflectCall(F2, V, args) { if (typeof F2 !== "function") { throw new TypeError("Argument is not a function"); } return Function.prototype.apply.call(F2, V, args); } function promiseCall(F2, V, args) { try { return promiseResolvedWith(reflectCall(F2, V, args)); } catch (value) { return promiseRejectedWith(value); } } const QUEUE_MAX_ARRAY_SIZE = 16384; class SimpleQueue { constructor() { this._cursor = 0; this._size = 0; this._front = { _elements: [], _next: void 0 }; this._back = this._front; this._cursor = 0; this._size = 0; } get length() { return this._size; } // For exception safety, this method is structured in order: // 1. Read state // 2. Calculate required state mutations // 3. Perform state mutations push(element) { const oldBack = this._back; let newBack = oldBack; if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { newBack = { _elements: [], _next: void 0 }; } oldBack._elements.push(element); if (newBack !== oldBack) { this._back = newBack; oldBack._next = newBack; } ++this._size; } // Like push(), shift() follows the read -> calculate -> mutate pattern for // exception safety. shift() { const oldFront = this._front; let newFront = oldFront; const oldCursor = this._cursor; let newCursor = oldCursor + 1; const elements = oldFront._elements; const element = elements[oldCursor]; if (newCursor === QUEUE_MAX_ARRAY_SIZE) { newFront = oldFront._next; newCursor = 0; } --this._size; this._cursor = newCursor; if (oldFront !== newFront) { this._front = newFront; } elements[oldCursor] = void 0; return element; } // The tricky thing about forEach() is that it can be called // re-entrantly. The queue may be mutated inside the callback. It is easy to // see that push() within the callback has no negative effects since the end // of the queue is checked for on every iteration. If shift() is called // repeatedly within the callback then the next iteration may return an // element that has been removed. In this case the callback will be called // with undefined values until we either "catch up" with elements that still // exist or reach the back of the queue. forEach(callback) { let i2 = this._cursor; let node = this._front; let elements = node._elements; while (i2 !== elements.length || node._next !== void 0) { if (i2 === elements.length) { node = node._next; elements = node._elements; i2 = 0; if (elements.length === 0) { break; } } callback(elements[i2]); ++i2; } } // Return the element that would be returned if shift() was called now, // without modifying the queue. peek() { const front = this._front; const cursor = this._cursor; return front._elements[cursor]; } } const AbortSteps = Symbol("[[AbortSteps]]"); const ErrorSteps = Symbol("[[ErrorSteps]]"); const CancelSteps = Symbol("[[CancelSteps]]"); const PullSteps = Symbol("[[PullSteps]]"); const ReleaseSteps = Symbol("[[ReleaseSteps]]"); function ReadableStreamReaderGenericInitialize(reader, stream) { reader._ownerReadableStream = stream; stream._reader = reader; if (stream._state === "readable") { defaultReaderClosedPromiseInitialize(reader); } else if (stream._state === "closed") { defaultReaderClosedPromiseInitializeAsResolved(reader); } else { defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); } } function ReadableStreamReaderGenericCancel(reader, reason) { const stream = reader._ownerReadableStream; return ReadableStreamCancel(stream, reason); } function ReadableStreamReaderGenericRelease(reader) { const stream = reader._ownerReadableStream; if (stream._state === "readable") { defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } else { defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } stream._readableStreamController[ReleaseSteps](); stream._reader = void 0; reader._ownerReadableStream = void 0; } function readerLockException(name) { return new TypeError("Cannot " + name + " a stream using a released reader"); } function defaultReaderClosedPromiseInitialize(reader) { reader._closedPromise = newPromise((resolve, reject) => { reader._closedPromise_resolve = resolve; reader._closedPromise_reject = reject; }); } function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseReject(reader, reason); } function defaultReaderClosedPromiseInitializeAsResolved(reader) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseResolve(reader); } function defaultReaderClosedPromiseReject(reader, reason) { if (reader._closedPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(reader._closedPromise); reader._closedPromise_reject(reason); reader._closedPromise_resolve = void 0; reader._closedPromise_reject = void 0; } function defaultReaderClosedPromiseResetToRejected(reader, reason) { defaultReaderClosedPromiseInitializeAsRejected(reader, reason); } function defaultReaderClosedPromiseResolve(reader) { if (reader._closedPromise_resolve === void 0) { return; } reader._closedPromise_resolve(void 0); reader._closedPromise_resolve = void 0; reader._closedPromise_reject = void 0; } const NumberIsFinite = Number.isFinite || function(x2) { return typeof x2 === "number" && isFinite(x2); }; const MathTrunc = Math.trunc || function(v) { return v < 0 ? Math.ceil(v) : Math.floor(v); }; function isDictionary(x2) { return typeof x2 === "object" || typeof x2 === "function"; } function assertDictionary(obj, context) { if (obj !== void 0 && !isDictionary(obj)) { throw new TypeError(`${context} is not an object.`); } } function assertFunction(x2, context) { if (typeof x2 !== "function") { throw new TypeError(`${context} is not a function.`); } } function isObject(x2) { return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; } function assertObject(x2, context) { if (!isObject(x2)) { throw new TypeError(`${context} is not an object.`); } } function assertRequiredArgument(x2, position, context) { if (x2 === void 0) { throw new TypeError(`Parameter ${position} is required in '${context}'.`); } } function assertRequiredField(x2, field, context) { if (x2 === void 0) { throw new TypeError(`${field} is required in '${context}'.`); } } function convertUnrestrictedDouble(value) { return Number(value); } function censorNegativeZero(x2) { return x2 === 0 ? 0 : x2; } function integerPart(x2) { return censorNegativeZero(MathTrunc(x2)); } function convertUnsignedLongLongWithEnforceRange(value, context) { const lowerBound = 0; const upperBound = Number.MAX_SAFE_INTEGER; let x2 = Number(value); x2 = censorNegativeZero(x2); if (!NumberIsFinite(x2)) { throw new TypeError(`${context} is not a finite number`); } x2 = integerPart(x2); if (x2 < lowerBound || x2 > upperBound) { throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); } if (!NumberIsFinite(x2) || x2 === 0) { return 0; } return x2; } function assertReadableStream(x2, context) { if (!IsReadableStream(x2)) { throw new TypeError(`${context} is not a ReadableStream.`); } } function AcquireReadableStreamDefaultReader(stream) { return new ReadableStreamDefaultReader(stream); } function ReadableStreamAddReadRequest(stream, readRequest) { stream._reader._readRequests.push(readRequest); } function ReadableStreamFulfillReadRequest(stream, chunk, done) { const reader = stream._reader; const readRequest = reader._readRequests.shift(); if (done) { readRequest._closeSteps(); } else { readRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadRequests(stream) { return stream._reader._readRequests.length; } function ReadableStreamHasDefaultReader(stream) { const reader = stream._reader; if (reader === void 0) { return false; } if (!IsReadableStreamDefaultReader(reader)) { return false; } return true; } class ReadableStreamDefaultReader { constructor(stream) { assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader"); assertReadableStream(stream, "First parameter"); if (IsReadableStreamLocked(stream)) { throw new TypeError("This stream has already been locked for exclusive reading by another reader"); } ReadableStreamReaderGenericInitialize(this, stream); this._readRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException("closed")); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = void 0) { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("cancel")); } return ReadableStreamReaderGenericCancel(this, reason); } /** * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. * * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. */ read() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException("read")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("read from")); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), _closeSteps: () => resolvePromise({ value: void 0, done: true }), _errorSteps: (e2) => rejectPromise(e2) }; ReadableStreamDefaultReaderRead(this, readRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamDefaultReader(this)) { throw defaultReaderBrandCheckException("releaseLock"); } if (this._ownerReadableStream === void 0) { return; } ReadableStreamDefaultReaderRelease(this); } } Object.defineProperties(ReadableStreamDefaultReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel"); setFunctionName(ReadableStreamDefaultReader.prototype.read, "read"); setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { value: "ReadableStreamDefaultReader", configurable: true }); } function IsReadableStreamDefaultReader(x2) { if (!typeIsObject(x2)) { return false; } if (!Object.prototype.hasOwnProperty.call(x2, "_readRequests")) { return false; } return x2 instanceof ReadableStreamDefaultReader; } function ReadableStreamDefaultReaderRead(reader, readRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === "closed") { readRequest._closeSteps(); } else if (stream._state === "errored") { readRequest._errorSteps(stream._storedError); } else { stream._readableStreamController[PullSteps](readRequest); } } function ReadableStreamDefaultReaderRelease(reader) { ReadableStreamReaderGenericRelease(reader); const e2 = new TypeError("Reader was released"); ReadableStreamDefaultReaderErrorReadRequests(reader, e2); } function ReadableStreamDefaultReaderErrorReadRequests(reader, e2) { const readRequests = reader._readRequests; reader._readRequests = new SimpleQueue(); readRequests.forEach((readRequest) => { readRequest._errorSteps(e2); }); } function defaultReaderBrandCheckException(name) { return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); } const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); class ReadableStreamAsyncIteratorImpl { constructor(reader, preventCancel) { this._ongoingPromise = void 0; this._isFinished = false; this._reader = reader; this._preventCancel = preventCancel; } next() { const nextSteps = () => this._nextSteps(); this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); return this._ongoingPromise; } return(value) { const returnSteps = () => this._returnSteps(value); return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); } _nextSteps() { if (this._isFinished) { return Promise.resolve({ value: void 0, done: true }); } const reader = this._reader; let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: (chunk) => { this._ongoingPromise = void 0; _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); }, _closeSteps: () => { this._ongoingPromise = void 0; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); resolvePromise({ value: void 0, done: true }); }, _errorSteps: (reason) => { this._ongoingPromise = void 0; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); rejectPromise(reason); } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promise; } _returnSteps(value) { if (this._isFinished) { return Promise.resolve({ value, done: true }); } this._isFinished = true; const reader = this._reader; if (!this._preventCancel) { const result = ReadableStreamReaderGenericCancel(reader, value); ReadableStreamReaderGenericRelease(reader); return transformPromiseWith(result, () => ({ value, done: true })); } ReadableStreamReaderGenericRelease(reader); return promiseResolvedWith({ value, done: true }); } } const ReadableStreamAsyncIteratorPrototype = { next() { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); } return this._asyncIteratorImpl.next(); }, return(value) { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); } return this._asyncIteratorImpl.return(value); } }; Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); function AcquireReadableStreamAsyncIterator(stream, preventCancel) { const reader = AcquireReadableStreamDefaultReader(stream); const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); iterator._asyncIteratorImpl = impl; return iterator; } function IsReadableStreamAsyncIterator(x2) { if (!typeIsObject(x2)) { return false; } if (!Object.prototype.hasOwnProperty.call(x2, "_asyncIteratorImpl")) { return false; } try { return x2._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; } catch (_a5) { return false; } } function streamAsyncIteratorBrandCheckException(name) { return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); } const NumberIsNaN = Number.isNaN || function(x2) { return x2 !== x2; }; var _a4, _b, _c; function CreateArrayFromList(elements) { return elements.slice(); } function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); } let TransferArrayBuffer = (O) => { if (typeof O.transfer === "function") { TransferArrayBuffer = (buffer) => buffer.transfer(); } else if (typeof structuredClone === "function") { TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] }); } else { TransferArrayBuffer = (buffer) => buffer; } return TransferArrayBuffer(O); }; let IsDetachedBuffer = (O) => { if (typeof O.detached === "boolean") { IsDetachedBuffer = (buffer) => buffer.detached; } else { IsDetachedBuffer = (buffer) => buffer.byteLength === 0; } return IsDetachedBuffer(O); }; function ArrayBufferSlice(buffer, begin, end) { if (buffer.slice) { return buffer.slice(begin, end); } const length = end - begin; const slice = new ArrayBuffer(length); CopyDataBlockBytes(slice, 0, buffer, begin, length); return slice; } function GetMethod(receiver, prop) { const func = receiver[prop]; if (func === void 0 || func === null) { return void 0; } if (typeof func !== "function") { throw new TypeError(`${String(prop)} is not a function`); } return func; } function CreateAsyncFromSyncIterator(syncIteratorRecord) { const syncIterable = { [Symbol.iterator]: () => syncIteratorRecord.iterator }; const asyncIterator = async function* () { return yield* syncIterable; }(); const nextMethod = asyncIterator.next; return { iterator: asyncIterator, nextMethod, done: false }; } const SymbolAsyncIterator = (_c = (_a4 = Symbol.asyncIterator) !== null && _a4 !== void 0 ? _a4 : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== void 0 ? _c : "@@asyncIterator"; function GetIterator(obj, hint = "sync", method) { if (method === void 0) { if (hint === "async") { method = GetMethod(obj, SymbolAsyncIterator); if (method === void 0) { const syncMethod = GetMethod(obj, Symbol.iterator); const syncIteratorRecord = GetIterator(obj, "sync", syncMethod); return CreateAsyncFromSyncIterator(syncIteratorRecord); } } else { method = GetMethod(obj, Symbol.iterator); } } if (method === void 0) { throw new TypeError("The object is not iterable"); } const iterator = reflectCall(method, obj, []); if (!typeIsObject(iterator)) { throw new TypeError("The iterator method must return an object"); } const nextMethod = iterator.next; return { iterator, nextMethod, done: false }; } function IteratorNext(iteratorRecord) { const resul