Files
bare-operating-system/packages/bare-os-seeder/kernel/lib/bare/bundles/bareNodeRuntime.js
T
2026-04-04 01:20:57 -04:00

16792 lines
572 KiB
JavaScript

var __bare_os_bundle_exports__ = (() => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// ../../node_modules/bare-events/web.js
var require_web = __commonJS({
"../../node_modules/bare-events/web.js"(exports) {
var BUBBLES = 1;
var CANCELABLE = 2;
var COMPOSED = 4;
var CANCELED = 8;
var DISPATCH = 16;
var STOP = 32;
var CAPTURE = 1;
var PASSIVE = 2;
var ONCE = 4;
var Event = class _Event {
// https://dom.spec.whatwg.org/#dom-event-event
constructor(type, options = {}) {
const { bubbles = false, cancelable = false, composed = false } = options;
this._type = type;
this._target = null;
this._state = 0;
if (bubbles) this._state |= BUBBLES;
if (cancelable) this._state |= CANCELABLE;
if (composed) this._state |= COMPOSED;
}
// https://dom.spec.whatwg.org/#dom-event-type
get type() {
return this._type;
}
// https://dom.spec.whatwg.org/#dom-event-target
get target() {
return this._target;
}
// https://dom.spec.whatwg.org/#dom-event-currenttarget
get currentTarget() {
return null;
}
// https://dom.spec.whatwg.org/#dom-event-bubbles
get bubbles() {
return (this._state & BUBBLES) !== 0;
}
// https://dom.spec.whatwg.org/#dom-event-cancelable
get cancelable() {
return (this._state & CANCELABLE) !== 0;
}
// https://dom.spec.whatwg.org/#dom-event-composed
get composed() {
return (this._state & COMPOSED) !== 0;
}
// https://dom.spec.whatwg.org/#dom-event-defaultprevented
get defaultPrevented() {
return (this._state & CANCELED) !== 0;
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
get isTrusted() {
return false;
}
// https://dom.spec.whatwg.org/#dom-event-preventdefault
preventDefault() {
if (this._state & CANCELABLE) this._state |= CANCELED;
}
// https://dom.spec.whatwg.org/#dom-event-stoppropagation
stopPropagation() {
}
// https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation
stopImmediatePropagation() {
this._state |= STOP;
}
toJSON() {
return {
type: this.type,
target: this.target,
bubbles: this.bubbles,
cancelable: this.cancelable,
composed: this.composed,
defaultPrevented: this.defaultPrevented,
isTrusted: this.isTrusted
};
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _Event },
type: this.type,
target: this.target,
bubbles: this.bubbles,
cancelable: this.cancelable,
composed: this.composed,
defaultPrevented: this.defaultPrevented,
isTrusted: this.isTrusted
};
}
};
exports.Event = Event;
exports.CustomEvent = class CustomEvent extends Event {
constructor(type, options = {}) {
super(type, options);
const { detail = null } = options;
this._detail = detail;
}
// https://dom.spec.whatwg.org/#dom-customevent-detail
get detail() {
return this._detail;
}
};
exports.EventTarget = class EventTarget {
// https://dom.spec.whatwg.org/#dom-eventtarget-eventtarget
constructor() {
this._listeners = /* @__PURE__ */ new Map();
}
// https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener
addEventListener(type, callback = null, options = {}) {
if (typeof options === "boolean") options = { capture: options };
const { capture = false, passive = false, once = false, signal = null } = options;
if (signal !== null && signal.aborted) return;
if (callback === null) return;
const listener = new EventListener(type, callback, capture, passive, once, signal);
const listeners = this._listeners.get(type);
if (listeners === void 0) this._listeners.set(type, listener);
else {
for (const existing of listeners) {
if (callback === existing.callback && capture === existing.capture) {
return;
}
}
listener.link(listeners);
if (signal !== null) {
let onabort2 = function() {
listener.unlink();
};
var onabort = onabort2;
signal.addEventListener("abort", onabort2);
}
}
}
// https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
removeEventListener(type, callback = null, options = {}) {
if (typeof options === "boolean") options = { capture: options };
const { capture = false } = options;
const listeners = this._listeners.get(type);
if (listeners === void 0) return;
for (const existing of listeners) {
if (callback === existing.callback && capture === existing.capture) {
const next = existing.unlink();
if (listeners === existing) this._listeners.set(type, next);
return;
}
}
}
// https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent
dispatchEvent(event) {
event._target = this;
event._state |= DISPATCH;
const listeners = this._listeners.get(event.type);
try {
if (listeners === void 0) return true;
for (const listener of listeners) {
if (listener.once) listener.unlink();
let callback = listener.callback;
let context = this;
if (typeof callback === "object") {
context = callback;
callback = callback.handleEvent;
}
Reflect.apply(callback, context, [event]);
if (event._state & STOP) break;
}
return (event._state & CANCELED) === 0;
} finally {
event._state &= ~DISPATCH;
event._state &= ~STOP;
}
}
toJSON() {
return {};
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: EventTarget }
};
}
};
var EventListener = class _EventListener {
constructor(type, callback, capture, passive, once, signal) {
this._type = type;
this._callback = callback;
this._signal = signal;
this._state = 0;
if (capture) this._state |= CAPTURE;
if (passive) this._state |= PASSIVE;
if (once) this._state |= ONCE;
this._previous = this;
this._next = this;
}
get type() {
return this._type;
}
get callback() {
return this._callback;
}
get capture() {
return (this._state & CAPTURE) !== 0;
}
get passive() {
return (this._state & PASSIVE) !== 0;
}
get once() {
return (this._state & ONCE) !== 0;
}
get removed() {
return this._previous === this && this._next === this;
}
link(listener) {
const next = this._next;
const previous = listener._previous;
this._next = listener;
listener._previous = this;
previous._next = next;
next._previous = previous;
return listener;
}
unlink() {
if (this.removed) return this;
const next = this._next;
const previous = this._previous;
this._next = this;
this._previous = this;
previous._next = next;
next._previous = previous;
return next;
}
*[Symbol.iterator]() {
let current = this;
while (true) {
const next = current._next;
yield current;
if (next === this) break;
current = next;
}
}
toJSON() {
return {
type: this.type,
capture: this.capture,
passive: this.passive,
once: this.once,
removed: this.removed
};
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _EventListener },
type: this.type,
callback: this.callback,
capture: this.capture,
passive: this.passive,
once: this.once,
removed: this.removed
};
}
};
}
});
// ../../node_modules/bare-abort-controller/index.js
var require_bare_abort_controller = __commonJS({
"../../node_modules/bare-abort-controller/index.js"(exports, module) {
var { Event, EventTarget } = require_web();
var AbortError = class extends Error {
get name() {
return "AbortError";
}
};
var TimeoutError = class extends Error {
get name() {
return "TimeoutError";
}
};
var AbortSignal = class _AbortSignal extends EventTarget {
constructor() {
super();
this._reason = void 0;
this._dependent = false;
this._sources = [];
this._dependents = [];
}
// https://dom.spec.whatwg.org/#dom-abortsignal-aborted
get aborted() {
return this._reason !== void 0;
}
// https://dom.spec.whatwg.org/#dom-abortsignal-reason
get reason() {
return this._reason;
}
// https://dom.spec.whatwg.org/#abortsignal-signal-abort
_abort(reason = new AbortError("The operation was aborted")) {
if (this.aborted) return;
this._reason = reason;
this.dispatchEvent(new Event("abort"));
for (const signal of this._dependents) {
signal._abort(reason);
}
}
// https://dom.spec.whatwg.org/#dom-abortsignal-throwifaborted
throwIfAborted() {
if (this._reason !== void 0) throw this._reason;
}
toJSON() {
return {
aborted: this.aborted,
reason: this.reason
};
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _AbortSignal },
aborted: this.aborted,
reason: this.reason
};
}
// https://dom.spec.whatwg.org/#dom-abortsignal-abort
static abort(reason) {
const signal = new _AbortSignal();
signal._reason = reason;
return signal;
}
// https://dom.spec.whatwg.org/#dom-abortsignal-timeout
static timeout(ms) {
const signal = new _AbortSignal();
const timer = setTimeout(
() => signal._abort(new TimeoutError("The operation timed out")),
ms
);
timer.unref();
return signal;
}
// https://dom.spec.whatwg.org/#dom-abortsignal-any
static any(signals) {
const result = new _AbortSignal();
for (const signal of signals) {
if (signal.aborted) {
result._reason = signal.reason;
return result;
}
}
result._dependent = true;
for (const signal of signals) {
if (signal._dependent === false) {
result._sources.push(signal);
signal._dependents.push(result);
} else {
for (const source of signal._sources) {
result._sources.push(source);
source._dependents.push(result);
}
}
}
return result;
}
};
var AbortController = class _AbortController {
constructor() {
this._signal = new AbortSignal();
}
// https://dom.spec.whatwg.org/#dom-abortcontroller-signal
get signal() {
return this._signal;
}
// https://dom.spec.whatwg.org/#dom-abortcontroller-abort
abort(reason) {
this._signal._abort(reason);
}
toJSON() {
return {
signal: this.signal
};
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _AbortController },
signal: this.signal
};
}
};
module.exports = exports = AbortController;
exports.AbortController = exports;
exports.AbortSignal = AbortSignal;
}
});
// ../../node_modules/bare-abort-controller/global.js
var require_global = __commonJS({
"../../node_modules/bare-abort-controller/global.js"() {
var { AbortController, AbortSignal } = require_bare_abort_controller();
global.AbortController = AbortController;
global.AbortSignal = AbortSignal;
}
});
// ../../node_modules/bare-ansi-escapes/index.js
var require_bare_ansi_escapes = __commonJS({
"../../node_modules/bare-ansi-escapes/index.js"(exports) {
var ESC = "\x1B";
var CSI = ESC + "[";
var SGR = (n) => CSI + n + "m";
exports.constants = {
ESC,
CSI,
SGR
};
exports.cursorHide = CSI + "?25l";
exports.cursorShow = CSI + "?25h";
exports.cursorUp = function cursorUp(n = 1) {
return CSI + n + "A";
};
exports.cursorDown = function cursorDown(n = 1) {
return CSI + n + "B";
};
exports.cursorForward = function cursorForward(n = 1) {
return CSI + n + "C";
};
exports.cursorBack = function cursorBack(n = 1) {
return CSI + n + "D";
};
exports.cursorNextLine = function cursorNextLine(n = 1) {
return CSI + n + "E";
};
exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
return CSI + n + "F";
};
exports.cursorPosition = function cursorPosition(column, row = 0) {
if (row === 0) return CSI + (column + 1) + "G";
return CSI + (row + 1) + ";" + (column + 1) + "H";
};
exports.eraseDisplayEnd = CSI + "J";
exports.eraseDisplayStart = CSI + "1J";
exports.eraseDisplay = CSI + "2J";
exports.eraseLineEnd = CSI + "K";
exports.eraseLineStart = CSI + "1K";
exports.eraseLine = CSI + "2K";
exports.scrollUp = function scrollUp(n = 1) {
return CSI + n + "S";
};
exports.scrollDown = function scrollDown(n = 1) {
return CSI + n + "T";
};
exports.modifierReset = SGR(0);
exports.modifierBold = SGR(1);
exports.modifierDim = SGR(2);
exports.modifierItalic = SGR(3);
exports.modifierUnderline = SGR(4);
exports.modifierNormal = SGR(22);
exports.modifierNotItalic = SGR(23);
exports.modifierNotUnderline = SGR(24);
exports.colorBlack = SGR(30);
exports.colorRed = SGR(31);
exports.colorGreen = SGR(32);
exports.colorYellow = SGR(33);
exports.colorBlue = SGR(34);
exports.colorMagenta = SGR(35);
exports.colorCyan = SGR(36);
exports.colorWhite = SGR(37);
exports.colorDefault = SGR(39);
exports.colorBrightBlack = SGR(90);
exports.colorBrightRed = SGR(91);
exports.colorBrightGreen = SGR(92);
exports.colorBrightYellow = SGR(93);
exports.colorBrightBlue = SGR(94);
exports.colorBrightMagenta = SGR(95);
exports.colorBrightCyan = SGR(96);
exports.colorBrightWhite = SGR(97);
}
});
// ../../node_modules/bare-type/binding.js
var require_binding = __commonJS({
"../../node_modules/bare-type/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-type/index.js
var require_bare_type = __commonJS({
"../../node_modules/bare-type/index.js"(exports, module) {
var binding = require_binding();
var t = binding.constants;
var Type = class {
constructor(type) {
this._type = type;
}
isUndefined() {
return this._type === t.UNDEFINED;
}
isNull() {
return this._type === t.NULL;
}
isBoolean() {
return this._type === t.BOOLEAN;
}
isNumber() {
return (this._type & 255) === t.NUMBER;
}
isInt32() {
return (this._type & (255 | t.INT32)) === (t.NUMBER | t.INT32);
}
isUint32() {
return (this._type & (255 | t.UINT32)) === (t.NUMBER | t.UINT32);
}
isString() {
return this._type === t.STRING;
}
isSymbol() {
return this._type === t.SYMBOL;
}
isObject() {
return (this._type & 255) === t.OBJECT;
}
isArray() {
return this._type === (t.OBJECT | t.ARRAY);
}
isArguments() {
return this._type === (t.OBJECT | t.ARGUMENTS);
}
isDate() {
return this._type === (t.OBJECT | t.DATE);
}
isRegExp() {
return this._type === (t.OBJECT | t.REGEXP);
}
isError() {
return this._type === (t.OBJECT | t.ERROR);
}
isPromise() {
return this._type === (t.OBJECT | t.PROMISE);
}
isProxy() {
return this._type === (t.OBJECT | t.PROXY);
}
isGenerator() {
return this._type === (t.OBJECT | t.GENERATOR);
}
isMap() {
return this._type === (t.OBJECT | t.MAP);
}
isSet() {
return this._type === (t.OBJECT | t.SET);
}
isWeakMap() {
return this._type === (t.OBJECT | t.WEAK_MAP);
}
isWeakSet() {
return this._type === (t.OBJECT | t.WEAK_SET);
}
isWeakRef() {
return this._type === (t.OBJECT | t.WEAK_REF);
}
isArrayBuffer() {
return this._type === (t.OBJECT | t.ARRAYBUFFER);
}
isSharedArrayBuffer() {
return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER);
}
isTypedArray() {
return (this._type & 65535) === (t.OBJECT | t.TYPEDARRAY);
}
isInt8Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY);
}
isUint8Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY);
}
isUint8ClampedArray() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY);
}
isInt16Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY);
}
isUint16Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY);
}
isInt32Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY);
}
isUint32Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY);
}
isFloat16Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY);
}
isFloat32Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY);
}
isFloat64Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY);
}
isBigInt64Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY);
}
isBigUint64Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY);
}
isDataView() {
return this._type === (t.OBJECT | t.DATAVIEW);
}
isModuleNamespace() {
return this._type === (t.OBJECT | t.MODULE_NAMESPACE);
}
isFunction() {
return (this._type & 255) === t.FUNCTION;
}
isAsyncFunction() {
return (this._type & (255 | t.ASYNC_FUNCTION)) === (t.FUNCTION | t.ASYNC_FUNCTION);
}
isGeneratorFunction() {
return (this._type & (255 | t.GENERATOR_FUNCTION)) === (t.FUNCTION | t.GENERATOR_FUNCTION);
}
isExternal() {
return this._type === t.EXTERNAL;
}
isBigInt() {
return this._type === t.BIGINT;
}
};
module.exports = exports = function type(value) {
switch (typeof value) {
case "undefined":
return new Type(t.UNDEFINED);
case "boolean":
return new Type(t.BOOLEAN);
case "number":
return new Type(
Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
);
case "string":
return new Type(t.STRING);
case "symbol":
return new Type(t.SYMBOL);
case "object":
return new Type(value === null ? t.NULL : binding.type(value));
case "function":
return new Type(binding.type(value));
case "bigint":
return new Type(t.BIGINT);
}
};
exports.createTag = function createTag(...components) {
const tag = new Uint32Array(4);
for (let i = 0; i < 4; i++) tag[i] = components[i] || 0;
return tag;
};
exports.addTag = function addTag(object, tag) {
binding.addTag(object, tag);
};
exports.checkTag = function checkTag(object, tag) {
return binding.checkTag(object, tag);
};
}
});
// ../../node_modules/bare-inspect/binding.js
var require_binding2 = __commonJS({
"../../node_modules/bare-inspect/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-inspect/index.js
var require_bare_inspect = __commonJS({
"../../node_modules/bare-inspect/index.js"(exports, module) {
var ansiEscapes = require_bare_ansi_escapes();
var getType = require_bare_type();
var binding = require_binding2();
var PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
var defaultDepth = 2;
var defaultBreakLength = 80;
var defaultMaxArrayLength = 40;
module.exports = exports = function inspect(value, opts = {}) {
const {
colors = false,
depth = defaultDepth,
breakLength = defaultBreakLength,
stylize = defaultStylize(colors)
} = opts;
const references = new InspectRefMap();
const tree = inspectValue(value, 0, {
colors,
depth,
breakLength,
stylize,
references
});
return tree.toString();
};
exports.styles = {
bigint: ansiEscapes.colorYellow,
boolean: ansiEscapes.colorYellow,
date: ansiEscapes.colorMagenta,
module: ansiEscapes.modifierUnderline,
name: ansiEscapes.modifierReset,
null: ansiEscapes.modifierBold,
number: ansiEscapes.colorYellow,
regexp: ansiEscapes.colorRed,
special: ansiEscapes.colorCyan,
string: ansiEscapes.colorGreen,
symbol: ansiEscapes.colorGreen,
undefined: ansiEscapes.colorBrightBlack
};
var styles = exports.styles;
function defaultStylize(colors) {
return function stylize(value, style) {
const color = colors && styles[style];
if (color) return color + value + ansiEscapes.modifierReset;
return value;
};
}
var InspectRefMap = class {
constructor() {
this.refs = /* @__PURE__ */ new WeakMap();
this.ids = /* @__PURE__ */ new WeakMap();
this.nextId = 1;
}
has(object) {
return this.refs.has(object);
}
get(object) {
return this.refs.get(object) || null;
}
set(object, ref) {
this.refs.set(object, ref);
}
id(object) {
let id = this.ids.get(object);
if (id) return id;
id = this.nextId++;
this.ids.set(object, id);
return id;
}
};
var InspectNode = class {
constructor(depth, length, opts) {
const { breakLength = defaultBreakLength, breakAlways = false } = opts;
this.depth = depth;
this.length = length;
this.breakLength = breakLength;
this.breakAlways = breakAlways;
}
pad(n, string) {
return string.padStart(n, " ");
}
indent(n, string) {
return " ".repeat(n) + string;
}
};
var InspectRef = class extends InspectNode {
constructor(depth, opts) {
super(depth, "[circular *]".length, opts);
this.refs = opts.references;
this.count = 0;
this.circular = false;
this.color = opts.colors && styles.special;
}
get id() {
return this.refs.id(this);
}
increment() {
return ++this.count;
}
decrement() {
return --this.count;
}
toString(opts = {}) {
const { offset = 0, pad = 0, indent = 0 } = opts;
let value = this.pad(pad, "[circular *" + this.id + "]");
if (this.color) value = this.color + value + ansiEscapes.modifierReset;
return offset ? value : this.indent(indent, value);
}
};
var InspectLeaf = class extends InspectNode {
constructor(value, color, depth, opts) {
const length = value.length;
if (value.includes("\n")) {
value = value.replaceAll("\n", "\n" + " ".repeat(depth));
opts = { ...opts, breakAlways: true };
}
super(depth, length, opts);
this.value = value;
this.color = opts.colors && color;
}
toString(opts = {}) {
const { offset = 0, pad = 0, indent = 0 } = opts;
let value = this.pad(pad, this.value);
if (this.color) value = this.color + value + ansiEscapes.modifierReset;
return offset ? value : this.indent(indent, value);
}
};
var InspectPair = class extends InspectNode {
constructor(delim, left, right, depth, opts) {
const length = left.length + delim.length + right.length;
if (left.breakAlways || right.breakAlways) {
opts = { ...opts, breakAlways: true };
}
super(depth, length, opts);
this.delim = delim;
this.left = left;
this.right = right;
}
toString(opts = {}) {
const { indent = 0 } = opts;
return this.indent(
indent,
this.left + this.delim + this.right.toString({
indent,
offset: this.left.length + this.delim.length
})
);
}
};
var InspectSuspension = class extends InspectNode {
constructor(overflow, depth, opts) {
const label = `... ${overflow} more`;
super(depth, label.length, opts);
this.label = label;
}
toString(opts = {}) {
const { indent = 0 } = opts;
return this.indent(indent, this.label);
}
};
var InspectSequence = class extends InspectNode {
constructor(header, footer, delim, values, ref, depth, opts) {
const { tabulate = false } = opts;
const length = (ref.circular ? "<ref *>".length + 1 : 0) + header.length + values.reduce(
(length2, value, i) => length2 + value.length + (i === 0 ? 0 : delim.length),
0
) + footer.length;
if (values.some((value) => value.breakAlways)) {
opts = { ...opts, breakAlways: true };
}
super(depth, length, opts);
this.header = header;
this.footer = footer;
this.delim = delim;
this.values = values;
this.ref = ref;
this.tabulate = tabulate;
}
toString(opts = {}) {
const { offset = 0, indent = 0 } = opts;
const split = this.breakAlways || this.values.length && (offset + this.length > this.breakLength || indent * 2 + this.length > this.breakLength);
let header = this.header;
if (this.ref.circular) {
header = "<ref *" + this.ref.id + "> " + header;
}
if (this.values.length === 0) {
header = header.trimEnd();
}
if (offset === 0) {
header = this.indent(indent, header);
}
if (split) {
header = header.trimEnd() + "\n";
}
let string = header;
let columns = 1;
let pad = 0;
if (this.tabulate) {
const widest = this.values.reduce(
(length, value) => value.breakAlways ? length : Math.max(length, value.length),
0
);
if (widest) {
columns = Math.max(
columns,
Math.floor(
(this.breakLength - indent * 2) / (widest + this.delim.length)
)
);
if (columns > 1) pad = widest;
}
}
for (let i = 0, n = this.values.length, offset2 = 0; i < n; i++) {
const value = this.values[i];
if (split) {
let part;
if (i % columns === 0 || value.breakAlways) {
part = value.toString({ indent: indent + 1, pad });
} else {
part = value.toString({ pad });
}
string += part;
if (i < n - 1) {
if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
string += this.delim.trimEnd() + "\n";
} else {
string += this.delim;
}
}
} else {
if (i > 0) string += this.delim;
string += value.toString({ offset: offset2 });
offset2 += value.length;
}
}
let footer = this.footer;
if (this.values.length === 0) {
footer = footer.trimStart();
}
if (split) {
string += "\n" + this.indent(indent, footer.trimStart());
} else {
string += footer;
}
return string;
}
};
function inspectValue(value, depth, opts) {
const type = getType(value);
if (type.isUndefined()) return inspectUndefined(depth, opts);
if (type.isNull()) return inspectNull(depth, opts);
if (type.isBoolean()) return inspectBoolean(value, depth, opts);
if (type.isNumber()) return inspectNumber(value, depth, opts);
if (type.isBigInt()) return inspectBigInt(value, depth, opts);
if (type.isString()) return inspectString(value, depth, opts);
if (type.isSymbol()) return inspectSymbol(value, depth, opts);
if (type.isObject()) return inspectObject(type, value, depth, opts);
if (type.isFunction()) return inspectFunction(type, value, depth, opts);
if (type.isExternal()) return inspectExternal(value, opts, opts);
}
function inspectUndefined(depth, opts) {
return new InspectLeaf("undefined", styles.undefined, depth, opts);
}
function inspectNull(depth, opts) {
return new InspectLeaf("null", styles.null, depth, opts);
}
function inspectBoolean(value, depth, opts) {
return new InspectLeaf(value.toString(), styles.boolean, depth, opts);
}
function inspectNumber(value, depth, opts) {
let string;
if (Object.is(value, -0)) {
string = "-0";
} else {
string = value.toString(10);
}
return new InspectLeaf(string, styles.number, depth, opts);
}
function inspectBigInt(value, depth, opts) {
return new InspectLeaf(value.toString(10) + "n", styles.bigint, depth, opts);
}
var STRING_ESCAPES = /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g;
function inspectString(value, depth, opts) {
const string = value.replace(STRING_ESCAPES, (match) => {
if (match.length === 2) return match;
switch (match) {
case "'":
return "\\'";
case "\\":
return "\\\\";
case "\b":
return "\\b";
case " ":
return "\\t";
case "\n":
return "\\n";
case "\f":
return "\\f";
case "\r":
return "\\r";
default:
return "\\u" + match.charCodeAt(0).toString(16).padStart(4, "0");
}
});
return new InspectLeaf("'" + string + "'", styles.string, depth, opts);
}
function inspectSymbol(value, depth, opts) {
return new InspectLeaf(value.toString(), styles.symbol, depth, opts);
}
function inspectKey(value, depth, opts) {
if (PLAIN_KEY.test(value)) {
return new InspectLeaf(value, null, depth, opts);
} else {
return inspectValue(value, depth, opts);
}
}
function inspectObject(type, object, depth, opts) {
const refs = opts.references;
let ref = refs.get(object);
if (ref === null) {
ref = new InspectRef(depth, opts);
refs.set(object, ref);
} else if (ref.count) {
ref.circular = true;
return ref;
}
const maxDepth = typeof opts.depth === "number" ? opts.depth : Infinity;
if (maxDepth < depth) {
const constructor = object.constructor;
return new InspectLeaf(
"[" + (constructor && constructor.name ? constructor.name : "Object") + "]",
styles.special,
depth,
opts
);
}
const inspect = object[Symbol.for("bare.inspect")] || object[Symbol.for("nodejs.util.inspect.custom")];
if (typeof inspect === "function") {
const value = inspect.call(
object,
typeof opts.depth === "number" ? opts.depth - depth : null,
{
colors: opts.colors,
breakLength: opts.breakLength,
stylize: opts.stylize
},
exports
);
if (typeof value === "object" && value !== null) {
refs.set(value, ref);
}
if (typeof value !== "string") {
return inspectValue(value, depth, opts);
}
return new InspectLeaf(value, null, depth, opts);
}
if (type.isArray()) return inspectArray(object, ref, depth, opts);
if (type.isDate()) return inspectDate(object, ref, depth, opts);
if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts);
if (type.isError()) return inspectError(object, ref, depth, opts);
if (type.isPromise()) return inspectPromise(object, ref, depth, opts);
if (type.isMap()) return inspectMap(object, ref, depth, opts);
if (type.isSet()) return inspectSet(object, ref, depth, opts);
if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts);
if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts);
if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts);
if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts);
if (type.isSharedArrayBuffer())
return inspectSharedArrayBuffer(object, ref, depth, opts);
if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts);
if (type.isDataView()) return inspectDataView(object, ref, depth, opts);
ref.increment();
const values = [];
for (const key in object) {
if (key === "constructor") continue;
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(object[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
let header = "{ ";
const tag = object[Symbol.toStringTag];
if (tag) header = "[" + tag + "] " + header;
if (object.constructor) {
const name = object.constructor.name;
if (name && name !== "Object") {
header = object.constructor.name + " " + header;
}
}
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectArray(array, ref, depth, opts) {
const { maxArrayLength = defaultMaxArrayLength } = opts;
ref.increment();
const values = [];
let remaining = Math.max(maxArrayLength, 0);
for (let i = 0, n = array.length; i < n; i++) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(array.length - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(inspectValue(array[i], depth + 1, opts));
}
for (const key of binding.getOwnNonIndexPropertyNames(array)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(array[key], depth + 1, opts),
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
let header = "[ ";
if (array.constructor.name !== "Array") {
header = array.constructor.name + "(" + array.length + ") " + header;
}
return new InspectSequence(header, " ]", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectDate(date, ref, depth, opts) {
return new InspectLeaf(date.toISOString(), styles.date, depth, opts);
}
function inspectRegExp(regExp, ref, depth, opts) {
return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts);
}
function inspectError(error, ref, depth, opts) {
let header;
if ("stack" in error) {
header = error.stack;
if (depth > 0) {
header = header.replaceAll("\n", "\n" + " ".repeat(depth));
}
} else {
header = error.toString();
}
const builtins = ["cause"];
if (error.name === "AggregateError") {
builtins.push("errors");
} else if (error.name === "SuppressedError") {
builtins.push("error", "suppressed");
}
const values = [];
for (const key of builtins) {
if (key in error === false) continue;
values.push(
new InspectPair(
": ",
new InspectLeaf("[" + key + "]", null, depth + 1, opts),
inspectValue(error[key], depth + 1, opts),
depth + 1,
opts
)
);
}
for (const key in error) {
if (key === "constructor" || builtins.includes(key)) continue;
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(error[key], depth + 1, opts),
depth + 1,
opts
)
);
}
if (values.length === 0) return new InspectLeaf(header, null, depth, opts);
return new InspectSequence(
header + " {",
" }",
", ",
values,
ref,
depth,
opts
);
}
function inspectPromise(promise, ref, depth, opts) {
ref.increment();
const state = binding.getPromiseState(promise);
const values = [];
switch (state) {
case 0:
values.push(new InspectLeaf("<pending>", styles.special, depth, opts));
break;
case 1:
values.push(inspectValue(binding.getPromiseResult(promise), depth, opts));
break;
case 2:
values.push(
new InspectLeaf("<rejected>", styles.special, depth, opts),
inspectValue(binding.getPromiseResult(promise), depth, opts)
);
}
ref.decrement();
const header = promise.constructor.name + " { ";
return new InspectSequence(header, " }", " ", values, ref, depth, opts);
}
function inspectMap(map, ref, depth, opts) {
const {
maxArrayLength = defaultMaxArrayLength,
maxMapLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = maxMapLength;
for (const entry of map) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(map.size - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(
new InspectPair(
" => ",
inspectValue(entry[0], depth + 1, opts),
inspectValue(entry[1], depth + 1, opts),
depth + 1,
opts
)
);
}
for (const key in map) {
if (key === "constructor") continue;
const value = inspectValue(map[key], depth + 1, opts);
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
value,
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
const header = map.constructor.name + "(" + map.size + ") { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectSet(set, ref, depth, opts) {
const {
maxArrayLength = defaultMaxArrayLength,
maxSetLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = maxSetLength;
for (const entry of set) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(set.size - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(inspectValue(entry, depth + 1, opts));
}
for (const key in set) {
if (key === "constructor") continue;
const value = inspectValue(set[key], depth + 1, opts);
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
value,
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
const header = set.constructor.name + "(" + set.size + ") { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectWeakMap(weakMap, ref, depth, opts) {
const header = weakMap.constructor.name + " { ";
return new InspectSequence(
header,
" }",
" ",
[new InspectLeaf("<items unknown>", styles.special, depth + 1, opts)],
ref,
depth,
opts
);
}
function inspectWeakSet(weakSet, ref, depth, opts) {
const header = weakSet.constructor.name + " { ";
return new InspectSequence(
header,
" }",
" ",
[new InspectLeaf("<items unknown>", styles.special, depth + 1, opts)],
ref,
depth,
opts
);
}
function inspectWeakRef(weakRef, ref, depth, opts) {
const target = weakRef.deref();
let value;
if (target === void 0) {
value = new InspectLeaf("<cleared>", styles.special, depth + 1, opts);
} else {
value = inspectValue(target, depth + 1, opts);
}
const header = weakRef.constructor.name + " { ";
return new InspectSequence(header, " }", " ", [value], ref, depth, opts);
}
function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
ref.increment();
const values = [];
for (const key of ["byteLength"]) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(arrayBuffer[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
const header = arrayBuffer.constructor.name + " { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
ref.increment();
const values = [];
for (const key of ["byteLength"]) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(sharedArrayBuffer[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
const header = sharedArrayBuffer.constructor.name + " { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectTypedArray(typedArray, ref, depth, opts) {
if (Buffer.isBuffer(typedArray)) {
return inspectBuffer(typedArray, ref, depth, opts);
}
const {
maxArrayLength = defaultMaxArrayLength,
maxTypedArrayLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = Math.max(maxTypedArrayLength, 0);
for (let i = 0, n = typedArray.length; i < n; i++) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(typedArray.length - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(inspectValue(typedArray[i], depth + 1, opts));
}
for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(typedArray[key], depth + 1, opts),
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
const header = typedArray.constructor.name + "(" + typedArray.length + ") [ ";
return new InspectSequence(header, " ]", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectBuffer(buffer, ref, depth, opts) {
const {
maxArrayLength = defaultMaxArrayLength,
maxBufferLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = Math.max(maxBufferLength, 0);
for (let i = 0, n = buffer.byteLength; i < n; i++) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(buffer.length - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(
new InspectLeaf(
buffer[i].toString(16).padStart(2, "0"),
null,
depth + 1,
opts
)
);
}
for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(buffer[key], depth + 1, opts),
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
return new InspectSequence("<Buffer ", ">", " ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectDataView(dataView, ref, depth, opts) {
ref.increment();
const values = [];
for (const key of ["byteLength", "byteOffset", "buffer"]) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(dataView[key], depth + 1, opts),
depth + 1,
opts
)
);
}
for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(dataView[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
const header = dataView.constructor.name + " { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectFunction(type, fn, depth, opts) {
if (fn.toString().startsWith("class")) return inspectClass(fn, depth, opts);
let tag = "function";
if (type.isGeneratorFunction()) tag = "generator " + tag;
if (type.isAsyncFunction()) tag = "async " + tag;
return new InspectLeaf(
"[" + tag + " " + (fn.name ? fn.name : "(anonymous)") + "]",
styles.special,
depth,
opts
);
}
function inspectClass(ctor, depth, opts) {
return new InspectLeaf(
"[class " + (ctor.name ? ctor.name : "(anonymous)") + "]",
styles.special,
depth,
opts
);
}
function inspectExternal(external, depth, opts) {
return new InspectLeaf(
"[external 0x" + binding.getExternal(external).toString(16) + "]",
styles.special,
depth,
opts
);
}
}
});
// ../../node_modules/bare-assert/index.js
var require_bare_assert = __commonJS({
"../../node_modules/bare-assert/index.js"(exports, module) {
var inspect = require_bare_inspect();
var AssertionError = class extends Error {
constructor(opts = {}) {
let { message = null, actual, expected, operator } = opts;
if (message === null) {
message = `${inspect(actual)} ${operator} ${inspect(expected)}`;
}
super(message);
this.actual = actual;
this.expected = expected;
this.operator = operator;
}
get name() {
return "AssertionError";
}
get code() {
"ASSERTION";
}
};
function assertFail(opts, fn) {
if (opts.message instanceof Error) throw opts.message;
const err = new AssertionError(opts);
if (Error.captureStackTrace) Error.captureStackTrace(err, fn);
throw err;
}
module.exports = exports = function assert(actual, message) {
if (actual) return;
assertFail({ message, actual, expected: true, operator: "==" }, assert);
};
exports.AssertionError = AssertionError;
exports.fail = function fail(message) {
if (message === void 0) message = "Failed";
assertFail({ message, operator: "fail" }, fail);
};
exports.ok = function ok(actual, message) {
if (actual) return;
assertFail({ message, actual, expected: true, operator: "==" }, ok);
};
exports.notOk = function ok(actual, message) {
if (!actual) return;
assertFail({ message, actual, expected: false, operator: "==" }, ok);
};
exports.equal = function equal(actual, expected, message) {
if (actual == expected || actual !== actual && expected !== expected) {
return;
}
assertFail({ message, actual, expected, operator: "==" }, equal);
};
exports.notEqual = function notEqual(actual, expected, message) {
if (actual != expected && (actual === actual || expected === expected)) {
return;
}
assertFail({ message, actual, expected, operator: "!=" }, notEqual);
};
exports.strictEqual = function strictEqual(actual, expected, message) {
if (Object.is(actual, expected)) return;
assertFail(
{ message, actual, expected, operator: "strictEqual" },
strictEqual
);
};
exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (!Object.is(actual, expected)) return;
assertFail(
{ message, actual, expected, operator: "notStrictEqual" },
notStrictEqual
);
};
}
});
// ../../node_modules/bare-crypto/binding.js
var require_binding3 = __commonJS({
"../../node_modules/bare-crypto/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-crypto/lib/errors.js
var require_errors = __commonJS({
"../../node_modules/bare-crypto/lib/errors.js"(exports, module) {
module.exports = class CryptoError extends Error {
constructor(msg, fn = CryptoError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "CryptoError";
}
static UNKNOWN_HASH(msg) {
return new CryptoError(msg, CryptoError.UNKNOWN_HASH);
}
static UNKNOWN_CIPHER(msg) {
return new CryptoError(msg, CryptoError.UNKNOWN_CIPHER);
}
static UNKNOWN_KEY_TYPE(msg) {
return new CryptoError(msg, CryptoError.UNKNOWN_KEY_TYPE);
}
static INVALID_ACCESS(msg) {
return new CryptoError(msg, CryptoError.INVALID_ACCESS);
}
static INVALID_DATA(msg) {
return new CryptoError(msg, CryptoError.INVALID_DATA);
}
static OPERATION_ERROR(msg) {
return new CryptoError(msg, CryptoError.OPERATION_ERROR);
}
static NOT_SUPPORTED(msg) {
return new CryptoError(msg, CryptoError.NOT_SUPPORTED);
}
};
}
});
// ../../node_modules/bare-crypto/lib/constants.js
var require_constants = __commonJS({
"../../node_modules/bare-crypto/lib/constants.js"(exports, module) {
var { fail } = require_bare_assert();
var binding = require_binding3();
var errors = require_errors();
module.exports = exports = {
hash: {
MD5: binding.MD5,
SHA1: binding.SHA1,
SHA256: binding.SHA256,
SHA384: binding.SHA384,
SHA512: binding.SHA512,
BLAKE2B256: binding.BLAKE2B256,
RIPEMD160: binding.RIPEMD160
},
signature: {
ED25519: binding.ED25519
},
cipher: {
AES128ECB: binding.AES128ECB,
AES128CBC: binding.AES128CBC,
AES128CTR: binding.AES128CTR,
AES128OFB: binding.AES128OFB,
AES256ECB: binding.AES256ECB,
AES256CBC: binding.AES256CBC,
AES256CTR: binding.AES256CTR,
AES256OFB: binding.AES256OFB,
AES128GCM: binding.AES128GCM,
AES256GCM: binding.AES256GCM,
CHACHA20POLY1305: binding.CHACHA20POLY1305,
XCHACHA20POLY1305: binding.XCHACHA20POLY1305
},
keyType: {
ED25519: binding.ED25519
}
};
exports.toHash = function toHash(hash) {
if (typeof hash === "number" && !isNaN(hash)) return hash;
if (typeof hash === "string") {
hash = hash.replace(/-/g, "");
if (hash in exports.hash === false) {
hash = hash.toUpperCase();
if (hash in exports.hash === false) {
throw errors.UNKNOWN_HASH(`Unknown hash '${hash}'`);
}
}
return exports.hash[hash];
}
fail(`Hash must be a number or string. Received ${isNaN(hash) ? "NaN" : typeof hash} (${hash})`);
};
exports.toCipher = function toCiper(cipher) {
if (typeof cipher === "number" && !isNaN(cipher)) return cipher;
if (typeof cipher === "string") {
cipher = cipher.replace(/-/g, "");
if (cipher in exports.cipher === false) {
cipher = cipher.toUpperCase();
if (cipher in exports.cipher === false) {
throw errors.UNKNOWN_CIPHER(`Unknown cipher '${cipher}'`);
}
}
return exports.cipher[cipher];
}
fail(
`Cipher must be a number or string. Received ${isNaN(cipher) ? "NaN" : typeof cipher} (${cipher})`
);
};
exports.toKeyType = function toKeyType(type) {
if (typeof type === "number" && !isNaN(type)) return type;
if (typeof type === "string") {
type = type.replace(/-/g, "");
if (type in exports.keyType === false) {
type = type.toUpperCase();
if (type in exports.keyType === false) {
throw errors.UNKNOWN_KEY_TYPE(`Unknown key type '${type}'`);
}
}
return exports.keyType[type];
}
fail(
`Key type must be a number or string. Received ${isNaN(type) ? "NaN" : typeof type} (${type})`
);
};
}
});
// ../../node_modules/events-universal/default.js
var require_default = __commonJS({
"../../node_modules/events-universal/default.js"(exports, module) {
module.exports = __require("events");
}
});
// ../../node_modules/fast-fifo/fixed-size.js
var require_fixed_size = __commonJS({
"../../node_modules/fast-fifo/fixed-size.js"(exports, module) {
module.exports = class FixedFIFO {
constructor(hwm) {
if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
this.buffer = new Array(hwm);
this.mask = hwm - 1;
this.top = 0;
this.btm = 0;
this.next = null;
}
clear() {
this.top = this.btm = 0;
this.next = null;
this.buffer.fill(void 0);
}
push(data) {
if (this.buffer[this.top] !== void 0) return false;
this.buffer[this.top] = data;
this.top = this.top + 1 & this.mask;
return true;
}
shift() {
const last = this.buffer[this.btm];
if (last === void 0) return void 0;
this.buffer[this.btm] = void 0;
this.btm = this.btm + 1 & this.mask;
return last;
}
peek() {
return this.buffer[this.btm];
}
isEmpty() {
return this.buffer[this.btm] === void 0;
}
};
}
});
// ../../node_modules/fast-fifo/index.js
var require_fast_fifo = __commonJS({
"../../node_modules/fast-fifo/index.js"(exports, module) {
var FixedFIFO = require_fixed_size();
module.exports = class FastFIFO {
constructor(hwm) {
this.hwm = hwm || 16;
this.head = new FixedFIFO(this.hwm);
this.tail = this.head;
this.length = 0;
}
clear() {
this.head = this.tail;
this.head.clear();
this.length = 0;
}
push(val) {
this.length++;
if (!this.head.push(val)) {
const prev = this.head;
this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
this.head.push(val);
}
}
shift() {
if (this.length !== 0) this.length--;
const val = this.tail.shift();
if (val === void 0 && this.tail.next) {
const next = this.tail.next;
this.tail.next = null;
this.tail = next;
return this.tail.shift();
}
return val;
}
peek() {
const val = this.tail.peek();
if (val === void 0 && this.tail.next) return this.tail.next.peek();
return val;
}
isEmpty() {
return this.length === 0;
}
};
}
});
// ../../node_modules/b4a/index.js
var require_b4a = __commonJS({
"../../node_modules/b4a/index.js"(exports, module) {
function isBuffer(value) {
return Buffer.isBuffer(value) || value instanceof Uint8Array;
}
function isEncoding(encoding) {
return Buffer.isEncoding(encoding);
}
function alloc(size, fill2, encoding) {
return Buffer.alloc(size, fill2, encoding);
}
function allocUnsafe(size) {
return Buffer.allocUnsafe(size);
}
function allocUnsafeSlow(size) {
return Buffer.allocUnsafeSlow(size);
}
function byteLength(string, encoding) {
return Buffer.byteLength(string, encoding);
}
function compare(a, b) {
return Buffer.compare(a, b);
}
function concat(buffers, totalLength) {
return Buffer.concat(buffers, totalLength);
}
function copy(source, target, targetStart, start, end) {
return toBuffer(source).copy(target, targetStart, start, end);
}
function equals(a, b) {
return toBuffer(a).equals(b);
}
function fill(buffer, value, offset, end, encoding) {
return toBuffer(buffer).fill(value, offset, end, encoding);
}
function from(value, encodingOrOffset, length) {
return Buffer.from(value, encodingOrOffset, length);
}
function includes(buffer, value, byteOffset, encoding) {
return toBuffer(buffer).includes(value, byteOffset, encoding);
}
function indexOf(buffer, value, byfeOffset, encoding) {
return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
}
function lastIndexOf(buffer, value, byteOffset, encoding) {
return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
}
function swap16(buffer) {
return toBuffer(buffer).swap16();
}
function swap32(buffer) {
return toBuffer(buffer).swap32();
}
function swap64(buffer) {
return toBuffer(buffer).swap64();
}
function toBuffer(buffer) {
if (Buffer.isBuffer(buffer)) return buffer;
return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
function toString(buffer, encoding, start, end) {
return toBuffer(buffer).toString(encoding, start, end);
}
function write(buffer, string, offset, length, encoding) {
return toBuffer(buffer).write(string, offset, length, encoding);
}
function readDoubleBE(buffer, offset) {
return toBuffer(buffer).readDoubleBE(offset);
}
function readDoubleLE(buffer, offset) {
return toBuffer(buffer).readDoubleLE(offset);
}
function readFloatBE(buffer, offset) {
return toBuffer(buffer).readFloatBE(offset);
}
function readFloatLE(buffer, offset) {
return toBuffer(buffer).readFloatLE(offset);
}
function readInt32BE(buffer, offset) {
return toBuffer(buffer).readInt32BE(offset);
}
function readInt32LE(buffer, offset) {
return toBuffer(buffer).readInt32LE(offset);
}
function readUInt32BE(buffer, offset) {
return toBuffer(buffer).readUInt32BE(offset);
}
function readUInt32LE(buffer, offset) {
return toBuffer(buffer).readUInt32LE(offset);
}
function writeDoubleBE(buffer, value, offset) {
return toBuffer(buffer).writeDoubleBE(value, offset);
}
function writeDoubleLE(buffer, value, offset) {
return toBuffer(buffer).writeDoubleLE(value, offset);
}
function writeFloatBE(buffer, value, offset) {
return toBuffer(buffer).writeFloatBE(value, offset);
}
function writeFloatLE(buffer, value, offset) {
return toBuffer(buffer).writeFloatLE(value, offset);
}
function writeInt32BE(buffer, value, offset) {
return toBuffer(buffer).writeInt32BE(value, offset);
}
function writeInt32LE(buffer, value, offset) {
return toBuffer(buffer).writeInt32LE(value, offset);
}
function writeUInt32BE(buffer, value, offset) {
return toBuffer(buffer).writeUInt32BE(value, offset);
}
function writeUInt32LE(buffer, value, offset) {
return toBuffer(buffer).writeUInt32LE(value, offset);
}
module.exports = {
isBuffer,
isEncoding,
alloc,
allocUnsafe,
allocUnsafeSlow,
byteLength,
compare,
concat,
copy,
equals,
fill,
from,
includes,
indexOf,
lastIndexOf,
swap16,
swap32,
swap64,
toBuffer,
toString,
write,
readDoubleBE,
readDoubleLE,
readFloatBE,
readFloatLE,
readInt32BE,
readInt32LE,
readUInt32BE,
readUInt32LE,
writeDoubleBE,
writeDoubleLE,
writeFloatBE,
writeFloatLE,
writeInt32BE,
writeInt32LE,
writeUInt32BE,
writeUInt32LE
};
}
});
// ../../node_modules/text-decoder/lib/pass-through-decoder.js
var require_pass_through_decoder = __commonJS({
"../../node_modules/text-decoder/lib/pass-through-decoder.js"(exports, module) {
var b4a = require_b4a();
module.exports = class PassThroughDecoder {
constructor(encoding) {
this.encoding = encoding;
}
get remaining() {
return 0;
}
decode(data) {
return b4a.toString(data, this.encoding);
}
flush() {
return "";
}
};
}
});
// ../../node_modules/text-decoder/lib/utf8-decoder.js
var require_utf8_decoder = __commonJS({
"../../node_modules/text-decoder/lib/utf8-decoder.js"(exports, module) {
var b4a = require_b4a();
module.exports = class UTF8Decoder {
constructor() {
this._reset();
}
get remaining() {
return this.bytesSeen;
}
decode(data) {
if (data.byteLength === 0) return "";
if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
this.bytesSeen = trailingBytesSeen(data);
return b4a.toString(data, "utf8");
}
let result = "";
let start = 0;
if (this.bytesNeeded > 0) {
while (start < data.byteLength) {
const byte = data[start];
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
result += "\uFFFD";
this._reset();
break;
}
this.lowerBoundary = 128;
this.upperBoundary = 191;
this.codePoint = this.codePoint << 6 | byte & 63;
this.bytesSeen++;
start++;
if (this.bytesSeen === this.bytesNeeded) {
result += String.fromCodePoint(this.codePoint);
this._reset();
break;
}
}
if (this.bytesNeeded > 0) return result;
}
const trailing = trailingIncomplete(data, start);
const end = data.byteLength - trailing;
if (end > start) result += b4a.toString(data, "utf8", start, end);
for (let i = end; i < data.byteLength; i++) {
const byte = data[i];
if (this.bytesNeeded === 0) {
if (byte <= 127) {
this.bytesSeen = 0;
result += String.fromCharCode(byte);
} else if (byte >= 194 && byte <= 223) {
this.bytesNeeded = 2;
this.bytesSeen = 1;
this.codePoint = byte & 31;
} else if (byte >= 224 && byte <= 239) {
if (byte === 224) this.lowerBoundary = 160;
else if (byte === 237) this.upperBoundary = 159;
this.bytesNeeded = 3;
this.bytesSeen = 1;
this.codePoint = byte & 15;
} else if (byte >= 240 && byte <= 244) {
if (byte === 240) this.lowerBoundary = 144;
else if (byte === 244) this.upperBoundary = 143;
this.bytesNeeded = 4;
this.bytesSeen = 1;
this.codePoint = byte & 7;
} else {
this.bytesSeen = 1;
result += "\uFFFD";
}
continue;
}
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
result += "\uFFFD";
i--;
this._reset();
continue;
}
this.lowerBoundary = 128;
this.upperBoundary = 191;
this.codePoint = this.codePoint << 6 | byte & 63;
this.bytesSeen++;
if (this.bytesSeen === this.bytesNeeded) {
result += String.fromCodePoint(this.codePoint);
this._reset();
}
}
return result;
}
flush() {
const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
this._reset();
return result;
}
_reset() {
this.codePoint = 0;
this.bytesNeeded = 0;
this.bytesSeen = 0;
this.lowerBoundary = 128;
this.upperBoundary = 191;
}
};
function trailingIncomplete(data, start) {
const len = data.byteLength;
if (len <= start) return 0;
const limit = Math.max(start, len - 4);
let i = len - 1;
while (i > limit && (data[i] & 192) === 128) i--;
if (i < start) return 0;
const byte = data[i];
let needed;
if (byte <= 127) return 0;
if (byte >= 194 && byte <= 223) needed = 2;
else if (byte >= 224 && byte <= 239) needed = 3;
else if (byte >= 240 && byte <= 244) needed = 4;
else return 0;
const available = len - i;
return available < needed ? available : 0;
}
function trailingBytesSeen(data) {
const len = data.byteLength;
if (len === 0) return 0;
const last = data[len - 1];
if (last <= 127) return 0;
if ((last & 192) !== 128) return 1;
const limit = Math.max(0, len - 4);
let i = len - 2;
while (i >= limit && (data[i] & 192) === 128) i--;
if (i < 0) return 1;
const first = data[i];
let needed;
if (first >= 194 && first <= 223) needed = 2;
else if (first >= 224 && first <= 239) needed = 3;
else if (first >= 240 && first <= 244) needed = 4;
else return 1;
if (len - i !== needed) return 1;
if (needed >= 3) {
const second = data[i + 1];
if (first === 224 && second < 160) return 1;
if (first === 237 && second > 159) return 1;
if (first === 240 && second < 144) return 1;
if (first === 244 && second > 143) return 1;
}
return 0;
}
}
});
// ../../node_modules/text-decoder/index.js
var require_text_decoder = __commonJS({
"../../node_modules/text-decoder/index.js"(exports, module) {
var PassThroughDecoder = require_pass_through_decoder();
var UTF8Decoder = require_utf8_decoder();
module.exports = class TextDecoder {
constructor(encoding = "utf8") {
this.encoding = normalizeEncoding(encoding);
switch (this.encoding) {
case "utf8":
this.decoder = new UTF8Decoder();
break;
case "utf16le":
case "base64":
throw new Error("Unsupported encoding: " + this.encoding);
default:
this.decoder = new PassThroughDecoder(this.encoding);
}
}
get remaining() {
return this.decoder.remaining;
}
push(data) {
if (typeof data === "string") return data;
return this.decoder.decode(data);
}
// For Node.js compatibility
write(data) {
return this.push(data);
}
end(data) {
let result = "";
if (data) result = this.push(data);
result += this.decoder.flush();
return result;
}
};
function normalizeEncoding(encoding) {
encoding = encoding.toLowerCase();
switch (encoding) {
case "utf8":
case "utf-8":
return "utf8";
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return "utf16le";
case "latin1":
case "binary":
return "latin1";
case "base64":
case "ascii":
case "hex":
return encoding;
default:
throw new Error("Unknown encoding: " + encoding);
}
}
}
});
// ../../node_modules/streamx/index.js
var require_streamx = __commonJS({
"../../node_modules/streamx/index.js"(exports, module) {
var { EventEmitter } = require_default();
var STREAM_DESTROYED = new Error("Stream was destroyed");
var PREMATURE_CLOSE = new Error("Premature close");
var FIFO = require_fast_fifo();
var TextDecoder = require_text_decoder();
var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask;
var MAX = (1 << 29) - 1;
var OPENING = 1;
var PREDESTROYING = 2;
var DESTROYING = 4;
var DESTROYED = 8;
var NOT_OPENING = MAX ^ OPENING;
var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
var READ_ACTIVE = 1 << 4;
var READ_UPDATING = 2 << 4;
var READ_PRIMARY = 4 << 4;
var READ_QUEUED = 8 << 4;
var READ_RESUMED = 16 << 4;
var READ_PIPE_DRAINED = 32 << 4;
var READ_ENDING = 64 << 4;
var READ_EMIT_DATA = 128 << 4;
var READ_EMIT_READABLE = 256 << 4;
var READ_EMITTED_READABLE = 512 << 4;
var READ_DONE = 1024 << 4;
var READ_NEXT_TICK = 2048 << 4;
var READ_NEEDS_PUSH = 4096 << 4;
var READ_READ_AHEAD = 8192 << 4;
var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
var READ_PAUSED = MAX ^ READ_RESUMED;
var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
var READ_NOT_ENDING = MAX ^ READ_ENDING;
var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
var WRITE_ACTIVE = 1 << 18;
var WRITE_UPDATING = 2 << 18;
var WRITE_PRIMARY = 4 << 18;
var WRITE_QUEUED = 8 << 18;
var WRITE_UNDRAINED = 16 << 18;
var WRITE_DONE = 32 << 18;
var WRITE_EMIT_DRAIN = 64 << 18;
var WRITE_NEXT_TICK = 128 << 18;
var WRITE_WRITING = 256 << 18;
var WRITE_FINISHING = 512 << 18;
var WRITE_CORKED = 1024 << 18;
var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING);
var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
var NOT_ACTIVE = MAX ^ ACTIVE;
var DONE = READ_DONE | WRITE_DONE;
var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
var OPEN_STATUS = DESTROY_STATUS | OPENING;
var AUTO_DESTROY = DESTROY_STATUS | DONE;
var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
var IS_OPENING = OPEN_STATUS | TICKING;
var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING;
var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS;
var asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator");
var WritableState = class {
constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {
this.stream = stream;
this.queue = new FIFO();
this.highWaterMark = highWaterMark;
this.buffered = 0;
this.error = null;
this.pipeline = null;
this.drains = null;
this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
this.map = mapWritable || map;
this.afterWrite = afterWrite.bind(this);
this.afterUpdateNextTick = updateWriteNT.bind(this);
}
get ending() {
return (this.stream._duplexState & WRITE_FINISHING) !== 0;
}
get ended() {
return (this.stream._duplexState & WRITE_DONE) !== 0;
}
push(data) {
if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
if (this.map !== null) data = this.map(data);
this.buffered += this.byteLength(data);
this.queue.push(data);
if (this.buffered < this.highWaterMark) {
this.stream._duplexState |= WRITE_QUEUED;
return true;
}
this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
return false;
}
shift() {
const data = this.queue.shift();
this.buffered -= this.byteLength(data);
if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
return data;
}
end(data) {
if (typeof data === "function") this.stream.once("finish", data);
else if (data !== void 0 && data !== null) this.push(data);
this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
}
autoBatch(data, cb) {
const buffer = [];
const stream = this.stream;
buffer.push(data);
while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
buffer.push(stream._writableState.shift());
}
if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
stream._writev(buffer, cb);
}
update() {
const stream = this.stream;
stream._duplexState |= WRITE_UPDATING;
do {
while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
const data = this.shift();
stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
stream._write(data, this.afterWrite);
}
if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
} while (this.continueUpdate() === true);
stream._duplexState &= WRITE_NOT_UPDATING;
}
updateNonPrimary() {
const stream = this.stream;
if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
stream._duplexState = stream._duplexState | WRITE_ACTIVE;
stream._final(afterFinal.bind(this));
return;
}
if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
stream._duplexState |= ACTIVE;
stream._destroy(afterDestroy.bind(this));
}
return;
}
if ((stream._duplexState & IS_OPENING) === OPENING) {
stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
stream._open(afterOpen.bind(this));
}
}
continueUpdate() {
if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
return true;
}
updateCallback() {
if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
else this.updateNextTick();
}
updateNextTick() {
if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
this.stream._duplexState |= WRITE_NEXT_TICK;
if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
};
var ReadableState = class {
constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {
this.stream = stream;
this.queue = new FIFO();
this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
this.buffered = 0;
this.readAhead = highWaterMark > 0;
this.error = null;
this.pipeline = null;
this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
this.map = mapReadable || map;
this.pipeTo = null;
this.afterRead = afterRead.bind(this);
this.afterUpdateNextTick = updateReadNT.bind(this);
}
get ending() {
return (this.stream._duplexState & READ_ENDING) !== 0;
}
get ended() {
return (this.stream._duplexState & READ_DONE) !== 0;
}
pipe(pipeTo, cb) {
if (this.pipeTo !== null) throw new Error("Can only pipe to one destination");
if (typeof cb !== "function") cb = null;
this.stream._duplexState |= READ_PIPE_DRAINED;
this.pipeTo = pipeTo;
this.pipeline = new Pipeline(this.stream, pipeTo, cb);
if (cb) this.stream.on("error", noop);
if (isStreamx(pipeTo)) {
pipeTo._writableState.pipeline = this.pipeline;
if (cb) pipeTo.on("error", noop);
pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
} else {
const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
pipeTo.on("error", onerror);
pipeTo.on("close", onclose);
pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
}
pipeTo.on("drain", afterDrain.bind(this));
this.stream.emit("piping", pipeTo);
pipeTo.emit("pipe", this.stream);
}
push(data) {
const stream = this.stream;
if (data === null) {
this.highWaterMark = 0;
stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
return false;
}
if (this.map !== null) {
data = this.map(data);
if (data === null) {
stream._duplexState &= READ_PUSHED;
return this.buffered < this.highWaterMark;
}
}
this.buffered += this.byteLength(data);
this.queue.push(data);
stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
return this.buffered < this.highWaterMark;
}
shift() {
const data = this.queue.shift();
this.buffered -= this.byteLength(data);
if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
return data;
}
unshift(data) {
const pending = [this.map !== null ? this.map(data) : data];
while (this.buffered > 0) pending.push(this.shift());
for (let i = 0; i < pending.length - 1; i++) {
const data2 = pending[i];
this.buffered += this.byteLength(data2);
this.queue.push(data2);
}
this.push(pending[pending.length - 1]);
}
read() {
const stream = this.stream;
if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
const data = this.shift();
if (this.pipeTo !== null && this.pipeTo.write(data) === false)
stream._duplexState &= READ_PIPE_NOT_DRAINED;
if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
return data;
}
if (this.readAhead === false) {
stream._duplexState |= READ_READ_AHEAD;
this.updateNextTick();
}
return null;
}
drain() {
const stream = this.stream;
while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
const data = this.shift();
if (this.pipeTo !== null && this.pipeTo.write(data) === false)
stream._duplexState &= READ_PIPE_NOT_DRAINED;
if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
}
}
update() {
const stream = this.stream;
stream._duplexState |= READ_UPDATING;
do {
this.drain();
while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
stream._read(this.afterRead);
this.drain();
}
if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
stream._duplexState |= READ_EMITTED_READABLE;
stream.emit("readable");
}
if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
} while (this.continueUpdate() === true);
stream._duplexState &= READ_NOT_UPDATING;
}
updateNonPrimary() {
const stream = this.stream;
if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
stream.emit("end");
if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
if (this.pipeTo !== null) this.pipeTo.end();
}
if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
stream._duplexState |= ACTIVE;
stream._destroy(afterDestroy.bind(this));
}
return;
}
if ((stream._duplexState & IS_OPENING) === OPENING) {
stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
stream._open(afterOpen.bind(this));
}
}
continueUpdate() {
if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
this.stream._duplexState &= READ_NOT_NEXT_TICK;
return true;
}
updateCallback() {
if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
else this.updateNextTick();
}
updateNextTickIfOpen() {
if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
this.stream._duplexState |= READ_NEXT_TICK;
if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
updateNextTick() {
if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
this.stream._duplexState |= READ_NEXT_TICK;
if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
};
var TransformState = class {
constructor(stream) {
this.data = null;
this.afterTransform = afterTransform.bind(stream);
this.afterFinal = null;
}
};
var Pipeline = class {
constructor(src, dst, cb) {
this.from = src;
this.to = dst;
this.afterPipe = cb;
this.error = null;
this.pipeToFinished = false;
}
finished() {
this.pipeToFinished = true;
}
done(stream, err) {
if (err) this.error = err;
if (stream === this.to) {
this.to = null;
if (this.from !== null) {
if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
}
return;
}
}
if (stream === this.from) {
this.from = null;
if (this.to !== null) {
if ((stream._duplexState & READ_DONE) === 0) {
this.to.destroy(this.error || new Error("Readable stream closed before ending"));
}
return;
}
}
if (this.afterPipe !== null) this.afterPipe(this.error);
this.to = this.from = this.afterPipe = null;
}
};
function afterDrain() {
this.stream._duplexState |= READ_PIPE_DRAINED;
this.updateCallback();
}
function afterFinal(err) {
const stream = this.stream;
if (err) stream.destroy(err);
if ((stream._duplexState & DESTROY_STATUS) === 0) {
stream._duplexState |= WRITE_DONE;
stream.emit("finish");
}
if ((stream._duplexState & AUTO_DESTROY) === DONE) {
stream._duplexState |= DESTROYING;
}
stream._duplexState &= WRITE_NOT_FINISHING;
if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
else this.updateNextTick();
}
function afterDestroy(err) {
const stream = this.stream;
if (!err && this.error !== STREAM_DESTROYED) err = this.error;
if (err) stream.emit("error", err);
stream._duplexState |= DESTROYED;
stream.emit("close");
const rs = stream._readableState;
const ws = stream._writableState;
if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
if (ws !== null) {
while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
if (ws.pipeline !== null) ws.pipeline.done(stream, err);
}
}
function afterWrite(err) {
const stream = this.stream;
if (err) stream.destroy(err);
stream._duplexState &= WRITE_NOT_ACTIVE;
if (this.drains !== null) tickDrains(this.drains);
if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
stream._duplexState &= WRITE_DRAINED;
if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
stream.emit("drain");
}
}
this.updateCallback();
}
function afterRead(err) {
if (err) this.stream.destroy(err);
this.stream._duplexState &= READ_NOT_ACTIVE;
if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
this.stream._duplexState &= READ_NO_READ_AHEAD;
this.updateCallback();
}
function updateReadNT() {
if ((this.stream._duplexState & READ_UPDATING) === 0) {
this.stream._duplexState &= READ_NOT_NEXT_TICK;
this.update();
}
}
function updateWriteNT() {
if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
this.update();
}
}
function tickDrains(drains) {
for (let i = 0; i < drains.length; i++) {
if (--drains[i].writes === 0) {
drains.shift().resolve(true);
i--;
}
}
}
function afterOpen(err) {
const stream = this.stream;
if (err) stream.destroy(err);
if ((stream._duplexState & DESTROYING) === 0) {
if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
stream.emit("open");
}
stream._duplexState &= NOT_ACTIVE;
if (stream._writableState !== null) {
stream._writableState.updateCallback();
}
if (stream._readableState !== null) {
stream._readableState.updateCallback();
}
}
function afterTransform(err, data) {
if (data !== void 0 && data !== null) this.push(data);
this._writableState.afterWrite(err);
}
function newListener(name) {
if (this._readableState !== null) {
if (name === "data") {
this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
this._readableState.updateNextTick();
}
if (name === "readable") {
this._duplexState |= READ_EMIT_READABLE;
this._readableState.updateNextTick();
}
}
if (this._writableState !== null) {
if (name === "drain") {
this._duplexState |= WRITE_EMIT_DRAIN;
this._writableState.updateNextTick();
}
}
}
var Stream = class extends EventEmitter {
constructor(opts) {
super();
this._duplexState = 0;
this._readableState = null;
this._writableState = null;
if (opts) {
if (opts.open) this._open = opts.open;
if (opts.destroy) this._destroy = opts.destroy;
if (opts.predestroy) this._predestroy = opts.predestroy;
if (opts.signal) {
opts.signal.addEventListener("abort", abort.bind(this));
}
}
this.on("newListener", newListener);
}
_open(cb) {
cb(null);
}
_destroy(cb) {
cb(null);
}
_predestroy() {
}
get readable() {
return this._readableState !== null ? true : void 0;
}
get writable() {
return this._writableState !== null ? true : void 0;
}
get destroyed() {
return (this._duplexState & DESTROYED) !== 0;
}
get destroying() {
return (this._duplexState & DESTROY_STATUS) !== 0;
}
destroy(err) {
if ((this._duplexState & DESTROY_STATUS) === 0) {
if (!err) err = STREAM_DESTROYED;
this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
if (this._readableState !== null) {
this._readableState.highWaterMark = 0;
this._readableState.error = err;
}
if (this._writableState !== null) {
this._writableState.highWaterMark = 0;
this._writableState.error = err;
}
this._duplexState |= PREDESTROYING;
this._predestroy();
this._duplexState &= NOT_PREDESTROYING;
if (this._readableState !== null) this._readableState.updateNextTick();
if (this._writableState !== null) this._writableState.updateNextTick();
}
}
};
var Readable = class _Readable extends Stream {
constructor(opts) {
super(opts);
this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
this._readableState = new ReadableState(this, opts);
if (opts) {
if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
if (opts.read) this._read = opts.read;
if (opts.eagerOpen) this._readableState.updateNextTick();
if (opts.encoding) this.setEncoding(opts.encoding);
}
}
setEncoding(encoding) {
const dec = new TextDecoder(encoding);
const map = this._readableState.map || echo;
this._readableState.map = mapOrSkip;
return this;
function mapOrSkip(data) {
const next = dec.push(data);
return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next);
}
}
_read(cb) {
cb(null);
}
pipe(dest, cb) {
this._readableState.updateNextTick();
this._readableState.pipe(dest, cb);
return dest;
}
read() {
this._readableState.updateNextTick();
return this._readableState.read();
}
push(data) {
this._readableState.updateNextTickIfOpen();
return this._readableState.push(data);
}
unshift(data) {
this._readableState.updateNextTickIfOpen();
return this._readableState.unshift(data);
}
resume() {
this._duplexState |= READ_RESUMED_READ_AHEAD;
this._readableState.updateNextTick();
return this;
}
pause() {
this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
return this;
}
static _fromAsyncIterator(ite, opts) {
let destroy;
const rs = new _Readable({
...opts,
read(cb) {
ite.next().then(push).then(cb.bind(null, null)).catch(cb);
},
predestroy() {
destroy = ite.return();
},
destroy(cb) {
if (!destroy) return cb(null);
destroy.then(cb.bind(null, null)).catch(cb);
}
});
return rs;
function push(data) {
if (data.done) rs.push(null);
else rs.push(data.value);
}
}
static from(data, opts) {
if (isReadStreamx(data)) return data;
if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
let i = 0;
return new _Readable({
...opts,
read(cb) {
this.push(i === data.length ? null : data[i++]);
cb(null);
}
});
}
static isBackpressured(rs) {
return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
}
static isPaused(rs) {
return (rs._duplexState & READ_RESUMED) === 0;
}
[asyncIterator]() {
const stream = this;
let error = null;
let promiseResolve = null;
let promiseReject = null;
this.on("error", (err) => {
error = err;
});
this.on("readable", onreadable);
this.on("close", onclose);
return {
[asyncIterator]() {
return this;
},
next() {
return new Promise(function(resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
const data = stream.read();
if (data !== null) ondata(data);
else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
});
},
return() {
return destroy(null);
},
throw(err) {
return destroy(err);
}
};
function onreadable() {
if (promiseResolve !== null) ondata(stream.read());
}
function onclose() {
if (promiseResolve !== null) ondata(null);
}
function ondata(data) {
if (promiseReject === null) return;
if (error) promiseReject(error);
else if (data === null && (stream._duplexState & READ_DONE) === 0)
promiseReject(STREAM_DESTROYED);
else promiseResolve({ value: data, done: data === null });
promiseReject = promiseResolve = null;
}
function destroy(err) {
stream.destroy(err);
return new Promise((resolve, reject) => {
if (stream._duplexState & DESTROYED) return resolve({ value: void 0, done: true });
stream.once("close", function() {
if (err) reject(err);
else resolve({ value: void 0, done: true });
});
});
}
}
};
var Writable = class extends Stream {
constructor(opts) {
super(opts);
this._duplexState |= OPENING | READ_DONE;
this._writableState = new WritableState(this, opts);
if (opts) {
if (opts.writev) this._writev = opts.writev;
if (opts.write) this._write = opts.write;
if (opts.final) this._final = opts.final;
if (opts.eagerOpen) this._writableState.updateNextTick();
}
}
cork() {
this._duplexState |= WRITE_CORKED;
}
uncork() {
this._duplexState &= WRITE_NOT_CORKED;
this._writableState.updateNextTick();
}
_writev(batch, cb) {
cb(null);
}
_write(data, cb) {
this._writableState.autoBatch(data, cb);
}
_final(cb) {
cb(null);
}
static isBackpressured(ws) {
return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
}
static drained(ws) {
if (ws.destroyed) return Promise.resolve(false);
const state = ws._writableState;
const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
if (writes === 0) return Promise.resolve(true);
if (state.drains === null) state.drains = [];
return new Promise((resolve) => {
state.drains.push({ writes, resolve });
});
}
write(data) {
this._writableState.updateNextTick();
return this._writableState.push(data);
}
end(data) {
this._writableState.updateNextTick();
this._writableState.end(data);
return this;
}
};
var Duplex = class extends Readable {
// and Writable
constructor(opts) {
super(opts);
this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
this._writableState = new WritableState(this, opts);
if (opts) {
if (opts.writev) this._writev = opts.writev;
if (opts.write) this._write = opts.write;
if (opts.final) this._final = opts.final;
}
}
cork() {
this._duplexState |= WRITE_CORKED;
}
uncork() {
this._duplexState &= WRITE_NOT_CORKED;
this._writableState.updateNextTick();
}
_writev(batch, cb) {
cb(null);
}
_write(data, cb) {
this._writableState.autoBatch(data, cb);
}
_final(cb) {
cb(null);
}
write(data) {
this._writableState.updateNextTick();
return this._writableState.push(data);
}
end(data) {
this._writableState.updateNextTick();
this._writableState.end(data);
return this;
}
};
var Transform = class extends Duplex {
constructor(opts) {
super(opts);
this._transformState = new TransformState(this);
if (opts) {
if (opts.transform) this._transform = opts.transform;
if (opts.flush) this._flush = opts.flush;
}
}
_write(data, cb) {
if (this._readableState.buffered >= this._readableState.highWaterMark) {
this._transformState.data = data;
} else {
this._transform(data, this._transformState.afterTransform);
}
}
_read(cb) {
if (this._transformState.data !== null) {
const data = this._transformState.data;
this._transformState.data = null;
cb(null);
this._transform(data, this._transformState.afterTransform);
} else {
cb(null);
}
}
destroy(err) {
super.destroy(err);
if (this._transformState.data !== null) {
this._transformState.data = null;
this._transformState.afterTransform();
}
}
_transform(data, cb) {
cb(null, data);
}
_flush(cb) {
cb(null);
}
_final(cb) {
this._transformState.afterFinal = cb;
this._flush(transformAfterFlush.bind(this));
}
};
var PassThrough = class extends Transform {
};
function transformAfterFlush(err, data) {
const cb = this._transformState.afterFinal;
if (err) return cb(err);
if (data !== null && data !== void 0) this.push(data);
this.push(null);
cb(null);
}
function pipelinePromise(...streams) {
return new Promise((resolve, reject) => {
return pipeline(...streams, (err) => {
if (err) return reject(err);
resolve();
});
});
}
function pipeline(stream, ...streams) {
const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
let src = all[0];
let dest = null;
let error = null;
for (let i = 1; i < all.length; i++) {
dest = all[i];
if (isStreamx(src)) {
src.pipe(dest, onerror);
} else {
errorHandle(src, true, i > 1, onerror);
src.pipe(dest);
}
src = dest;
}
if (done) {
let fin = false;
const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
dest.on("error", (err) => {
if (error === null) error = err;
});
dest.on("finish", () => {
fin = true;
if (!autoDestroy) done(error);
});
if (autoDestroy) {
dest.on("close", () => done(error || (fin ? null : PREMATURE_CLOSE)));
}
}
return dest;
function errorHandle(s, rd, wr, onerror2) {
s.on("error", onerror2);
s.on("close", onclose);
function onclose() {
if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE);
if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE);
}
}
function onerror(err) {
if (!err || error) return;
error = err;
for (const s of all) {
s.destroy(err);
}
}
}
function echo(s) {
return s;
}
function isStream(stream) {
return !!stream._readableState || !!stream._writableState;
}
function isStreamx(stream) {
return typeof stream._duplexState === "number" && isStream(stream);
}
function isEnding(stream) {
return !!stream._readableState && stream._readableState.ending;
}
function isEnded(stream) {
return !!stream._readableState && stream._readableState.ended;
}
function isFinishing(stream) {
return !!stream._writableState && stream._writableState.ending;
}
function isFinished(stream) {
return !!stream._writableState && stream._writableState.ended;
}
function getStreamError(stream, opts = {}) {
const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
return !opts.all && err === STREAM_DESTROYED ? null : err;
}
function isReadStreamx(stream) {
return isStreamx(stream) && stream.readable;
}
function isDisturbed(stream) {
return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
}
function isTypedArray(data) {
return typeof data === "object" && data !== null && typeof data.byteLength === "number";
}
function defaultByteLength(data) {
return isTypedArray(data) ? data.byteLength : 1024;
}
function noop() {
}
function abort() {
this.destroy(new Error("Stream aborted."));
}
function isWritev(s) {
return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
}
module.exports = {
pipeline,
pipelinePromise,
isStream,
isStreamx,
isEnding,
isEnded,
isFinishing,
isFinished,
isDisturbed,
getStreamError,
Stream,
Writable,
Readable,
Duplex,
Transform,
// Export PassThrough for compatibility with Node.js core's stream module
PassThrough
};
}
});
// ../../node_modules/teex/index.js
var require_teex = __commonJS({
"../../node_modules/teex/index.js"(exports, module) {
var { Readable } = require_streamx();
module.exports = function(s, forks = 2) {
const streams = new Array(forks);
const status = new Array(forks).fill(true);
let ended = false;
for (let i = 0; i < forks; i++) {
streams[i] = new Readable({
read(cb) {
const check = !status[i];
status[i] = true;
if (check && allReadable()) s.resume();
cb(null);
}
});
}
s.on("end", function() {
ended = true;
for (const stream of streams) stream.push(null);
});
s.on("error", function(err) {
for (const stream of streams) stream.destroy(err);
});
s.on("close", function() {
if (ended) return;
for (const stream of streams) stream.destroy();
});
s.on("data", function(data) {
let needsPause = false;
for (let i = 0; i < streams.length; i++) {
if (!(status[i] = streams[i].push(data))) {
needsPause = true;
}
}
if (needsPause) s.pause();
});
return streams;
function allReadable() {
for (let j = 0; j < status.length; j++) {
if (!status[j]) return false;
}
return true;
}
};
}
});
// ../../node_modules/bare-stream/web.js
var require_web2 = __commonJS({
"../../node_modules/bare-stream/web.js"(exports) {
var { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require_streamx();
var tee = require_teex();
var readableKind = Symbol.for("bare.stream.readable.kind");
var writableKind = Symbol.for("bare.stream.writable.kind");
var transformKind = Symbol.for("bare.stream.transform.kind");
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
constructor(stream) {
this._stream = stream;
this._stream._stream.once("close", onclose).once("error", onerror);
const closed = Promise.withResolvers();
closed.promise.catch(noop);
this._closed = closed;
function onclose() {
closed.resolve();
}
function onerror(err) {
closed.reject(err);
}
}
get closed() {
return this._closed.promise;
}
read() {
const stream = this._stream._stream;
return new Promise((resolve, reject) => {
const err = getStreamError(stream);
if (err) return reject(err);
if (stream.destroyed) {
return resolve({ value: void 0, done: true });
}
const value = stream.read();
if (value !== null) {
return resolve({ value, done: false });
}
stream.once("readable", onreadable).once("close", onclose).once("error", onerror);
function onreadable() {
const value2 = stream.read();
ondone(null, value2 === null ? { value: void 0, done: true } : { value: value2, done: false });
}
function onclose() {
ondone(null, { value: void 0, done: true });
}
function onerror(err2) {
ondone(err2, null);
}
function ondone(err2, value2) {
stream.off("readable", onreadable).off("close", onclose).off("error", onerror);
if (err2) reject(err2);
else resolve(value2);
}
});
}
releaseLock() {
this._closed.reject(new TypeError("Reader was released"));
this._stream._releaseLock();
this._stream = null;
}
cancel(reason = new TypeError("Stream was cancelled")) {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise(
(resolve) => stream.once("close", resolve).once("error", noop).destroy(reason)
);
}
};
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
get desiredSize() {
const stream = this._stream._stream;
return stream._readableState.highWaterMark - stream._readableState.buffered;
}
enqueue(data) {
this._stream._stream.push(data);
}
close() {
this._stream._stream.push(null);
}
error(err) {
this._stream._stream.destroy(err);
}
};
var ReadableStream = class _ReadableStream {
static get [readableKind]() {
return 0;
}
static from(iterable) {
return new _ReadableStream(Readable.from(iterable));
}
constructor(underlyingSource = {}, queuingStrategy) {
if (isStreamx(underlyingSource)) {
this._stream = underlyingSource;
} else {
if (queuingStrategy === void 0) {
queuingStrategy = new exports.CountQueuingStrategy();
}
const { start, pull, cancel } = underlyingSource;
const { highWaterMark = 1, size = defaultSize } = queuingStrategy;
this._stream = new Readable({ highWaterMark, byteLength: size });
const controller = new exports.ReadableStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, controller));
}
if (pull) {
this._stream._read = this._read.bind(this, pull.bind(this, controller));
}
if (cancel) {
this._stream.once("error", cancel);
}
}
this._reader = null;
}
get [readableKind]() {
return _ReadableStream[readableKind];
}
get locked() {
return this._reader !== null;
}
getReader() {
if (this.locked) throw new TypeError("Stream is locked");
this._reader = new exports.ReadableStreamDefaultReader(this);
return this._reader;
}
cancel(reason = new TypeError("Stream was cancelled")) {
const stream = this._stream;
if (stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise(
(resolve) => stream.once("close", resolve).once("error", noop).destroy(reason)
);
}
tee() {
const [a, b] = tee(this._stream);
return [new _ReadableStream(a), new _ReadableStream(b)];
}
pipeTo(destination) {
return new Promise(
(resolve, reject) => this._stream.pipe(destination._stream, (err) => {
err ? reject(err) : resolve();
})
);
}
[Symbol.asyncIterator]() {
return this._stream[Symbol.asyncIterator]();
}
_releaseLock() {
this._reader = null;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _read(pull, cb) {
let err = null;
try {
await pull();
} catch (e) {
err = e;
}
cb(err);
}
};
function defaultSize() {
return 1;
}
exports.ReadableStream = ReadableStream;
exports.CountQueuingStrategy = class CountQueuingStrategy {
constructor(opts = {}) {
const { highWaterMark = 1 } = opts;
this.highWaterMark = highWaterMark;
}
size(chunk) {
return 1;
}
};
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
constructor(opts = {}) {
const { highWaterMark = 16384 } = opts;
this.highWaterMark = highWaterMark;
}
size(chunk) {
return chunk.byteLength;
}
};
exports.isReadableStream = function isReadableStream(value) {
if (value instanceof ReadableStream) return true;
return typeof value === "object" && value !== null && value[readableKind] === ReadableStream[readableKind];
};
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
return getStreamError(stream._stream) !== null;
};
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
return isDisturbed(stream._stream);
};
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
constructor(stream) {
this._stream = stream;
this._stream._stream.once("close", onclose).once("error", onerror);
const closed = Promise.withResolvers();
closed.promise.catch(noop);
this._closed = closed;
function onclose() {
closed.resolve();
}
function onerror(err) {
closed.reject(err);
}
}
get desiredSize() {
const stream = this._stream._stream;
return stream._writableState.highWaterMark - stream._writableState.buffered;
}
get closed() {
return this._closed.promise;
}
get ready() {
const stream = this._stream._stream;
if (getStreamError(stream)) return Promise.reject();
return Writable.drained(stream).then();
}
async write(chunk) {
const stream = this._stream._stream;
let err = getStreamError(stream);
if (err) return Promise.reject(err);
stream.write(chunk);
await Writable.drained(stream);
err = getStreamError(stream);
if (err) return Promise.reject(err);
}
releaseLock() {
this._closed.reject(new TypeError("Writer was released"));
this._stream._releaseLock();
this._stream = null;
}
close() {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise((resolve) => stream.once("close", resolve).end());
}
abort(reason = new TypeError("Stream was aborted")) {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise((resolve) => stream.once("close", resolve).destroy(reason));
}
};
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
error(err) {
this._stream._stream.destroy(err);
}
};
var WritableStream = class _WritableStream {
static get [writableKind]() {
return 0;
}
constructor(underlyingSink = {}, queuingStrategy = {}) {
if (isStreamx(underlyingSink)) {
this._stream = underlyingSink;
} else {
if (queuingStrategy === void 0) {
queuingStrategy = new exports.CountQueuingStrategy();
}
const { start, write, close, abort } = underlyingSink;
const { highWaterMark = 1, size = defaultSize } = queuingStrategy;
this._stream = new Writable({ highWaterMark, byteLength: size });
this._controller = new exports.WritableStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, this._controller));
}
if (write) {
this._stream._write = this._write.bind(this, write);
}
if (close) {
this._stream._destroy = this._destroy.bind(this, close.call(this));
}
if (abort) {
this._stream.once("error", abort);
}
}
this._writer = null;
}
get [writableKind]() {
return _WritableStream[writableKind];
}
get locked() {
return this._writer !== null;
}
getWriter() {
if (this.locked) throw new TypeError("Stream is locked");
this._writer = new exports.WritableStreamDefaultWriter(this);
return this._writer;
}
abort(reason = new TypeError("Stream was aborted")) {
if (this._stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise((resolve) => this._stream.once("close", resolve).destroy(reason));
}
close() {
if (this._stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise((resolve) => this._stream.once("close", resolve).end());
}
_releaseLock() {
this._writer = null;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _write(write, data, cb) {
let err = null;
try {
await write(data, this._controller);
} catch (e) {
err = e;
}
cb(err);
}
async _destroy(closing, cb) {
let err = null;
try {
await closing;
} catch (e) {
err = e;
}
cb(err);
}
};
exports.WritableStream = WritableStream;
exports.isWritableStream = function isWritableStream(value) {
if (value instanceof WritableStream) return true;
return typeof value === "object" && value !== null && value[writableKind] === WritableStream[writableKind];
};
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
get desiredSize() {
const stream = this._stream._stream;
return stream._readableState.highWaterMark - stream._readableState.buffered;
}
enqueue(data) {
this._stream._stream.push(data);
}
error(err) {
this._stream._stream.destroy(err);
}
terminate() {
const stream = this._stream._stream;
stream.push(null);
stream.destroy(new TypeError("Stream has been terminated"));
}
};
var TransformStream = class _TransformStream {
static get [transformKind]() {
return 0;
}
constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
const { start, transform, flush } = transformer;
this._stream = new Transform({ ...writableStrategy, ...readableStrategy });
this._writable = new WritableStream(this._stream);
this._readable = new ReadableStream(this._stream);
this._controller = new exports.TransformStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, this._controller));
}
if (transform) {
this._stream._write = this._transform.bind(this, transform);
}
if (flush) {
this._stream._flush = this._flush.bind(this, flush.call(this, this._controller));
}
}
get [transformKind]() {
return _TransformStream[transformKind];
}
get writable() {
return this._writable;
}
get readable() {
return this._readable;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _transform(transform, data, cb) {
let err = null;
try {
await transform(data, this._controller);
} catch (e) {
err = e;
}
cb(err);
}
async _flush(flush, cb) {
let err = null;
try {
await flush;
} catch (e) {
err = e;
}
cb(err);
}
};
exports.TransformStream = TransformStream;
exports.isTransformStream = function isTransformStream(value) {
if (value instanceof TransformStream) return true;
return typeof value === "object" && value !== null && value[transformKind] === TransformStream[transformKind];
};
function noop() {
}
}
});
// ../../node_modules/bare-stream/index.js
var require_bare_stream = __commonJS({
"../../node_modules/bare-stream/index.js"(exports, module) {
var stream = require_streamx();
var { ReadableStream, WritableStream } = require_web2();
var defaultEncoding = "utf8";
module.exports = exports = stream.Stream;
exports.pipeline = stream.pipeline;
exports.isStream = stream.isStream;
exports.isEnding = stream.isEnding;
exports.isEnded = stream.isEnded;
exports.isFinishing = stream.isFinishing;
exports.isFinished = stream.isFinished;
exports.isDisturbed = stream.isDisturbed;
exports.isErrored = function isErrored(stream2) {
return exports.getStreamError(stream2) !== null;
};
exports.isReadable = function isReadable(stream2) {
return stream2.readable && !stream2.destroying && !exports.isEnded(stream2);
};
exports.isWritable = function isWritable(stream2) {
return stream2.writable && !stream2.destroying && !exports.isFinishing(stream2);
};
exports.getStreamError = stream.getStreamError;
exports.addAbortSignal = function addAbortSignal(signal, stream2) {
function onAbort() {
stream2.destroy(signal.reason);
}
if (signal.aborted) onAbort();
else signal.addEventListener("abort", onAbort);
return stream2;
};
exports.Stream = exports;
exports.Readable = class Readable extends stream.Readable {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
map: null,
mapReadable: null
});
if (this._construct) this._open = this._construct;
if (this._read !== stream.Readable.prototype._read) {
this._read = read.bind(this, this._read);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
get closed() {
return !exports.isReadable(this);
}
get errored() {
return stream.getStreamError(this);
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
static fromWeb(readableStream, opts = {}) {
const stream2 = readableStream._stream;
if (opts.encoding) stream2.setEncoding(opts.encoding);
if (opts.signal) exports.addAbortSignal(opts.signal, stream2);
return stream2;
}
static toWeb(readable, opts = {}) {
return new ReadableStream(readable, opts.strategy);
}
async [Symbol.asyncDispose]() {
if (!this.destroyed) this.destroy();
await new Promise((resolve) => exports.finished(this, resolve));
}
};
exports.Writable = class Writable extends stream.Writable {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthWritable,
map: null,
mapWritable: null
});
if (this._construct) this._open = this._construct;
if (this._write !== stream.Writable.prototype._write) {
this._write = write.bind(this, this._write);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
get closed() {
return !exports.isWritable(this);
}
get errored() {
return stream.getStreamError(this);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding || defaultEncoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
static fromWeb(writableStream, opts = {}) {
const stream2 = writableStream._stream;
if (opts.signal) exports.addAbortSignal(opts.signal, stream2);
return stream2;
}
static toWeb(writable) {
return new WritableStream(writable);
}
async [Symbol.asyncDispose]() {
if (!this.destroyed) this.destroy();
await new Promise((resolve) => exports.finished(this, resolve));
}
};
exports.Duplex = class Duplex extends stream.Duplex {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
byteLengthWritable,
map: null,
mapReadable: null,
mapWritable: null
});
if (this._construct) this._open = this._construct;
if (this._read !== stream.Readable.prototype._read) {
this._read = read.bind(this, this._read);
}
if (this._write !== stream.Duplex.prototype._write) {
this._write = write.bind(this, this._write);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
const readable = exports.Readable.fromWeb(readableStream, opts);
const writable = exports.Readable.fromWeb(writableStream, opts);
const duplex = new exports.Duplex({
write(data, encoding, cb) {
writable.write(data, encoding, cb);
}
});
readable.on("data", (data) => duplex.push(data)).on("end", () => duplex.push(null)).on("error", (err) => duplex.destroy(err));
writable.on("finish", () => duplex.end()).on("error", (err) => duplex.destroy(err));
return duplex;
}
static toWeb(duplex) {
const readableStream = exports.Readable.toWeb(duplex);
const writableStream = exports.Writable.toWeb(duplex);
return { readable: readableStream, writable: writableStream };
}
};
var DuplexSide = class extends exports.Duplex {
constructor(opts) {
super(opts);
this._otherSide = null;
this._cb = null;
}
_read() {
const cb = this._cb;
if (!cb) return;
this._cb = null;
cb();
}
_write(chunk, encoding, cb) {
this._otherSide.push(chunk, encoding);
this._otherSide._cb = cb;
}
_final(cb) {
this._otherSide.on("end", cb);
this._otherSide.push(null);
}
};
exports.duplexPair = function duplexPair(opts) {
const sideA = new DuplexSide(opts);
const sideB = new DuplexSide(opts);
sideA._otherSide = sideB;
sideB._otherSide = sideA;
return [sideA, sideB];
};
exports.Transform = class Transform extends stream.Transform {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
byteLengthWritable,
map: null,
mapReadable: null,
mapWritable: null
});
if (this._transform !== stream.Transform.prototype._transform) {
this._transform = transform.bind(this, this._transform);
} else {
this._transform = passthrough;
}
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
};
exports.PassThrough = class PassThrough extends exports.Transform {
};
exports.finished = function finished(stream2, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (!opts) opts = {};
const { cleanup = false } = opts;
const done = () => {
cb(exports.getStreamError(stream2, { all: true }));
if (cleanup) detach();
};
const detach = () => {
stream2.off("close", done);
stream2.off("error", noop);
};
if (stream2.destroyed) {
done();
} else {
stream2.on("close", done);
stream2.on("error", noop);
}
return detach;
};
function read(read2, cb) {
read2.call(this, 65536);
cb(null);
}
function write(write2, data, cb) {
write2.call(this, data.chunk, data.encoding, cb);
}
function transform(transform2, data, cb) {
transform2.call(this, data.chunk, data.encoding, cb);
}
function destroy(destroy2, cb) {
destroy2.call(this, exports.getStreamError(this), cb);
}
function passthrough(data, cb) {
cb(null, data.chunk);
}
function byteLengthWritable(data) {
return data.chunk.byteLength;
}
function noop() {
}
}
});
// ../../node_modules/bare-crypto/lib/hash.js
var require_hash = __commonJS({
"../../node_modules/bare-crypto/lib/hash.js"(exports, module) {
var { Transform } = require_bare_stream();
var assert = require_bare_assert();
var binding = require_binding3();
var constants = require_constants();
var {
hash: { RIPEMD160 }
} = constants;
var CryptoDigest = class {
constructor(algorithm) {
this._handle = binding.digestInit(algorithm);
}
update(data) {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
binding.digestUpdate(this._handle, data.buffer, data.byteOffset, data.byteLength);
}
final() {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
const result = Buffer.from(binding.digestFinal(this._handle));
this._handle = null;
return result;
}
};
var CryptoRIPEMD160Digest = class {
constructor() {
this._handle = binding.ripemd160Init();
}
update(data) {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
binding.ripemd160Update(this._handle, data.buffer, data.byteOffset, data.byteLength);
}
final() {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
const result = Buffer.from(binding.ripemd160Final(this._handle));
this._handle = null;
return result;
}
};
module.exports = class CryptoHash extends Transform {
constructor(algorithm, opts = {}) {
super(opts);
algorithm = constants.toHash(algorithm);
switch (algorithm) {
case RIPEMD160:
this._digest = new CryptoRIPEMD160Digest();
break;
default:
this._digest = new CryptoDigest(algorithm);
break;
}
}
update(data, encoding = "utf8") {
if (typeof data === "string") data = Buffer.from(data, encoding);
assert(ArrayBuffer.isView(data));
this._digest.update(data);
return this;
}
digest(encoding) {
const digest = this._digest.final();
return encoding && encoding !== "buffer" ? digest.toString(encoding) : digest;
}
_transform(data, encoding, cb) {
this.update(data);
cb(null);
}
_flush(cb) {
this.push(this.digest());
cb(null);
}
};
}
});
// ../../node_modules/bare-crypto/lib/hmac.js
var require_hmac = __commonJS({
"../../node_modules/bare-crypto/lib/hmac.js"(exports, module) {
var { Transform } = require_bare_stream();
var assert = require_bare_assert();
var binding = require_binding3();
var constants = require_constants();
module.exports = class CryptoHmac extends Transform {
constructor(algorithm, key, opts = {}) {
super(opts);
const { encoding = "utf8" } = opts;
if (typeof key === "string") key = Buffer.from(key, encoding);
assert(ArrayBuffer.isView(key));
this._handle = binding.hmacInit(
constants.toHash(algorithm),
key.buffer,
key.byteOffset,
key.byteLength
);
}
update(data, encoding = "utf8") {
if (this._handle === null) {
throw new Error("Hmac has already been finalized");
}
if (typeof data === "string") data = Buffer.from(data, encoding);
assert(ArrayBuffer.isView(data));
binding.hmacUpdate(this._handle, data.buffer, data.byteOffset, data.byteLength);
return this;
}
digest(encoding) {
if (this._handle === null) {
throw new Error("Hmac has already been finalized");
}
const digest = Buffer.from(binding.hmacFinal(this._handle));
this._handle = null;
return encoding && encoding !== "buffer" ? digest.toString(encoding) : digest;
}
_transform(data, encoding, cb) {
this.update(data);
cb(null);
}
_flush(cb) {
this.push(this.digest());
cb(null);
}
};
}
});
// ../../node_modules/bare-crypto/lib/cipher.js
var require_cipher = __commonJS({
"../../node_modules/bare-crypto/lib/cipher.js"(exports) {
var { Transform } = require_bare_stream();
var assert = require_bare_assert();
var binding = require_binding3();
var constants = require_constants();
var {
cipher: {
AES128ECB,
AES128CBC,
AES128CTR,
AES128OFB,
AES256ECB,
AES256CBC,
AES256CTR,
AES256OFB,
AES128GCM,
AES256GCM,
CHACHA20POLY1305,
XCHACHA20POLY1305
}
} = constants;
var CryptoCipher = class {
constructor(algorithm, key, iv, encrypt, opts = {}) {
const { encoding = "utf8" } = opts;
if (typeof key === "string") key = Buffer.from(key, encoding);
if (typeof iv === "string") iv = Buffer.from(iv, encoding);
assert(ArrayBuffer.isView(key));
assert(ArrayBuffer.isView(iv));
if (key.byteLength !== binding.cipherKeyLength(algorithm)) {
throw new RangeError("Invalid key length");
}
if (iv.byteLength < binding.cipherIVLength(algorithm)) {
throw new RangeError("Invalid iv length");
}
this._handle = binding.cipherInit(
algorithm,
key.buffer,
key.byteOffset,
key.byteLength,
iv.buffer,
iv.byteOffset,
iv.byteLength,
encrypt
);
}
update(data, inputEncoding = "utf8", outputEncoding) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
if (typeof data === "string") data = Buffer.from(data, inputEncoding);
assert(ArrayBuffer.isView(data));
const out = new ArrayBuffer(data.byteLength + binding.cipherBlockSize(this._handle));
const written = binding.cipherUpdate(
this._handle,
data.buffer,
data.byteOffset,
data.byteLength,
out
);
const result = Buffer.from(out, 0, written);
return outputEncoding ? result.toString(outputEncoding) : result;
}
final(outputEncoding) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
const out = new ArrayBuffer(binding.cipherBlockSize(this._handle));
const written = binding.cipherFinal(this._handle, out);
this._handle = null;
const result = Buffer.from(out, 0, written);
return outputEncoding ? result.toString(outputEncoding) : result;
}
setAutoPadding(pad) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
binding.cipherSetPadding(this._handle, pad);
}
};
var CryptoAuthenticatedCipher = class {
constructor(algorithm, key, nonce, opts = {}) {
const { encoding = "utf8", authTagLength = 16 } = opts;
if (typeof key === "string") key = Buffer.from(key, encoding);
if (typeof nonce === "string") nonce = Buffer.from(nonce, encoding);
assert(ArrayBuffer.isView(key));
assert(ArrayBuffer.isView(nonce));
if (key.byteLength !== binding.aeadKeyLength(algorithm)) {
throw new RangeError("Invalid key length");
}
if (nonce.byteLength < binding.aeadNonceLength(algorithm)) {
throw new RangeError("Invalid nonce length");
}
this._buffer = [];
this._nonce = nonce;
this._authTag = null;
this._authTagLength = authTagLength;
this._additionalData = null;
this._handle = binding.aeadInit(
algorithm,
key.buffer,
key.byteOffset,
key.byteLength,
authTagLength
);
}
update(data, inputEncoding = "utf8", outputEncoding) {
if (typeof data === "string") data = Buffer.from(data, inputEncoding);
assert(ArrayBuffer.isView(data));
this._buffer.push(data);
return outputEncoding ? "" : Buffer.alloc(0);
}
setAAD(buffer, opts = {}) {
const { encoding = "utf8" } = opts;
if (typeof buffer === "string") buffer = Buffer.from(buffer, encoding);
assert(ArrayBuffer.isView(buffer));
this._additionalData = buffer;
}
getAuthTag() {
return this._authTag;
}
setAuthTag(authTag, encoding) {
if (typeof authTag === "string") authTag = Buffer.from(authTag, encoding);
assert(ArrayBuffer.isView(authTag));
this._authTag = authTag;
}
};
var CryptoAuthenticatedSeal = class extends CryptoAuthenticatedCipher {
final(outputEncoding) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
const data = this._buffer.length === 1 ? this._buffer[0] : Buffer.concat(this._buffer);
const nonce = this._nonce;
const ad = this._additionalData || Buffer.alloc(0);
const out = new ArrayBuffer(data.byteLength + binding.aeadMaxOverhead(this._handle));
const written = binding.aeadSeal(
this._handle,
data.buffer,
data.byteOffset,
data.byteLength,
nonce.buffer,
nonce.byteOffset,
nonce.byteLength,
ad.buffer,
ad.byteOffset,
ad.byteLength,
out
);
this._handle = null;
const cipherLength = written - this._authTagLength;
this._authTag = Buffer.from(out, cipherLength);
const result = Buffer.from(out, 0, cipherLength);
return outputEncoding ? result.toString(outputEncoding) : result;
}
};
var CryptoAuthenticatedOpen = class extends CryptoAuthenticatedCipher {
final(outputEncoding) {
if (this._handle === null) {
throw new Error("Decipher has already been finalized");
}
this._buffer.push(this._authTag);
const data = Buffer.concat(this._buffer);
const nonce = this._nonce;
const ad = this._additionalData || Buffer.alloc(0);
const out = new ArrayBuffer(data.byteLength);
const written = binding.aeadOpen(
this._handle,
data.buffer,
data.byteOffset,
data.byteLength,
nonce.buffer,
nonce.byteOffset,
nonce.byteLength,
ad.buffer,
ad.byteOffset,
ad.byteLength,
out
);
this._handle = null;
const result = Buffer.from(out, 0, written);
return outputEncoding ? result.toString(outputEncoding) : result;
}
};
exports.Cipheriv = class CryptoCipheriv extends Transform {
constructor(algorithm, key, iv, opts = {}) {
super(opts);
algorithm = constants.toCipher(algorithm);
switch (algorithm) {
case AES128ECB:
case AES128CBC:
case AES128CTR:
case AES128OFB:
case AES256ECB:
case AES256CBC:
case AES256CTR:
case AES256OFB:
this._cipher = new CryptoCipher(algorithm, key, iv, true, opts);
break;
case AES128GCM:
case AES256GCM:
case CHACHA20POLY1305:
case XCHACHA20POLY1305:
this._cipher = new CryptoAuthenticatedSeal(algorithm, key, iv, opts);
break;
}
}
update(data, inputEncoding, outputEncoding) {
return this._cipher.update(data, inputEncoding, outputEncoding);
}
final(outputEncoding) {
return this._cipher.final(outputEncoding);
}
setAutoPadding(pad) {
this._cipher.setAutoPadding(pad);
return this;
}
setAAD(buffer, opts) {
this._cipher.setAAD(buffer, opts);
return this;
}
getAuthTag() {
return this._cipher.getAuthTag();
}
_transform(data, encoding, cb) {
this.push(this.update(data));
cb(null);
}
_flush(cb) {
this.push(this.final());
cb(null);
}
};
exports.Decipheriv = class CryptoDeipheriv extends Transform {
constructor(algorithm, key, iv, opts = {}) {
super(opts);
algorithm = constants.toCipher(algorithm);
switch (algorithm) {
case AES128ECB:
case AES128CBC:
case AES128CTR:
case AES128OFB:
case AES256ECB:
case AES256CBC:
case AES256CTR:
case AES256OFB:
this._cipher = new CryptoCipher(algorithm, key, iv, false, opts);
break;
case AES128GCM:
case AES256GCM:
case CHACHA20POLY1305:
case XCHACHA20POLY1305:
this._cipher = new CryptoAuthenticatedOpen(algorithm, key, iv, opts);
break;
}
}
update(data, inputEncoding, outputEncoding) {
return this._cipher.update(data, inputEncoding, outputEncoding);
}
final(outputEncoding) {
return this._cipher.final(outputEncoding);
}
setAutoPadding(pad) {
this._cipher.setAutoPadding(pad);
return this;
}
setAAD(buffer, opts) {
this._cipher.setAAD(buffer, opts);
return this;
}
setAuthTag(authTag, encoding) {
this._cipher.setAuthTag(authTag, encoding);
return this;
}
_transform(data, encoding, cb) {
this.push(this.update(data));
cb(null);
}
_flush(cb) {
this.push(this.final());
cb(null);
}
};
}
});
// ../../node_modules/bare-crypto/lib/random.js
var require_random = __commonJS({
"../../node_modules/bare-crypto/lib/random.js"(exports) {
var assert = require_bare_assert();
var binding = require_binding3();
exports.randomBytes = function randomBytes(size, cb) {
assert(typeof size === "number" && !isNaN(size));
const buffer = Buffer.allocUnsafe(size);
exports.randomFill(buffer);
if (cb) queueMicrotask(() => cb(null, buffer));
else return buffer;
};
exports.randomFill = function randomFill(buffer, offset, size, cb) {
if (typeof offset === "function") {
cb = offset;
offset = void 0;
} else if (typeof size === "function") {
cb = size;
size = void 0;
}
assert(buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer));
assert(size === void 0 || typeof size === "number" && !isNaN(size));
assert(offset === void 0 || typeof offset === "number" && !isNaN(offset));
const elementSize = buffer.BYTES_PER_ELEMENT || 1;
if (offset === void 0) offset = 0;
else offset *= elementSize;
if (size === void 0) size = buffer.byteLength - offset;
else size *= elementSize;
if (offset < 0 || offset > buffer.byteLength) {
throw new RangeError("offset is out of range");
}
if (size < 0 || size > buffer.byteLength) {
throw new RangeError("size is out of range");
}
if (offset + size > buffer.byteLength) {
throw new RangeError("offset + size is out of range");
}
let arraybuffer;
if (ArrayBuffer.isView(buffer)) {
offset += buffer.byteOffset;
arraybuffer = buffer.buffer;
} else {
arraybuffer = buffer;
}
binding.randomFill(arraybuffer, offset, size);
if (cb) queueMicrotask(() => cb(null, buffer));
else return buffer;
};
exports.randomUUID = function randomUUID() {
const uuid = exports.randomBytes(16);
uuid[6] = uuid[6] >>> 4 | 64;
uuid[8] = uuid[8] >>> 2 | 128;
return uuid.subarray(0, 4).toString("hex") + "-" + uuid.subarray(4, 6).toString("hex") + "-" + uuid.subarray(6, 8).toString("hex") + "-" + uuid.subarray(8, 10).toString("hex") + "-" + uuid.subarray(10, 16).toString("hex");
};
}
});
// ../../node_modules/bare-crypto/lib/pbkdf2.js
var require_pbkdf2 = __commonJS({
"../../node_modules/bare-crypto/lib/pbkdf2.js"(exports, module) {
var assert = require_bare_assert();
var binding = require_binding3();
var constants = require_constants();
module.exports = function pbkdf2(password, salt, iterations, keylen, digest, cb) {
if (iterations <= 0) {
throw new RangeError("iterations is out of range");
}
assert(typeof iterations === "number" && !isNaN(iterations));
assert(typeof keylen === "number" && !isNaN(keylen));
if (typeof password === "string") password = Buffer.from(password);
if (typeof salt === "string") salt = Buffer.from(salt);
assert(ArrayBuffer.isView(password));
assert(ArrayBuffer.isView(salt));
const buffer = Buffer.from(
binding.pbkdf2(
password.buffer,
password.byteOffset,
password.byteLength,
salt.buffer,
salt.byteOffset,
salt.byteLength,
iterations,
constants.toHash(digest),
keylen
)
);
if (cb) queueMicrotask(() => cb(null, buffer));
else return buffer;
};
}
});
// ../../node_modules/bare-crypto/lib/key.js
var require_key = __commonJS({
"../../node_modules/bare-crypto/lib/key.js"(exports) {
var binding = require_binding3();
var constants = require_constants();
var {
keyType: { ED25519 }
} = constants;
var CryptoKey = class {
constructor(keyType) {
this._keyType = keyType;
}
};
exports.Key = CryptoKey;
var CryptoEd25519Key = class extends CryptoKey {
constructor(key) {
super(ED25519);
this._key = key;
}
get asymmetricKeyType() {
return "ed25519";
}
};
var CryptoEd25519PublicKey = class extends CryptoEd25519Key {
get type() {
return "public";
}
};
exports.Ed25519PublicKey = CryptoEd25519PublicKey;
var CryptoEd25519PrivateKey = class extends CryptoEd25519Key {
get type() {
return "private";
}
};
exports.Ed25519PrivateKey = CryptoEd25519PrivateKey;
exports.generateKeyPair = function generateKeyPair(type, opts = {}) {
type = constants.toKeyType(type);
switch (type) {
case ED25519: {
const { publicKey, privateKey } = binding.ed25519GenerateKeypair();
return {
publicKey: new CryptoEd25519PublicKey(publicKey),
privateKey: new CryptoEd25519PrivateKey(privateKey)
};
}
}
};
}
});
// ../../node_modules/bare-crypto/lib/signature.js
var require_signature = __commonJS({
"../../node_modules/bare-crypto/lib/signature.js"(exports) {
var assert = require_bare_assert();
var binding = require_binding3();
var { Key } = require_key();
var constants = require_constants();
var {
keyType: { ED25519 }
} = constants;
exports.sign = function sign(algorithm, data, key) {
assert(data instanceof ArrayBuffer || ArrayBuffer.isView(data));
if (ArrayBuffer.isView(data)) {
data = Buffer.coerce(data);
} else {
data = Buffer.from(data);
}
assert(key instanceof Key);
switch (key._keyType) {
case ED25519:
return Buffer.from(
binding.ed25519Sign(data.buffer, data.byteOffset, data.byteLength, key._key)
);
}
};
exports.verify = function verify(algorithm, data, key, signature) {
assert(data instanceof ArrayBuffer || ArrayBuffer.isView(data));
if (ArrayBuffer.isView(data)) {
data = Buffer.coerce(data);
} else {
data = Buffer.from(data);
}
assert(signature instanceof ArrayBuffer || ArrayBuffer.isView(signature));
if (ArrayBuffer.isView(signature)) {
signature = Buffer.coerce(signature);
} else {
signature = Buffer.from(signature);
}
assert(key instanceof Key);
switch (key._keyType) {
case ED25519:
assert(signature.byteLength === 64);
return binding.ed25519Verify(
data.buffer,
data.byteOffset,
data.byteLength,
signature.buffer,
signature.byteOffset,
key._key
);
}
};
}
});
// ../../node_modules/bare-crypto/index.js
var require_bare_crypto = __commonJS({
"../../node_modules/bare-crypto/index.js"(exports) {
var constants = require_constants();
var Hash = require_hash();
var Hmac = require_hmac();
var { Cipheriv, Decipheriv } = require_cipher();
var { randomBytes, randomFill, randomUUID } = require_random();
var pbkdf2 = require_pbkdf2();
var { generateKeyPair } = require_key();
var { sign, verify } = require_signature();
exports.constants = constants;
exports.Hash = Hash;
exports.createHash = function createHash(algorithm, opts) {
return new Hash(algorithm, opts);
};
exports.Hmac = Hmac;
exports.createHmac = function createHmac(algorithm, key, opts) {
return new Hmac(algorithm, key, opts);
};
exports.Cipheriv = Cipheriv;
exports.createCipheriv = function createCipheriv(algorithm, key, iv, opts) {
return new Cipheriv(algorithm, key, iv, opts);
};
exports.Decipheriv = Decipheriv;
exports.createDecipheriv = function createDecipheriv(algorithm, key, iv, opts) {
return new Decipheriv(algorithm, key, iv, opts);
};
exports.randomBytes = randomBytes;
exports.randomFill = randomFill;
exports.randomFillSync = function randomFillSync(buffer, offset, size) {
return exports.randomFill(buffer, offset, size);
};
exports.randomUUID = randomUUID;
exports.pbkdf2 = pbkdf2;
exports.pbkdf2Sync = function pbkdf2Sync(password, salt, iterations, keylen, digest) {
return exports.pbkdf2(password, salt, iterations, keylen, digest);
};
exports.generateKeyPair = generateKeyPair;
exports.sign = sign;
exports.verify = verify;
exports.webcrypto = require_web3();
}
});
// ../../node_modules/bare-crypto/lib/web/crypto-key.js
var require_crypto_key = __commonJS({
"../../node_modules/bare-crypto/lib/web/crypto-key.js"(exports, module) {
module.exports = class CryptoKey {
constructor(type, extractable, algorithm, usages, handle = null) {
this._type = type;
this._extractable = extractable;
this._algorithm = algorithm;
this._usages = usages;
this._handle = handle;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-type
get type() {
return this._type;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-extractable
get extractable() {
return this._extractable;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-algorithm
get algorithm() {
return this._algorithm;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-usages
get usages() {
return this._usages;
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: CryptoKey },
type: this.type,
extractable: this.extractable,
algorithm: this.algorithm,
usages: this.usages
};
}
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/hmac.js
var require_hmac2 = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/hmac.js"(exports) {
var crypto = require_bare_crypto();
var errors = require_errors();
var CryptoKey = require_crypto_key();
exports.sign = function sign(algorithm, key, data) {
const digest = crypto.createHmac(key.algorithm.hash.name, key._handle).update(data).digest();
return digest.buffer.slice(0, digest.byteLength);
};
exports.verify = function verify(algorithm, key, signature, data) {
const digest = crypto.createHmac(key.algorithm.hash.name, key._handle).update(data).digest();
if (ArrayBuffer.isView(signature)) {
signature = Buffer.coerce(signature);
} else {
signature = Buffer.from(signature);
}
return signature.equals(digest);
};
exports.generateKey = function generateKey(algorithm, extractable, usages) {
for (const usage of usages) {
if (usage !== "sign" && usage !== "verify") {
throw new SyntaxError(`Usage '${usage}' cannot be used for the HMAC generateKey() operation`);
}
}
const { length = exports.getKeyLength(algorithm) } = algorithm.length;
let hash = algorithm.hash;
if (typeof hash === "string") hash = { name: hash };
const key = crypto.createHmac(hash.name, crypto.randomBytes(length)).digest();
return new CryptoKey(
"secret",
extractable,
{
name: "HMAC",
length,
hash: {
name: hash.name.toUpperCase()
}
},
usages,
key
);
};
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
for (const usage of usages) {
if (usage !== "sign" && usage !== "verify") {
throw new SyntaxError(`Invalid usage ${usage}`);
}
}
let hash = algorithm.hash;
if (typeof hash === "string") hash = { name: hash };
let data;
switch (format) {
case "raw":
data = keyData;
break;
case "jwk":
const jwk = keyData;
if (jwk.kty !== "oct") {
throw errors.INVALID_DATA("JWK key must be an octet sequence");
}
data = Buffer.from(jwk.k, "base64url");
switch (hash.name.toLowerCase()) {
case "sha-1":
if (jwk.alg === "HS1") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
case "sha-256":
if (jwk.alg === "HS256") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
case "sha-384":
if (jwk.alg === "HS384") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
case "sha-512":
if (jwk.alg === "HS512") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
}
if (usages.length && "use" in jwk && jwk.use !== "sign") {
throw errors.INVALID_DATA("JWK cannot be used for signing");
}
if ("ext" in jwk && jwk.ext !== extractable && extractable) {
throw errors.INVALID_DATA("JWK is not extractable");
}
break;
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the HMAC importKey() operation`
);
}
const length = data.byteLength * 8;
if (length === 0) {
throw errors.INVALID_DATA("Key cannot be empty");
}
return new CryptoKey(
"secret",
extractable,
{
name: "HMAC",
length,
hash: {
name: hash.name.toUpperCase()
}
},
usages,
data
);
};
exports.exportKey = function exportKey(format, key) {
const data = key._handle;
switch (format) {
case "raw":
return data.buffer.slice(0, data.byteLength);
case "jwk": {
const jwk = {
kty: "oct",
k: data.toString("base64url"),
alg: null,
key_ops: key.usages,
ext: key.extractable
};
switch (key.algorithm.hash.name) {
case "SHA-1":
jwk.alg = "HS1";
break;
case "SHA-256":
jwk.alg = "HS256";
break;
case "SHA-384":
jwk.alg = "HS384";
break;
case "SHA-512":
jwk.alg = "HS512";
break;
}
return jwk;
}
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the HMAC exportKey() operation`
);
}
};
exports.getKeyLength = function getKeyLength(algorithm) {
const { length, hash } = algorithm;
if (length === void 0) {
if (hash === "SHA-1" || hash === "SHA-256") return 512;
if (hash === "SHA-512") return 1024;
throw errors.OPERATION_ERROR(`Invalid hash '${hash}'`);
}
if (length === 0) {
throw errors.OPERATION_ERROR(`Invalid length ${length}`);
}
return length;
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/pbkdf2.js
var require_pbkdf22 = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/pbkdf2.js"(exports) {
var crypto = require_bare_crypto();
var errors = require_errors();
var CryptoKey = require_crypto_key();
exports.deriveBits = function deriveBits(algorithm, key, length) {
if (length === void 0 || length % 8) {
throw errors.OPERATION_ERROR("Length must be multiple of 8");
}
if (algorithm.iterations === 0) {
throw errors.OPERATION_ERROR("Iterations must be non-0");
}
if (length === 0) {
return new ArrayBuffer(0);
}
let hash = algorithm.hash;
if (typeof hash === "string") hash = { name: hash };
const result = crypto.pbkdf2(
key._handle,
algorithm.salt,
algorithm.iterations,
length / 8,
hash.name
);
return result.buffer;
};
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
if (format !== "raw") {
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the PBKDF2 importKey() operation`
);
}
for (const usage of usages) {
if (usage !== "deriveKey" && usage !== "deriveBits") {
throw new SyntaxError(`Invalid usage ${usage}`);
}
}
if (extractable) {
throw new SyntaxError("Extractable must be false");
}
return new CryptoKey(
"secret",
extractable,
{
name: "PBKDF2"
},
usages,
keyData
);
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/ed25519.js
var require_ed25519 = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/ed25519.js"(exports) {
var crypto = require_bare_crypto();
var binding = require_binding3();
var errors = require_errors();
var { Ed25519PublicKey, Ed25519PrivateKey } = require_key();
var CryptoKey = require_crypto_key();
exports.sign = function sign(algorithm, key, data) {
if (key.type !== "private") {
throw errors.INVALID_ACCESS("Must pass private key for Ed25519 signing");
}
const signature = crypto.sign(null, data, key._handle);
return signature.buffer.slice(0, signature.byteLength);
};
exports.verify = function verify(algorithm, key, signature, data) {
if (key.type !== "public") {
throw errors.INVALID_ACCESS("Must pass public key for Ed25519 verification");
}
return crypto.verify(null, data, key._handle, signature);
};
exports.generateKey = function generateKey(algorithm, extractable, usages) {
for (const usage of usages) {
if (usage !== "sign" && usage !== "verify") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 generateKey() operation`
);
}
}
const keys = crypto.generateKeyPair("ed25519");
algorithm = { name: "Ed25519" };
return {
publicKey: new CryptoKey("public", true, algorithm, ["verify"], keys.publicKey),
privateKey: new CryptoKey("private", extractable, algorithm, ["sign"], keys.privateKey)
};
};
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
switch (format) {
case "spki":
for (const usage of usages) {
if (usage !== "verify") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
);
}
}
keyData = binding.ed25519FromSPKI(keyData.buffer, keyData.byteOffset, keyData.byteLength);
return new CryptoKey(
"public",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PublicKey(keyData)
);
case "pkcs8":
for (const usage of usages) {
if (usage !== "sign") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
);
}
}
keyData = binding.ed25519FromPKCS8(keyData.buffer, keyData.byteOffset, keyData.byteLength);
return new CryptoKey(
"private",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PrivateKey(keyData)
);
case "raw":
for (const usage of usages) {
if (usage !== "verify") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
);
}
}
if (keyData.byteLength * 8 !== 256) {
throw errors.INVALID_DATA("Key must be 256 bits");
}
return new CryptoKey(
"public",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PublicKey(keyData.buffer)
);
case "jwk":
const jwk = keyData;
if ("d" in jwk) {
if (usages.some((usage) => usage !== "sign")) {
throw new SyntaxError("JWK must be valid for signing");
}
} else {
if (usages.some((usage) => usage !== "verify")) {
throw new SyntaxError("JWK must be valid for verification");
}
}
if (jwk.kty !== "OKP") {
throw errors.INVALID_DATA("JWK key must be an octet key-pair");
}
if (jwk.crv !== "Ed25519") {
throw errors.INVALID_DATA("JWK must use the Ed25519 curve");
}
if ("alg" in jwk && jwk.alg !== "Ed25519" && jwk.alg !== "EdDSA") {
throw errors.INVALID_DATA("JWK must use the Ed25519 curve");
}
if (usages.length && "use" in jwk && jwk.use !== "sig") {
throw errors.INVALID_DATA("JWK cannot be used for signatures");
}
if ("ext" in jwk && jwk.ext !== extractable && extractable) {
throw errors.INVALID_DATA("JWK is not extractable");
}
if ("d" in jwk) {
const key2 = Buffer.concat([
Buffer.from(jwk.d, "base64url"),
Buffer.from(jwk.x, "base64url")
]);
if (key2.byteLength * 8 !== 512) {
throw errors.INVALID_DATA("Key must be 512 bits");
}
return new CryptoKey(
"private",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PrivateKey(key2.buffer)
);
}
const key = Buffer.from(jwk.x, "base64url");
if (key.byteLength * 8 !== 256) {
throw errors.INVALID_DATA("Key must be 256 bits");
}
return new CryptoKey(
"public",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PublicKey(key.buffer)
);
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the Ed25519 importKey() operation`
);
}
};
exports.exportKey = function exportKey(format, key) {
const data = key._handle;
switch (format) {
case "spki":
if (key.type !== "public") {
throw errors.INVALID_ACCESS(
`Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
);
}
return binding.ed25519ToSPKI(data._key);
case "pkcs8":
if (key.type !== "private") {
throw errors.INVALID_ACCESS(
`Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
);
}
return binding.ed25519ToPKCS8(data._key);
case "raw": {
if (key.type !== "public") {
throw errors.INVALID_ACCESS(
`Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
);
}
return data._key.slice();
}
case "jwk": {
const buffer = Buffer.from(data._key);
if (key.type === "private") {
const d = buffer.subarray(0, 32).toString("base64url");
const x = buffer.subarray(32).toString("base64url");
return {
kty: "OKP",
alg: "Ed25519",
crv: "Ed25519",
x,
d,
key_ops: key.usages,
ext: key.extractable
};
}
return {
kty: "OKP",
alg: "Ed25519",
crv: "Ed25519",
x: buffer.toString("base64url"),
key_ops: key.usages,
ext: key.extractable
};
}
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the HMAC exportKey() operation`
);
}
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/sha.js
var require_sha = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/sha.js"(exports) {
var crypto = require_bare_crypto();
exports.digest = function digest(name, data) {
const digest2 = crypto.createHash(name).update(data).digest();
return digest2.buffer.slice(0, digest2.byteLength);
};
}
});
// ../../node_modules/bare-crypto/web.js
var require_web3 = __commonJS({
"../../node_modules/bare-crypto/web.js"(exports) {
var crypto = require_bare_crypto();
var errors = require_errors();
var CryptoKey = require_crypto_key();
var hmac = require_hmac2();
var pbkdf2 = require_pbkdf22();
var ed25519 = require_ed25519();
var sha = require_sha();
exports.CryptoKey = CryptoKey;
exports.getRandomValues = function getRandomValues(array) {
return crypto.randomFillSync(array);
};
exports.randomUUID = crypto.randomUUID;
exports.SubtleCrypto = class SubtleCrypto {
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-generateKey
async generateKey(algorithm, extractable, usages) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.generateKey(algorithm, extractable, usages);
case "ed25519":
return ed25519.generateKey(algorithm, extractable, usages);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the generateKey() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
async importKey(format, keyData, algorithm, extractable, usages) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
switch (format) {
case "raw":
case "pkcs8":
case "spki":
if (ArrayBuffer.isView(keyData)) {
keyData = Buffer.from(keyData);
} else {
keyData = Buffer.from(keyData.slice());
}
break;
}
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.importKey(format, keyData, algorithm, extractable, usages);
case "ed25519":
return ed25519.importKey(format, keyData, algorithm, extractable, usages);
case "pbkdf2":
return pbkdf2.importKey(format, keyData, algorithm, extractable, usages);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the importKey() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-exportKey
async exportKey(format, key) {
if (!key.extractable) {
throw errors.INVALID_ACCESS("Key is not extractable");
}
switch (key.algorithm.name.toLowerCase()) {
case "hmac":
return hmac.exportKey(format, key);
case "ed25519":
return ed25519.exportKey(format, key);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${key.algorithm.name}' does not support the exportKey() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-sign
async sign(algorithm, key, data) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!key.usages.includes("sign")) {
throw errors.INVALID_ACCESS("Key cannot be used for signing");
}
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.sign(algorithm, key, data);
case "ed25519":
return ed25519.sign(algorithm, key, data);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the sign() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-verify
async verify(algorithm, key, signature, data) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!key.usages.includes("verify")) {
throw errors.INVALID_ACCESS("Key cannot be used for verification");
}
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.verify(algorithm, key, signature, data);
case "ed25519":
return ed25519.verify(algorithm, key, signature, data);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the verify() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveBits
async deriveBits(algorithm, key, length) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!key.usages.includes("deriveBits")) {
throw errors.INVALID_ACCESS("Key cannot be used to derive bits");
}
switch (algorithm.name.toLowerCase()) {
case "pbkdf2":
return pbkdf2.deriveBits(algorithm, key, length);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the deriveBits() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveKey
async deriveKey(algorithm, baseKey, derivedKeyType, extractable, usages) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (typeof derivedKeyType === "string") {
derivedKeyType = { name: derivedKeyType };
}
if (algorithm.name.toLowerCase() !== baseKey.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!baseKey.usages.includes("deriveKey")) {
throw errors.INVALID_ACCESS("Key cannot be used to derive key");
}
let length;
switch (derivedKeyType.name.toLowerCase()) {
case "hmac":
length = hmac.getKeyLength(derivedKeyType);
break;
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${derivedKeyType.name}' does not support the getKeyLength() operation`
);
}
let secret;
switch (algorithm.name.toLowerCase()) {
case "pbkdf2":
secret = pbkdf2.deriveBits(algorithm, baseKey, length);
break;
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the deriveBits() operation`
);
}
return this.importKey("raw", secret, derivedKeyType, extractable, usages);
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-digest
async digest(algorithm, data) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
switch (algorithm.name.toLowerCase()) {
case "sha-1":
return sha.digest(crypto.constants.hash.SHA1, data);
case "sha-256":
return sha.digest(crypto.constants.hash.SHA256, data);
case "sha-384":
return sha.digest(crypto.constants.hash.SHA384, data);
case "sha-512":
return sha.digest(crypto.constants.hash.SHA512, data);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the digest() operation`
);
}
}
};
exports.subtle = new exports.SubtleCrypto();
exports.Crypto = class Crypto {
get subtle() {
return exports.subtle;
}
getRandomValues(array) {
return exports.getRandomValues(array);
}
randomUUID() {
return exports.randomUUID();
}
};
}
});
// ../../node_modules/bare-crypto/global.js
var require_global2 = __commonJS({
"../../node_modules/bare-crypto/global.js"() {
var crypto = require_web3();
global.crypto = crypto;
global.Crypto = crypto.Crypto;
global.CryptoKey = crypto.CryptoKey;
global.SubtleCrypto = crypto.SubtleCrypto;
}
});
// ../../node_modules/bare-encoding/lib/utf8-decoder.js
var require_utf8_decoder2 = __commonJS({
"../../node_modules/bare-encoding/lib/utf8-decoder.js"(exports, module) {
module.exports = class UTF8Decoder {
constructor() {
this.codePoint = 0;
this.bytesSeen = 0;
this.bytesNeeded = 0;
this.lowerBoundary = 128;
this.upperBoundary = 191;
}
get remaining() {
return this.bytesSeen;
}
decode(data) {
if (ArrayBuffer.isView(data)) {
data = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
} else {
data = Buffer.from(data);
}
if (this.bytesNeeded === 0) {
let isBoundary = true;
for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength; i < n && isBoundary; i++) {
isBoundary = data[i] <= 127;
}
if (isBoundary) return data.toString("utf8");
}
let result = "";
for (let i = 0, n = data.byteLength; i < n; i++) {
const byte = data[i];
if (this.bytesNeeded === 0) {
if (byte <= 127) {
this.bytesSeen = 0;
result += String.fromCharCode(byte);
} else {
this.bytesSeen = 1;
if (byte >= 194 && byte <= 223) {
this.bytesNeeded = 2;
this.codePoint = byte & 31;
} else if (byte >= 224 && byte <= 239) {
if (byte === 224) this.lowerBoundary = 160;
else if (byte === 237) this.upperBoundary = 159;
this.bytesNeeded = 3;
this.codePoint = byte & 15;
} else if (byte >= 240 && byte <= 244) {
if (byte === 240) this.lowerBoundary = 144;
if (byte === 244) this.upperBoundary = 143;
this.bytesNeeded = 4;
this.codePoint = byte & 7;
} else {
result += "\uFFFD";
}
}
continue;
}
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
this.codePoint = 0;
this.bytesNeeded = 0;
this.bytesSeen = 0;
this.lowerBoundary = 128;
this.upperBoundary = 191;
result += "\uFFFD";
i--;
continue;
}
this.lowerBoundary = 128;
this.upperBoundary = 191;
this.codePoint = this.codePoint << 6 | byte & 63;
this.bytesSeen++;
if (this.bytesSeen !== this.bytesNeeded) continue;
result += String.fromCodePoint(this.codePoint);
this.codePoint = 0;
this.bytesNeeded = 0;
this.bytesSeen = 0;
}
return result;
}
flush() {
const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
this.codePoint = 0;
this.bytesNeeded = 0;
this.bytesSeen = 0;
this.lowerBoundary = 128;
this.upperBoundary = 191;
return result;
}
};
}
});
// ../../node_modules/bare-encoding/lib/pass-through-decoder.js
var require_pass_through_decoder2 = __commonJS({
"../../node_modules/bare-encoding/lib/pass-through-decoder.js"(exports, module) {
module.exports = class PassThroughDecoder {
constructor(encoding) {
this.encoding = encoding;
}
get remaining() {
return 0;
}
decode(data) {
if (ArrayBuffer.isView(data)) {
data = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
} else {
data = Buffer.from(data);
}
return data.toString(this.encoding);
}
flush() {
return "";
}
};
}
});
// ../../node_modules/bare-encoding/lib/errors.js
var require_errors2 = __commonJS({
"../../node_modules/bare-encoding/lib/errors.js"(exports, module) {
module.exports = class EncodingError extends Error {
constructor(msg, code, fn = EncodingError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "EncodingError";
}
static INVALID_LABEL(msg) {
return new EncodingError(msg, "INVALID_LABEL", EncodingError.INVALID_LABEL);
}
};
}
});
// ../../node_modules/bare-encoding/index.js
var require_bare_encoding = __commonJS({
"../../node_modules/bare-encoding/index.js"(exports) {
var UTF8Decoder = require_utf8_decoder2();
var PassThroughDecoder = require_pass_through_decoder2();
var errors = require_errors2();
exports.TextEncoder = class TextEncoder {
// https://encoding.spec.whatwg.org/#dom-textencoder-encoding
get encoding() {
return "utf-8";
}
// https://encoding.spec.whatwg.org/#dom-textencoder-encode
encode(input) {
return Buffer.from(input);
}
// https://encoding.spec.whatwg.org/#dom-textencoder-encodeinto
encodeInto(input, destination) {
if (ArrayBuffer.isView(destination)) {
destination = Buffer.from(
destination.buffer,
destination.byteOffset,
destination.byteLength
);
} else {
destination = Buffer.from(destination);
}
return {
read: input.length,
written: destination.write(input)
};
}
};
exports.TextDecoder = class TextDecoder {
// https://encoding.spec.whatwg.org/#dom-textdecoder
constructor(label = "utf-8") {
this.encoding = getEncoding(label);
switch (this.encoding) {
case "utf-8":
this.decoder = new UTF8Decoder();
break;
default:
this.decoder = new PassThroughDecoder(this.encoding);
break;
}
}
// https://encoding.spec.whatwg.org/#dom-textdecoder-decode
decode(input, options = {}) {
const result = this.decoder.decode(input);
if (options.stream) return result;
return result + this.decoder.flush();
}
};
function getEncoding(label) {
switch (label.trim().toLowerCase()) {
case "unicode-1-1-utf-8":
case "unicode11utf8":
case "unicode11utf8":
case "unicode20utf8":
case "utf-8":
case "utf8":
case "x-unicode20utf8":
return "utf-8";
default:
throw errors.INVALID_LABEL(`The label '${label}' is not a valid encoding`);
}
}
}
});
// ../../node_modules/bare-encoding/global.js
var require_global3 = __commonJS({
"../../node_modules/bare-encoding/global.js"() {
var encoding = require_bare_encoding();
global.TextDecoder = encoding.TextDecoder;
global.TextEncoder = encoding.TextEncoder;
}
});
// ../../node_modules/bare-events/global.js
var require_global4 = __commonJS({
"../../node_modules/bare-events/global.js"() {
var events = require_web();
global.Event = events.Event;
global.CustomEvent = events.CustomEvent;
global.EventTarget = events.EventTarget;
}
});
// ../../node_modules/bare-http1/lib/incoming-message.js
var require_incoming_message = __commonJS({
"../../node_modules/bare-http1/lib/incoming-message.js"(exports, module) {
var { Readable } = require_bare_stream();
module.exports = class HTTPIncomingMessage extends Readable {
constructor(socket = null, opts = {}) {
super();
this._socket = socket;
this._upgrade = false;
this._headers = opts.headers || {};
this._method = opts.method || "";
this._url = opts.url || "";
this._statusCode = opts.statusCode || 0;
this._statusMessage = opts.statusMessage || "";
}
get socket() {
return this._socket;
}
get upgrade() {
return this._upgrade;
}
get headers() {
return this._headers;
}
set headers(value) {
this._headers = value;
}
get method() {
return this._method;
}
set method(value) {
this._method = value;
}
get url() {
return this._url;
}
set url(value) {
this._url = value;
}
get statusCode() {
return this._statusCode;
}
set statusCode(value) {
this._statusCode = value;
}
get statusMessage() {
return this._statusMessage;
}
set statusMessage(value) {
this._statusMessage = value;
}
get httpVersion() {
return "1.1";
}
getHeader(name) {
return this._headers[name.toLowerCase()];
}
getHeaders() {
return { ...this._headers };
}
hasHeader(name) {
return name.toLowerCase() in this._headers;
}
setTimeout(ms, ontimeout) {
if (ontimeout) this.once("timeout", ontimeout);
this._socket.setTimeout(ms);
return this;
}
_predestroy() {
if (this._upgrade === false && this._socket !== null) this._socket.destroy();
}
};
}
});
// ../../node_modules/bare-http1/lib/errors.js
var require_errors3 = __commonJS({
"../../node_modules/bare-http1/lib/errors.js"(exports, module) {
module.exports = class HTTPError extends Error {
constructor(msg, fn = HTTPError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "HTTPError";
}
static NOT_IMPLEMENTED(msg = "Method not implemented") {
return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED);
}
static CONNECTION_LOST(msg = "Socket hung up") {
return new HTTPError(msg, HTTPError.CONNECTION_LOST);
}
static AGENT_SUSPENDED(msg = "Agent is suspended") {
return new HTTPError(msg, HTTPError.AGENT_SUSPENDED);
}
};
}
});
// ../../node_modules/bare-http1/lib/outgoing-message.js
var require_outgoing_message = __commonJS({
"../../node_modules/bare-http1/lib/outgoing-message.js"(exports, module) {
var { Writable } = require_bare_stream();
var errors = require_errors3();
module.exports = class HTTPOutgoingMessage extends Writable {
constructor(socket = null) {
super();
this._socket = socket;
this._upgrade = false;
this._headersSent = false;
this._headers = {};
}
get socket() {
return this._socket;
}
get upgrade() {
return this._upgrade;
}
get headersSent() {
return this._headersSent;
}
get headers() {
return this._headers;
}
set headers(value) {
this._headers = value;
}
getHeader(name) {
return this._headers[name.toLowerCase()];
}
getHeaders() {
return { ...this._headers };
}
hasHeader(name) {
return name.toLowerCase() in this._headers;
}
setHeader(name, value) {
this._headers[name.toLowerCase()] = value;
}
flushHeaders() {
if (this._headersSent === true || this._socket === null) return;
this._socket.write(Buffer.from(this._header()));
this._headersSent = true;
}
setTimeout(ms, ontimeout) {
if (ontimeout) this.once("timeout", ontimeout);
this._socket.setTimeout(ms);
return this;
}
_header() {
throw errors.NOT_IMPLEMENTED();
}
_predestroy() {
if (this._upgrade === false && this._socket !== null) this._socket.destroy();
}
};
}
});
// ../../node_modules/bare-events/lib/errors.js
var require_errors4 = __commonJS({
"../../node_modules/bare-events/lib/errors.js"(exports, module) {
module.exports = class EventEmitterError extends Error {
constructor(msg, code, fn = EventEmitterError, opts) {
super(`${code}: ${msg}`, opts);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "EventEmitterError";
}
static OPERATION_ABORTED(cause, msg = "Operation aborted") {
return new EventEmitterError(msg, "OPERATION_ABORTED", EventEmitterError.OPERATION_ABORTED, {
cause
});
}
static UNHANDLED_ERROR(cause, msg = "Unhandled error") {
return new EventEmitterError(msg, "UNHANDLED_ERROR", EventEmitterError.UNHANDLED_ERROR, {
cause
});
}
};
}
});
// ../../node_modules/bare-events/index.js
var require_bare_events = __commonJS({
"../../node_modules/bare-events/index.js"(exports, module) {
var errors = require_errors4();
var EventListener = class {
constructor() {
this.list = [];
this.count = 0;
}
append(ctx, name, fn, once) {
this.count++;
ctx.emit("newListener", name, fn);
this.list.push([fn, once]);
}
prepend(ctx, name, fn, once) {
this.count++;
ctx.emit("newListener", name, fn);
this.list.unshift([fn, once]);
}
remove(ctx, name, fn) {
for (let i = 0, n = this.list.length; i < n; i++) {
const l = this.list[i];
if (l[0] === fn) {
this.list.splice(i, 1);
if (this.count === 1) delete ctx._events[name];
ctx.emit("removeListener", name, fn);
this.count--;
return;
}
}
}
removeAll(ctx, name) {
const list = [...this.list];
this.list = [];
if (this.count === list.length) delete ctx._events[name];
for (let i = list.length - 1; i >= 0; i--) {
ctx.emit("removeListener", name, list[i][0]);
}
this.count -= list.length;
}
emit(ctx, name, ...args) {
const list = [...this.list];
for (let i = 0, n = list.length; i < n; i++) {
const l = list[i];
if (l[1] === true) this.remove(ctx, name, l[0]);
Reflect.apply(l[0], ctx, args);
}
return list.length > 0;
}
};
function appendListener(ctx, name, fn, once) {
if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null);
const e = ctx._events[name] || (ctx._events[name] = new EventListener());
e.append(ctx, name, fn, once);
return ctx;
}
function prependListener(ctx, name, fn, once) {
if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null);
const e = ctx._events[name] || (ctx._events[name] = new EventListener());
e.prepend(ctx, name, fn, once);
return ctx;
}
function removeListener(ctx, name, fn) {
if (ctx._events === void 0) return ctx;
const e = ctx._events[name];
if (e !== void 0) e.remove(ctx, name, fn);
return ctx;
}
function throwUnhandledError(...args) {
let err;
if (args.length > 0) err = args[0];
if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err);
if (Error.captureStackTrace) {
Error.captureStackTrace(err, exports.prototype.emit);
}
queueMicrotask(() => {
throw err;
});
}
module.exports = exports = class EventEmitter {
constructor() {
this._events = /* @__PURE__ */ Object.create(null);
}
addListener(name, fn) {
return appendListener(this, name, fn, false);
}
addOnceListener(name, fn) {
return appendListener(this, name, fn, true);
}
prependListener(name, fn) {
return prependListener(this, name, fn, false);
}
prependOnceListener(name, fn) {
return prependListener(this, name, fn, true);
}
removeListener(name, fn) {
return removeListener(this, name, fn);
}
on(name, fn) {
return appendListener(this, name, fn, false);
}
once(name, fn) {
return appendListener(this, name, fn, true);
}
off(name, fn) {
return removeListener(this, name, fn);
}
emit(name, ...args) {
if (name === "error" && this._events !== void 0 && this._events.error === void 0) {
throwUnhandledError(...args);
}
if (this._events === void 0) return false;
const e = this._events[name];
return e === void 0 ? false : e.emit(this, name, ...args);
}
listeners(name) {
if (this._events === void 0) return [];
const e = this._events[name];
return e === void 0 ? [] : [...e.list];
}
listenerCount(name) {
if (this._events === void 0) return 0;
const e = this._events[name];
return e === void 0 ? 0 : e.list.length;
}
getMaxListeners() {
return EventEmitter.defaultMaxListeners;
}
setMaxListeners(n) {
}
removeAllListeners(name) {
if (arguments.length === 0) {
for (const key of Reflect.ownKeys(this._events)) {
if (key === "removeListener") continue;
this.removeAllListeners(key);
}
this.removeAllListeners("removeListener");
} else {
const e = this._events[name];
if (e !== void 0) e.removeAll(this, name);
}
return this;
}
};
exports.EventEmitter = exports;
exports.errors = errors;
exports.defaultMaxListeners = 10;
exports.on = function on(emitter, name, opts = {}) {
const { signal } = opts;
if (signal && signal.aborted) {
throw errors.OPERATION_ABORTED(signal.reason);
}
let error = null;
let done = false;
const events = [];
const promises = [];
if (name !== "error") emitter.on("error", onerror);
if (signal) signal.addEventListener("abort", onabort);
emitter.on(name, onevent);
return {
next() {
if (events.length) {
return Promise.resolve({ value: events.shift(), done: false });
}
if (error) {
const err = error;
error = null;
return Promise.reject(err);
}
if (done) return onclose();
return new Promise((resolve, reject) => promises.push({ resolve, reject }));
},
return() {
return onclose();
},
throw(err) {
return onerror(err);
},
[Symbol.asyncIterator]() {
return this;
}
};
function onevent(...args) {
if (promises.length) {
promises.shift().resolve({ value: args, done: false });
} else {
events.push(args);
}
}
function onerror(err) {
emitter.off(name, onevent).off("error", onerror);
if (promises.length) {
promises.shift().reject(err);
} else {
error = err;
}
return Promise.resolve({ done: true });
}
function onabort() {
signal.removeEventListener("abort", onabort);
onerror(errors.OPERATION_ABORTED(signal.reason));
}
function onclose() {
emitter.off(name, onevent);
if (name !== "error") emitter.off("error", onerror);
if (signal) signal.removeEventListener("abort", onabort);
done = true;
if (promises.length) promises.shift().resolve({ done: true });
return Promise.resolve({ done: true });
}
};
exports.once = function once(emitter, name, opts = {}) {
const { signal } = opts;
if (signal && signal.aborted) {
return Promise.reject(errors.OPERATION_ABORTED(signal.reason));
}
return new Promise((resolve, reject) => {
if (name !== "error") emitter.on("error", onerror);
if (signal) signal.addEventListener("abort", onabort);
emitter.once(name, onevent);
function onevent(...args) {
if (name !== "error") emitter.off("error", onerror);
if (signal) signal.removeEventListener("abort", onabort);
resolve(args);
}
function onerror(err) {
emitter.off(name, onevent);
if (name !== "error") emitter.off("error", onerror);
reject(err);
}
function onabort() {
signal.removeEventListener("abort", onabort);
onerror(errors.OPERATION_ABORTED(signal.reason));
}
});
};
exports.forward = function forward(from, to, names, opts = {}) {
if (typeof names === "string") names = [names];
const { emit = to.emit.bind(to) } = opts;
const listeners = names.map(
(name) => function onevent(...args) {
emit(name, ...args);
}
);
to.on("newListener", (name) => {
const i = names.indexOf(name);
if (i !== -1 && to.listenerCount(name) === 0) {
from.on(name, listeners[i]);
}
}).on("removeListener", (name) => {
const i = names.indexOf(name);
if (i !== -1 && to.listenerCount(name) === 0) {
from.off(name, listeners[i]);
}
});
};
exports.listenerCount = function listenerCount(emitter, name) {
return emitter.listenerCount(name);
};
exports.getMaxListeners = function getMaxListeners(emitter) {
if (typeof emitter.getMaxListeners === "function") {
return emitter.getMaxListeners();
}
return exports.defaultMaxListeners;
};
exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
if (emitters.length === 0) exports.defaultMaxListeners = n;
else {
for (const emitter of emitters) {
if (typeof emitter.setMaxListeners === "function") {
emitter.setMaxListeners(n);
}
}
}
};
}
});
// ../../node_modules/bare-dns/binding.js
var require_binding4 = __commonJS({
"../../node_modules/bare-dns/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-dns/index.js
var require_bare_dns = __commonJS({
"../../node_modules/bare-dns/index.js"(exports) {
var binding = require_binding4();
exports.Resolver = class DNSResolver {
constructor() {
this._handle = binding.initResolver();
}
resolveTxt(hostname, cb = noop) {
binding.resolveTxt(this._handle, hostname, cb, this);
}
destroy() {
binding.destroyResolver(this._handle);
this._handle = null;
}
static global = new this();
};
function onlookup(err, addresses) {
const req = this;
if (err) return req.cb(err, null, 0);
const { address, family } = addresses[0];
return req.cb(null, address, family);
}
function onlookupall(err, addresses) {
const req = this;
if (err) return req.cb(err, null);
return req.cb(null, addresses);
}
exports.lookup = function lookup(hostname, opts = {}, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
let { family = 0, all = false } = opts;
if (typeof family === "string") {
switch (family) {
case "IPv4":
family = 4;
break;
case "IPv6":
family = 6;
break;
default:
family = 0;
}
}
const req = {
cb,
handle: null
};
req.handle = binding.lookup(
hostname,
family || 0,
all,
req,
all ? onlookupall : onlookup
);
};
exports.resolveTxt = function resolveTxt(hostname, cb) {
exports.Resolver.global.resolveTxt(hostname, cb);
};
function noop() {
}
}
});
// ../../node_modules/bare-tcp/binding.js
var require_binding5 = __commonJS({
"../../node_modules/bare-tcp/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tcp/lib/constants.js
var require_constants2 = __commonJS({
"../../node_modules/bare-tcp/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTING: 1,
CONNECTED: 2,
BINDING: 4,
BOUND: 8,
READING: 16,
CLOSING: 32,
UNREFED: 64
}
};
}
});
// ../../node_modules/bare-tcp/lib/errors.js
var require_errors5 = __commonJS({
"../../node_modules/bare-tcp/lib/errors.js"(exports, module) {
module.exports = class TCPError extends Error {
constructor(msg, fn = TCPError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "TCPError";
}
static SOCKET_ALREADY_CONNECTED(msg) {
return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED);
}
static SERVER_ALREADY_LISTENING(msg) {
return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING);
}
static SERVER_IS_CLOSED(msg) {
return new TCPError(msg, TCPError.SERVER_IS_CLOSED);
}
static INVALID_HOST(msg = "Unrecognizable host format") {
return new TCPError(msg, TCPError.INVALID_HOST);
}
};
}
});
// ../../node_modules/bare-tcp/lib/ip.js
var require_ip = __commonJS({
"../../node_modules/bare-tcp/lib/ip.js"(exports) {
var v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
var v4Str = `(${v4Seg}[.]){3}${v4Seg}`;
var IPv4Pattern = new RegExp(`^${v4Str}$`);
var v6Seg = "(?:[0-9a-fA-F]{1,4})";
var IPv6Pattern = new RegExp(
`^((?:${v6Seg}:){7}(?:${v6Seg}|:)|(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$`
);
var isIPv4 = exports.isIPv4 = function isIPv42(host) {
return IPv4Pattern.test(host);
};
var isIPv6 = exports.isIPv6 = function isIPv62(host) {
return IPv6Pattern.test(host);
};
exports.isIP = function isIP(host) {
if (isIPv4(host)) return 4;
if (isIPv6(host)) return 6;
return 0;
};
}
});
// ../../node_modules/bare-tcp/index.js
var require_bare_tcp = __commonJS({
"../../node_modules/bare-tcp/index.js"(exports) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var dns = require_bare_dns();
var binding = require_binding5();
var constants = require_constants2();
var errors = require_errors5();
var ip = require_ip();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
exports.Socket = class TCPSocket extends Duplex {
constructor(opts = {}) {
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts;
super({ eagerOpen });
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._keepAlive = 0;
this._keepAliveInitialDelay = 0;
this._noDelay = 0;
this._localAddress = null;
this._remoteAddress = null;
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
this._timer = null;
this._timeout = 0;
this._buffer = Buffer.alloc(readBufferSize);
this._addresses = null;
this._errors = null;
this._handle = binding.init(
this._buffer,
this,
noop,
this._onconnect,
this._onreset,
this._onread,
this._onwrite,
this._onfinal,
this._onclose
);
}
get connecting() {
return (this._state & constants.state.CONNECTING) !== 0;
}
get pending() {
return (this._state & constants.state.CONNECTED) === 0;
}
get timeout() {
return this._timeout || void 0;
}
get readyState() {
if (this._state & constants.state.CONNECTED) {
return "open";
}
return "opening";
}
get localAddress() {
if (this._localAddress) return this._localAddress.address;
}
get localFamily() {
if (this._localAddress) return `IPv${this._localAddress.family}`;
}
get localPort() {
if (this._localAddress) return this._localAddress.port;
}
get remoteAddress() {
if (this._remoteAddress) return this._remoteAddress.address;
}
get remoteFamily() {
if (this._remoteAddress) return `IPv${this._remoteAddress.family}`;
}
get remotePort() {
if (this._remoteAddress) return this._remoteAddress.port;
}
connect(port, host = "localhost", opts = {}, onconnect) {
if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
throw errors.SOCKET_ALREADY_CONNECTED("Socket is already connected");
}
this._state |= constants.state.CONNECTING;
if (typeof host === "function") {
onconnect = host;
host = "localhost";
} else if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
let family = 0;
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
family = opts.family || 0;
}
if (!host) host = "localhost";
const {
lookup = dns.lookup,
hints,
keepAlive = false,
keepAliveInitialDelay = 0,
noDelay = false,
timeout
} = opts;
const type = ip.isIP(host);
if (type === 0) {
lookup(host, { all: true, family, hints }, (err, addresses) => {
if (this._state & constants.state.CLOSING) return;
this._state &= ~constants.state.CONNECTING;
if (err || addresses.length === 0) {
if (!err) {
err = new Error(`No address found for host "${host}"`);
err.code = "ENOTFOUND";
}
this.emit("lookup", err, null, 0, host);
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
for (const { address: address2, family: family3 } of addresses) {
this.emit("lookup", null, address2, family3, host);
}
const [{ address, family: family2 }, ...rest] = addresses;
if (rest.length > 0) {
this._addresses = rest.map(({ address: address2, family: family3 }) => [
port,
address2,
{ ...opts, family: family3 },
onconnect
]);
this._errors = [];
}
this.connect(port, address, { ...opts, family: family2 }, onconnect);
});
return this;
}
family = type;
try {
binding.connect(this._handle, port, host, family);
if (keepAlive) {
this._keepAlive = keepAlive;
this._keepAliveInitialDelay = keepAliveInitialDelay;
}
if (noDelay) this._noDelay = noDelay;
if (timeout) this.setTimeout(timeout);
if (onconnect) this.once("connect", onconnect);
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
setKeepAlive(enable = false, delay = 0) {
if (typeof enable === "number") {
delay = enable;
enable = false;
}
delay = Math.floor(delay / 1e3);
if (delay === 0) enable = false;
binding.keepalive(this._handle, enable, delay);
return this;
}
setNoDelay(enable = true) {
binding.nodelay(this._handle, enable);
return this;
}
setTimeout(ms, ontimeout) {
if (ms === 0) {
clearTimeout(this._timer);
this._timer = null;
} else {
if (ontimeout) this.once("timeout", ontimeout);
this._timer = setTimeout(() => this.emit("timeout"), ms);
this._timer.unref();
}
this._timeout = ms;
return this;
}
ref() {
binding.ref(this._handle);
return this;
}
unref() {
binding.unref(this._handle);
return this;
}
_open(cb) {
if (this._state & constants.state.CONNECTED) return cb(null);
this._pendingOpen = cb;
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(this._handle);
}
}
_writev(batch, cb) {
this._pendingWrite = [cb, batch];
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
}
_final(cb) {
this._pendingFinal = cb;
binding.end(this._handle);
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
}
_continueOpen(err) {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite[0];
this._pendingWrite = null;
cb(err);
}
_continueFinal(err) {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_reset() {
this._state = 0;
this._localAddress = null;
this._remoteAddress = null;
binding.reset(this._handle);
}
_onconnect(err) {
if (err) {
if (this._addresses !== null) {
this._errors.push(err);
if (this._addresses.length > 0) return this._reset();
err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors);
}
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay);
if (this._noDelay) this.setNoDelay();
this._localAddress = binding.address(this._handle, true);
this._remoteAddress = binding.address(this._handle, false);
this._state |= constants.state.CONNECTED;
this._state &= ~constants.state.CONNECTING;
this._continueOpen();
this.emit("connect");
}
_onreset(err) {
if (err) {
this._errors.push(err);
this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors));
return;
}
this.connect(...this._addresses.shift());
}
_onread(err, read) {
if (this._timer) this._timer.refresh();
if (err) {
this.destroy(err);
return;
}
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
if (this.push(copy) === false && this.destroying === false) {
this._state &= ~constants.state.READING;
binding.pause(this._handle);
}
}
_onwrite(err) {
if (this._timer) this._timer.refresh();
this._continueWrite(err);
}
_onfinal(err) {
this._continueFinal(err);
}
_onclose() {
clearTimeout(this._timer);
this._continueDestroy();
}
};
exports.Server = class TCPServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = true,
keepAlive = false,
keepAliveInitialDelay = 0,
noDelay = false,
pauseOnConnect = false
} = opts;
this._state = 0;
this._readBufferSize = readBufferSize;
this._allowHalfOpen = allowHalfOpen;
this._keepAlive = keepAlive;
this._keepAliveInitialDelay = keepAliveInitialDelay;
this._noDelay = noDelay;
this._pauseOnConnect = pauseOnConnect;
this._address = null;
this._connections = /* @__PURE__ */ new Set();
this._error = null;
this._handle = null;
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return (this._state & constants.state.BOUND) !== 0;
}
get closing() {
return (this._state & constants.state.CLOSING) !== 0;
}
get connections() {
return this._connections;
}
address() {
if ((this._state & constants.state.BOUND) === 0) return null;
const { address, family, port } = this._address;
return { address, family: `IPv${family}`, port };
}
listen(port = 0, host = "localhost", backlog = 511, opts = {}, onlistening) {
if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
throw errors.SERVER_ALREADY_LISTENING("Server is already listening");
}
if (this._state & constants.state.CLOSING) {
throw errors.SERVER_IS_CLOSED("Server is closed");
}
this._state |= constants.state.BINDING;
if (typeof port === "function") {
onlistening = port;
port = 0;
} else if (typeof host === "function") {
onlistening = host;
host = "localhost";
} else if (typeof backlog === "function") {
onlistening = backlog;
backlog = 511;
} else if (typeof opts === "function") {
onlistening = opts;
opts = {};
}
let family = 0;
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
family = opts.family || 0;
backlog = opts.backlog || 511;
}
if (!host) host = "localhost";
if (!backlog) backlog = 511;
const { lookup = dns.lookup, hints } = opts;
const type = ip.isIP(host);
if (type === 0) {
lookup(host, { family, hints }, (err, address, family2) => {
if (this._state & constants.state.CLOSING) return;
this.emit("lookup", err, address, family2, host);
this._state &= ~constants.state.BINDING;
if (err) return this.emit("error", err);
this.listen(port, address, backlog, { ...opts, family: family2 }, onlistening);
});
return this;
}
family = type;
this._handle = binding.init(
empty,
this,
this._onconnection,
noop,
noop,
noop,
noop,
noop,
this._onclose
);
if (this._state & constants.state.UNREFED) binding.unref(this._handle);
try {
binding.bind(this._handle, port, host, backlog, family);
this._address = binding.address(this._handle, true);
this._state |= constants.state.BOUND;
this._state &= ~constants.state.BINDING;
if (onlistening) this.once("listening", onlistening);
queueMicrotask(() => this.emit("listening"));
} catch (err) {
this._error = err;
binding.close(this._handle);
}
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
if (this._state & constants.state.CLOSING) return this;
this._state |= constants.state.CLOSING;
this._closeMaybe();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._handle !== null) binding.ref(this._handle);
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._handle !== null) binding.unref(this._handle);
return this;
}
_closeMaybe() {
if (this._state & constants.state.CLOSING && this._connections.size === 0) {
if (this._handle !== null) binding.close(this._handle);
else queueMicrotask(() => this.emit("close"));
}
}
_onconnection(err) {
if (err) {
this.emit("error", err);
return;
}
if (this._state & constants.state.CLOSING) return;
const socket = new exports.Socket({
readBufferSize: this._readBufferSize,
allowHalfOpen: this._allowHalfOpen,
eagerOpen: !this._pauseOnConnect
});
try {
binding.accept(this._handle, socket._handle);
socket._localAddress = binding.address(socket._handle, true);
socket._remoteAddress = binding.address(socket._handle, false);
socket._state |= constants.state.CONNECTED;
this._connections.add(socket);
if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay);
if (this._noDelay) socket.setNoDelay();
socket.on("close", () => {
this._connections.delete(socket);
this._closeMaybe();
});
this.emit("connection", socket);
} catch (err2) {
socket.destroy();
this.emit("error", err2);
}
}
_onclose() {
const err = this._error;
this._state &= ~constants.state.BINDING;
this._error = null;
this._handle = null;
this._address = null;
if (err) this.emit("error", err);
else this.emit("close");
}
};
exports.constants = constants;
exports.errors = errors;
exports.isIP = ip.isIP;
exports.isIPv4 = ip.isIPv4;
exports.isIPv6 = ip.isIPv6;
exports.createConnection = function createConnection(port, host, opts, onconnect) {
if (typeof host === "function") {
onconnect = host;
host = "localhost";
} else if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
}
return new exports.Socket(opts).connect(port, host, opts, onconnect);
};
exports.connect = exports.createConnection;
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
function noop() {
}
}
});
// ../../node_modules/bare-http-parser/lib/errors.js
var require_errors6 = __commonJS({
"../../node_modules/bare-http-parser/lib/errors.js"(exports, module) {
module.exports = class HTTPParserError extends Error {
constructor(msg, fn = HTTPParserError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(this, fn);
}
get name() {
return "HTTPParserError";
}
static INVALID_MESSAGE(msg = "Invalid HTTP message") {
return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE);
}
static INVALID_HEADER(msg = "Invalid HTTP header") {
return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER);
}
static INVALID_CONTENT_LENGTH(msg = "Invalid HTTP Content-Length") {
return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH);
}
static INVALID_CHUNK_LENGTH(msg = "Invalid HTTP chunk length") {
return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH);
}
};
}
});
// ../../node_modules/bare-http-parser/index.js
var require_bare_http_parser = __commonJS({
"../../node_modules/bare-http-parser/index.js"(exports, module) {
var errors = require_errors6();
var constants = {
REQUEST: 1,
RESPONSE: 2,
DATA: 3,
END: 4
};
var TAB = 9;
var LF = 10;
var CR = 13;
var SP = 32;
var ZERO = 48;
var NINE = 57;
var UPPER_A = 65;
var UPPER_F = 70;
var UPPER_Z = 90;
var LOWER_A = 97;
var LOWER_F = 102;
var COLON = 58;
var MAX_CHUNK_SIZE_LENGTH = 16;
var FIRST_TOKEN = 0;
var REQUEST_URL = 1;
var REQUEST_VERSION = 2;
var STATUS_CODE = 3;
var STATUS_REASON = 4;
var FIRST_LINE_LF = 5;
var HEADER_START = 6;
var HEADER_NAME = 7;
var HEADER_VALUE_WS = 8;
var HEADER_VALUE = 9;
var HEADER_LINE_LF = 10;
var HEADER_END_LF = 11;
var BODY = 12;
var CHUNK_SIZE = 13;
var CHUNK_SIZE_LF = 14;
var CHUNK_DATA = 15;
var CHUNK_EXTENSION = 16;
var LAST_CHUNK_LF = 17;
var TRAILER_CR = 18;
var TRAILER_LF = 19;
module.exports = exports = class HTTPParser {
constructor(opts = {}) {
const { maxHeaderSize = 16384, maxHeadersCount = 2e3 } = opts;
this._maxHeaderSize = maxHeaderSize;
this._maxHeadersCount = maxHeadersCount;
this._state = FIRST_TOKEN;
this._buffer = [];
this._bufferIndex = 0;
this._byteIndex = 0;
this._buffered = 0;
this._accumulator = [];
this._isResponse = false;
this._method = "";
this._url = "";
this._version = "";
this._code = 0;
this._reason = "";
this._headerName = "";
this._headers = {};
this._headerCount = 0;
this._headerSize = 0;
this._remaining = 0;
}
*push(data, encoding) {
if (typeof data === "string") data = Buffer.from(data, encoding);
this._buffer.push(data);
this._buffered += data.byteLength;
yield* this._parse();
this._compact();
}
end() {
const buffers = this._buffer;
const bufferIndex = this._bufferIndex;
const byteIndex = this._byteIndex;
this._buffer = [];
this._bufferIndex = 0;
this._byteIndex = 0;
this._buffered = 0;
if (bufferIndex >= buffers.length) return Buffer.alloc(0);
buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex);
const remaining = buffers.slice(bufferIndex);
if (remaining.length === 0) return Buffer.alloc(0);
if (remaining.length === 1) return remaining[0];
return Buffer.concat(remaining);
}
_compact() {
if (this._bufferIndex > 0) {
this._buffer = this._buffer.slice(this._bufferIndex);
this._bufferIndex = 0;
}
if (this._byteIndex > 0 && this._buffer.length > 0) {
this._buffer[0] = this._buffer[0].subarray(this._byteIndex);
this._byteIndex = 0;
}
}
_consume(n) {
this._buffered -= n;
const current = this._buffer[this._bufferIndex];
if (this._byteIndex + n <= current.byteLength) {
const slice = current.subarray(this._byteIndex, this._byteIndex + n);
this._byteIndex += n;
if (this._byteIndex >= current.byteLength) {
this._bufferIndex++;
this._byteIndex = 0;
}
return slice;
}
const result = Buffer.allocUnsafe(n);
let written = 0;
while (written < n) {
const buffer = this._buffer[this._bufferIndex];
const available = buffer.byteLength - this._byteIndex;
const take = Math.min(available, n - written);
buffer.copy(result, written, this._byteIndex, this._byteIndex + take);
written += take;
this._byteIndex += take;
if (this._byteIndex >= buffer.byteLength) {
this._bufferIndex++;
this._byteIndex = 0;
}
}
return result;
}
_buildString() {
const string = String.fromCharCode.apply(null, this._accumulator);
this._accumulator = [];
return string;
}
_checkHeaderSize() {
if (++this._headerSize > this._maxHeaderSize) {
throw errors.INVALID_MESSAGE("Header exceeds limit of " + this._maxHeaderSize + " bytes");
}
}
_storeHeader(name, value) {
let end = value.length;
while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
end--;
}
if (end < value.length) value = value.substring(0, end);
this._headerCount++;
if (this._headerCount > this._maxHeadersCount) {
throw errors.INVALID_MESSAGE("Header count exceeds limit of " + this._maxHeadersCount);
}
switch (name) {
case "__proto__":
case "constructor":
case "prototype":
throw errors.INVALID_HEADER("Unsafe header name '" + name + "'");
case "host":
case "content-length":
case "transfer-encoding":
if (name in this._headers) {
throw errors.INVALID_HEADER("Duplicate header '" + name + "'");
}
this._headers[name] = value;
break;
default:
const delimiter = name === "cookie" ? "; " : ", ";
if (name in this._headers) {
this._headers[name] += delimiter + value;
} else {
this._headers[name] = value;
}
}
}
*_parse() {
while (true) {
if (this._state === BODY) {
if (this._buffered === 0) return;
const available = Math.min(this._buffered, this._remaining);
const data = this._consume(available);
this._remaining -= available;
const ended = this._remaining === 0;
if (ended) this._state = FIRST_TOKEN;
yield { type: constants.DATA, data };
if (ended) yield { type: constants.END };
continue;
}
if (this._state === CHUNK_DATA) {
if (this._buffered < this._remaining) return;
const consumed = this._consume(this._remaining);
if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
throw errors.INVALID_MESSAGE("Expected CRLF after chunk data");
}
const data = consumed.subarray(0, this._remaining - 2);
this._remaining = 0;
this._state = CHUNK_SIZE;
yield { type: constants.DATA, data };
continue;
}
if (this._buffered === 0) return;
const byte = this._buffer[this._bufferIndex][this._byteIndex++];
this._buffered--;
if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
this._bufferIndex++;
this._byteIndex = 0;
}
switch (this._state) {
case FIRST_TOKEN: {
this._checkHeaderSize();
if (byte === SP) {
const token = this._buildString();
if (token.length === 0) throw errors.INVALID_MESSAGE();
this._isResponse = token.startsWith("HTTP/");
if (this._isResponse) {
if (token !== "HTTP/1.0" && token !== "HTTP/1.1") {
throw errors.INVALID_MESSAGE();
}
this._version = token;
this._state = STATUS_CODE;
} else {
this._method = token;
this._state = REQUEST_URL;
}
} else if (byte === CR) {
throw errors.INVALID_MESSAGE();
} else if (isTokenByte(byte)) {
this._accumulator.push(byte);
} else if (byte === 47 && this._accumulator.length === 4 && this._accumulator[0] === 72 && this._accumulator[1] === 84 && this._accumulator[2] === 84 && this._accumulator[3] === 80) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case REQUEST_URL: {
this._checkHeaderSize();
if (byte === SP) {
this._url = this._buildString();
if (this._url.length === 0) throw errors.INVALID_MESSAGE();
this._state = REQUEST_VERSION;
} else if (byte === CR) {
throw errors.INVALID_MESSAGE();
} else if (byte >= 33 && byte !== 127) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case REQUEST_VERSION: {
this._checkHeaderSize();
if (byte === CR) {
this._version = this._buildString();
if (this._version !== "HTTP/1.0" && this._version !== "HTTP/1.1") {
throw errors.INVALID_MESSAGE();
}
this._state = FIRST_LINE_LF;
} else if (byte >= 33 && byte !== 127) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case STATUS_CODE: {
this._checkHeaderSize();
if (byte === SP) {
if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE();
let code = 0;
for (let i = 0, n = this._accumulator.length; i < n; i++) {
code = code * 10 + this._accumulator[i];
}
this._accumulator = [];
if (code < 100 || code > 999) throw errors.INVALID_MESSAGE();
this._code = code;
this._state = STATUS_REASON;
} else if (byte >= ZERO && byte <= NINE) {
this._accumulator.push(byte - ZERO);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case STATUS_REASON: {
this._checkHeaderSize();
if (byte === CR) {
this._reason = this._buildString();
this._state = FIRST_LINE_LF;
} else if (isFieldByte(byte)) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case FIRST_LINE_LF: {
if (byte !== LF) throw errors.INVALID_MESSAGE();
this._headers = {};
this._headerCount = 0;
this._state = HEADER_START;
break;
}
case HEADER_START: {
this._checkHeaderSize();
if (byte === CR) {
this._state = HEADER_END_LF;
} else if (byte !== COLON && isTokenByte(byte)) {
this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 32 : byte);
this._state = HEADER_NAME;
} else {
throw errors.INVALID_HEADER();
}
break;
}
case HEADER_NAME: {
this._checkHeaderSize();
if (byte === COLON) {
this._headerName = this._buildString();
this._state = HEADER_VALUE_WS;
} else if (byte !== COLON && isTokenByte(byte)) {
this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 32 : byte);
} else {
throw errors.INVALID_HEADER();
}
break;
}
case HEADER_VALUE_WS: {
this._checkHeaderSize();
if (byte === SP || byte === TAB) break;
if (byte === CR) {
this._storeHeader(this._headerName, "");
this._headerName = "";
this._state = HEADER_LINE_LF;
break;
}
if (!isFieldByte(byte)) throw errors.INVALID_HEADER();
this._accumulator.push(byte);
this._state = HEADER_VALUE;
break;
}
case HEADER_VALUE: {
this._checkHeaderSize();
if (byte === CR) {
this._storeHeader(this._headerName, this._buildString());
this._headerName = "";
this._state = HEADER_LINE_LF;
} else if (isFieldByte(byte)) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_HEADER();
}
break;
}
case HEADER_LINE_LF: {
if (byte !== LF) throw errors.INVALID_HEADER();
this._state = HEADER_START;
break;
}
case HEADER_END_LF: {
if (byte !== LF) throw errors.INVALID_MESSAGE();
const headers = this._headers;
if (this._isResponse) {
yield {
type: constants.RESPONSE,
version: this._version,
code: this._code,
reason: this._reason,
headers
};
} else {
if (this._version === "HTTP/1.1" && !("host" in headers)) {
throw errors.INVALID_HEADER("Header 'Host' is missing");
}
yield {
type: constants.REQUEST,
version: this._version,
method: this._method,
url: this._url,
headers
};
}
const transferEncoding = headers["transfer-encoding"];
const contentLength = headers["content-length"];
const encodings = transferEncoding ? transferEncoding.split(",") : null;
const lastEncoding = encodings ? encodings[encodings.length - 1].trim().toLowerCase() : null;
if (lastEncoding === "chunked") {
if (contentLength) {
throw errors.INVALID_MESSAGE(
"Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
);
}
this._state = CHUNK_SIZE;
this._headerSize = 0;
continue;
}
if (contentLength) {
if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH();
let length = 0;
for (let i = 0, n = contentLength.length; i < n; i++) {
const c = contentLength.charCodeAt(i);
if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH();
length = length * 10 + (c - ZERO);
}
if (!Number.isSafeInteger(length) || length < 0) {
throw errors.INVALID_CONTENT_LENGTH();
}
if (length === 0) {
this._state = FIRST_TOKEN;
this._headerSize = 0;
yield { type: constants.END };
} else {
this._state = BODY;
this._remaining = length;
this._headerSize = 0;
}
} else {
this._state = FIRST_TOKEN;
this._headerSize = 0;
yield { type: constants.END };
}
break;
}
case CHUNK_SIZE: {
if (byte === CR || byte === 59) {
if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH();
let length = 0;
for (let i = 0, n = this._accumulator.length; i < n; i++) {
length = length * 16 + this._accumulator[i];
}
this._accumulator = [];
if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH();
if (byte === 59) {
this._remaining = length;
this._state = CHUNK_EXTENSION;
} else if (length === 0) {
this._state = LAST_CHUNK_LF;
} else {
this._remaining = length + 2;
this._state = CHUNK_SIZE_LF;
}
} else if (isHex(byte)) {
if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
throw errors.INVALID_CHUNK_LENGTH();
}
this._accumulator.push(hexValue(byte));
} else {
throw errors.INVALID_CHUNK_LENGTH();
}
break;
}
case CHUNK_EXTENSION: {
this._checkHeaderSize();
if (byte === CR) {
if (this._remaining === 0) {
this._state = LAST_CHUNK_LF;
} else {
this._remaining += 2;
this._state = CHUNK_SIZE_LF;
}
} else if (!isFieldByte(byte)) {
throw errors.INVALID_CHUNK_LENGTH();
}
break;
}
case CHUNK_SIZE_LF: {
if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH();
this._state = CHUNK_DATA;
break;
}
case LAST_CHUNK_LF: {
if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH();
this._state = TRAILER_CR;
break;
}
case TRAILER_CR: {
if (byte !== CR) throw errors.INVALID_MESSAGE();
this._state = TRAILER_LF;
break;
}
case TRAILER_LF: {
if (byte !== LF) throw errors.INVALID_MESSAGE();
this._state = FIRST_TOKEN;
this._headerSize = 0;
yield { type: constants.END };
break;
}
default:
throw errors.INVALID_MESSAGE();
}
}
}
};
exports.constants = constants;
var TOKEN_BYTES = Buffer.from([
// 0x00-0x1f (control characters) + 0x20 (space)
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
// 0x42-0x62: B-Z [ \ ] ^ _ ` a b
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
// 0x63-0x7f: c-z { | } ~ DEL
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0
]);
function isTokenByte(b) {
return TOKEN_BYTES[b] === 1;
}
function isFieldByte(b) {
return b === TAB || b >= 32 && b <= 126;
}
function isHex(b) {
return b >= ZERO && b <= NINE || b >= UPPER_A && b <= UPPER_F || b >= LOWER_A && b <= LOWER_F;
}
function hexValue(b) {
if (b >= ZERO && b <= NINE) return b - ZERO;
if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10;
return b - LOWER_A + 10;
}
}
});
// ../../node_modules/bare-http1/lib/client-connection.js
var require_client_connection = __commonJS({
"../../node_modules/bare-http1/lib/client-connection.js"(exports, module) {
var HTTPParser = require_bare_http_parser();
var HTTPIncomingMessage = require_incoming_message();
var errors = require_errors3();
var {
constants: { RESPONSE, DATA, END }
} = HTTPParser;
var EMPTY = Buffer.alloc(0);
module.exports = class HTTPClientConnection {
static _connections = /* @__PURE__ */ new WeakMap();
static for(socket) {
return this._connections.get(socket) || null;
}
static from(socket, opts) {
return this.for(socket) || new this(socket, opts);
}
constructor(socket, opts = {}) {
const { IncomingMessage = HTTPIncomingMessage } = opts;
this._socket = socket;
this._req = null;
this._res = null;
this._IncomingMessage = IncomingMessage;
this._parser = new HTTPParser();
this._idle = true;
this._onerror = this._onerror.bind(this);
this._onclose = this._onclose.bind(this);
this._onend = this._onend.bind(this);
this._ondata = this._ondata.bind(this);
this._ondrain = this._ondrain.bind(this);
this._ontimeout = this._ontimeout.bind(this);
socket.on("error", this._onerror).on("close", this._onclose).on("end", this._onend).on("data", this._ondata).on("drain", this._ondrain).on("timeout", this._ontimeout);
HTTPClientConnection._connections.set(socket, this);
}
get socket() {
return this._socket;
}
get req() {
return this._req;
}
get res() {
return this._res;
}
get idle() {
return this._idle;
}
_onerror(err) {
if (this._req) this._req.destroy(err);
}
_onclose() {
if (this._req) this._req.destroy();
}
_onend() {
if (this._req) this._req.destroy(errors.CONNECTION_LOST());
}
_ondata(data) {
this._idle = false;
try {
for (const op of this._parser.push(data)) {
switch (op.type) {
case RESPONSE:
this._req.on("close", () => {
this._req = null;
});
this._res = new this._IncomingMessage(this._socket, {
headers: op.headers,
statusCode: op.code,
statusMessage: op.reason
});
this._res.on("close", () => {
this._res = null;
this._idle = true;
this._socket.emit("free");
});
if (op.headers.connection && op.headers.connection.toLowerCase() === "upgrade") {
return this._onupgrade(this._parser.end());
}
this._req.emit("response", this._res);
break;
case DATA:
this._res.push(op.data);
break;
case END:
if (this._res) {
this._res._socket = null;
this._res.push(null);
}
if (this._req) {
this._req._socket = null;
this._req.destroy();
}
break;
}
}
} catch (err) {
this._socket.destroy(err);
}
}
_onupgrade(data) {
this._detach();
const res = this._res;
const req = this._req;
res._upgrade = req._upgrade = true;
const upgraded = req.emit("upgrade", res, this._socket, data || EMPTY);
res.push(null);
req.destroy();
if (!upgraded) this._socket.destroy();
}
_ontimeout() {
if (this._req) this._req.emit("timeout");
}
_ondrain() {
if (this._req) this._req._continueWrite();
}
_detach() {
this._socket.off("error", this._onerror).off("close", this._onclose).off("end", this._onend).off("data", this._ondata).off("drain", this._ondrain).off("timeout", this._ontimeout);
HTTPClientConnection._connections.delete(this._socket);
}
};
}
});
// ../../node_modules/bare-http1/lib/agent.js
var require_agent = __commonJS({
"../../node_modules/bare-http1/lib/agent.js"(exports, module) {
var EventEmitter = require_bare_events();
var tcp = require_bare_tcp();
var HTTPClientConnection = require_client_connection();
var errors = require_errors3();
var HTTPSocketSet = class {
constructor() {
this._sockets = /* @__PURE__ */ new Map();
this._size = 0;
}
get size() {
return this._size;
}
add(name, socket) {
const sockets = this._sockets.get(name);
this._size++;
if (sockets === void 0) this._sockets.set(name, [socket]);
else sockets.push(socket);
}
pop(name) {
const sockets = this._sockets.get(name);
if (sockets === void 0 || sockets.length === 0) return null;
this._size--;
const last = sockets.pop();
if (sockets.length === 0) this._sockets.delete(name);
return last;
}
delete(name, socket) {
const sockets = this._sockets.get(name);
if (sockets === void 0) return;
const i = sockets.indexOf(socket);
if (i === -1) return;
this._size--;
const last = sockets.pop();
if (last !== socket) sockets[i] = last;
if (sockets.length === 0) this._sockets.delete(name);
}
*sockets() {
for (const sockets of this._sockets.values()) {
yield* sockets;
}
}
*[Symbol.iterator]() {
for (const [name, sockets] of this._sockets) {
for (const socket of sockets) yield [name, socket];
}
}
};
var HTTPAgent = class _HTTPAgent extends EventEmitter {
constructor(opts = {}) {
super();
const { keepAlive = false, keepAliveMsecs = 1e3, defaultPort = 80 } = opts;
this._suspended = false;
this._resuming = null;
this._sockets = new HTTPSocketSet();
this._freeSockets = new HTTPSocketSet();
this._keepAlive = typeof keepAlive === "number" ? keepAlive : keepAlive ? keepAliveMsecs : -1;
this._defaultPort = defaultPort;
this._opts = { ...opts };
}
get suspended() {
return this._suspended;
}
get resumed() {
return this._resuming ? this._resuming.promise : null;
}
get sockets() {
return this._sockets.sockets();
}
get freeSockets() {
return this._freeSockets.sockets();
}
get defaultPort() {
return this._defaultPort;
}
createConnection(opts) {
if (this._suspended) throw errors.AGENT_SUSPENDED();
return tcp.createConnection(opts);
}
reuseSocket(socket, req) {
socket.ref();
}
keepSocketAlive(socket) {
if (this._keepAlive === -1) return false;
socket.setKeepAlive(true, this._keepAlive);
socket.unref();
return true;
}
getName(opts) {
return `${opts.host}:${opts.port}`;
}
addRequest(req, opts) {
opts = { ...opts, ...this._opts };
const name = this.getName(opts);
let socket = this._freeSockets.pop(name);
if (socket) this.reuseSocket(socket, req);
else {
let onfree2 = function() {
if (socket.destroyed) return;
if (agent.keepSocketAlive(socket)) {
agent._freeSockets.add(name, socket);
} else {
socket.end();
}
agent.emit("free", socket);
}, onremove2 = function() {
socket.off("free", onfree2);
agent._sockets.delete(name, socket);
agent._freeSockets.delete(name, socket);
if (agent._sockets.size === 0) _HTTPAgent._agents.delete(agent);
}, ontimeout2 = function() {
socket.destroy();
agent._freeSockets.delete(name, socket);
};
var onfree = onfree2, onremove = onremove2, ontimeout = ontimeout2;
const agent = this;
socket = this.createConnection(opts);
socket.on("free", onfree2).on("end", onremove2).on("finish", onremove2).on("close", onremove2).on("timeout", ontimeout2);
}
if (this._sockets.size === 0) _HTTPAgent._agents.add(this);
this._sockets.add(name, socket);
req._socket = socket;
const connection = HTTPClientConnection.from(socket, opts);
connection._req = req;
}
suspend() {
if (this._suspended) return;
this._resuming = Promise.withResolvers();
this._suspended = true;
this.destroy();
}
resume() {
if (this._resuming === null) return;
this._resuming.resolve();
this._resuming = null;
this._suspended = false;
}
destroy() {
for (const socket of this._sockets.sockets()) socket.destroy();
}
static _agents = /* @__PURE__ */ new Set();
static _onidle() {
for (const agent of this._agents) {
agent.destroy();
}
}
};
HTTPAgent.global = new HTTPAgent({ keepAlive: 1e3, timeout: 5e3 });
module.exports = HTTPAgent;
Bare.on("idle", HTTPAgent._onidle.bind(HTTPAgent));
}
});
// ../../node_modules/bare-http1/lib/constants.js
var require_constants3 = __commonJS({
"../../node_modules/bare-http1/lib/constants.js"(exports, module) {
module.exports = {
method: {
GET: "GET",
HEAD: "HEAD",
POST: "POST",
PUT: "PUT",
DELETE: "DELETE",
CONNECT: "CONNECT",
OPTIONS: "OPTIONS",
TRACE: "TRACE",
PATCH: "PATCH"
},
status: {
100: "Continue",
101: "Switching Protocols",
102: "Processing",
103: "Early Hints",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi-Status",
208: "Already Reported",
226: "IM Used",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
308: "Permanent Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Payload Too Large",
414: "URI Too Long",
415: "Unsupported Media Type",
416: "Range Not Satisfiable",
417: "Expectation Failed",
418: "I'm a Teapot",
421: "Misdirected Request",
422: "Unprocessable Entity",
423: "Locked",
424: "Failed Dependency",
425: "Too Early",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
451: "Unavailable For Legal Reasons",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
509: "Bandwidth Limit Exceeded",
510: "Not Extended",
511: "Network Authentication Required"
}
};
}
});
// ../../node_modules/bare-http1/lib/server-response.js
var require_server_response = __commonJS({
"../../node_modules/bare-http1/lib/server-response.js"(exports, module) {
var { isFinishing } = require_bare_stream();
var HTTPOutgoingMessage = require_outgoing_message();
var constants = require_constants3();
var CHUNK_DELIMITER = Buffer.from("\r\n");
var CHUNK_TERMINATOR = Buffer.from("0\r\n\r\n");
module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
constructor(socket, req) {
super(socket);
this._req = req;
this._statusCode = 200;
this._statusMessage = null;
this._chunked = true;
this._close = req.headers.connection === "close";
this._onlyHeaders = req.method === "HEAD";
this._pendingWrite = null;
}
get req() {
return this._req;
}
get statusCode() {
return this._statusCode;
}
set statusCode(value) {
this._statusCode = value;
}
get statusMessage() {
return this._statusMessage;
}
set statusMessage(value) {
this._statusMessage = value;
}
writeHead(statusCode, statusMessage = null, headers = {}) {
if (typeof statusMessage === "object" && statusMessage !== null) {
headers = statusMessage;
statusMessage = null;
}
this._statusCode = statusCode;
this._statusMessage = statusMessage || null;
if (headers) this._headers = { ...this._headers, ...headers };
}
_header() {
let h = "HTTP/1.1 " + this._statusCode + " " + (this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage) + "\r\n";
for (const name of Object.keys(this._headers)) {
const n = name.toLowerCase();
const v = this._headers[name];
if (n === "content-length") this._chunked = false;
if (n === "connection" && v && v.toLowerCase() === "close") this._close = true;
h += httpCase(n) + ": " + v + "\r\n";
}
if (this._chunked) h += "Transfer-Encoding: chunked\r\n";
h += "\r\n";
return h;
}
_write(data, encoding, cb) {
if (this._headersSent === false) {
if (isFinishing(this)) {
this.setHeader(
"Content-Length",
(data.byteLength + this._writableState.buffered).toString()
);
}
this.flushHeaders();
}
if (this._onlyHeaders === true) return cb(null);
if (this._chunked) {
this._socket.write(Buffer.from(data.byteLength.toString(16)));
this._socket.write(CHUNK_DELIMITER);
}
let flushed = this._socket.write(data);
if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER);
if (flushed) cb(null);
else this._pendingWrite = cb;
}
_final(cb) {
if (this._headersSent === false) {
this.setHeader("Content-Length", "0");
this.flushHeaders();
}
if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR);
if (this._close) this._socket.end();
cb(null);
}
_predestroy() {
super._predestroy();
this._req.destroy();
this._continueWrite();
}
_continueWrite() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
};
function httpCase(n) {
let s = "";
for (const part of n.split("-")) {
s += (s ? "-" : "") + part.slice(0, 1).toUpperCase() + part.slice(1);
}
return s;
}
}
});
// ../../node_modules/bare-http1/lib/server-connection.js
var require_server_connection = __commonJS({
"../../node_modules/bare-http1/lib/server-connection.js"(exports, module) {
var { isEnded, isFinished, getStreamError } = require_bare_stream();
var HTTPParser = require_bare_http_parser();
var HTTPIncomingMessage = require_incoming_message();
var HTTPServerResponse = require_server_response();
var {
constants: { REQUEST, DATA, END }
} = HTTPParser;
var EMPTY = Buffer.alloc(0);
module.exports = class HTTPServerConnection {
static _connections = /* @__PURE__ */ new WeakMap();
static for(socket) {
return this._connections.get(socket) || null;
}
constructor(server, socket, opts = {}) {
const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts;
this._server = server;
this._socket = socket;
this._req = null;
this._res = null;
this._IncomingMessage = IncomingMessage;
this._ServerResponse = ServerResponse;
this._parser = new HTTPParser();
this._idle = true;
this._onclose = this._onclose.bind(this);
this._ondata = this._ondata.bind(this);
this._ondrain = this._ondrain.bind(this);
this._ontimeout = this._ontimeout.bind(this);
socket.on("error", noop).on("close", this._onclose).on("data", this._ondata).on("drain", this._ondrain).on("timeout", this._ontimeout);
HTTPServerConnection._connections.set(socket, this);
if (this._server.timeout) socket.setTimeout(this._server.timeout);
}
get server() {
return this._server;
}
get socket() {
return this._socket;
}
get req() {
return this._req;
}
get res() {
return this._res;
}
get idle() {
return this._idle;
}
_onclose() {
if (this._req && !isEnded(this._req)) this._req.destroy();
if (this._res && !isFinished(this._res)) this._res.destroy();
const err = getStreamError(this._socket);
if (err) this._socket.destroy(err);
}
_ondata(data) {
this._idle = false;
try {
for (const op of this._parser.push(data)) {
switch (op.type) {
case REQUEST:
this._req = new this._IncomingMessage(this._socket, {
headers: op.headers,
method: op.method,
url: op.url
});
this._req.on("close", () => {
this._req = null;
this._idle = true;
if (this._server.closing) this._socket.destroy();
});
this._req.resume();
this._req.pause();
if (op.headers.connection && op.headers.connection.toLowerCase() === "upgrade") {
return this._onupgrade(this._parser.end());
}
this._res = new this._ServerResponse(this._socket, this._req);
this._res.on("close", () => {
this._res = null;
});
this._server.emit("request", this._req, this._res);
break;
case DATA:
this._req.push(op.data);
break;
case END:
if (this._req) {
this._req._socket = null;
this._req.push(null);
}
break;
}
}
} catch (err) {
this._socket.destroy(err);
}
}
_onupgrade(data) {
this._detach();
const req = this._req;
req._upgrade = true;
const upgraded = this._server.emit("upgrade", req, this._socket, data || EMPTY);
req.push(null);
if (!upgraded) this._socket.destroy();
}
_ontimeout() {
const reqTimeout = this._req && this._req.emit("timeout");
const resTimeout = this._res && this._res.emit("timeout");
const serverTimeout = this._server.emit("timeout", this._socket);
if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy();
}
_ondrain() {
if (this._res) this._res._continueWrite();
}
_detach() {
this._socket.off("error", noop).off("close", this._onclose).off("data", this._ondata).off("drain", this._ondrain).off("timeout", this._ontimeout);
HTTPServerConnection._connections.delete(this._socket);
}
};
function noop() {
}
}
});
// ../../node_modules/bare-http1/lib/server.js
var require_server = __commonJS({
"../../node_modules/bare-http1/lib/server.js"(exports, module) {
var TCPServer = require_bare_tcp().Server;
var HTTPServerConnection = require_server_connection();
module.exports = class HTTPServer extends TCPServer {
constructor(opts = {}, onrequest) {
if (typeof opts === "function") {
onrequest = opts;
opts = {};
}
super({ allowHalfOpen: false });
this._timeout = 0;
this.on("connection", (socket) => {
new HTTPServerConnection(this, socket, opts);
});
if (onrequest) this.on("request", onrequest);
}
get timeout() {
return this._timeout || void 0;
}
setTimeout(ms = 0, ontimeout) {
if (ontimeout) this.on("timeout", ontimeout);
this._timeout = ms;
return this;
}
close(onclose) {
super.close(onclose);
for (const socket of this.connections) {
const connection = HTTPServerConnection.for(socket);
if (connection === null || connection.idle) {
socket.destroy();
}
}
return this;
}
};
}
});
// ../../node_modules/bare-http1/lib/client-request.js
var require_client_request = __commonJS({
"../../node_modules/bare-http1/lib/client-request.js"(exports, module) {
var HTTPAgent = require_agent();
var HTTPOutgoingMessage = require_outgoing_message();
var CHUNK_DELIMITER = Buffer.from("\r\n");
var CHUNK_TERMINATOR = Buffer.from("0\r\n\r\n");
module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
constructor(opts = {}, onresponse = null) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
opts = opts ? { ...opts } : {};
const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global;
const method = opts.method || "GET";
const path = opts.path || "/";
const defaultPort = opts.defaultPort || agent && agent.defaultPort || 80;
const host = opts.host = opts.host || "localhost";
const port = opts.port = opts.port || defaultPort;
const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers };
super();
agent.addRequest(this, opts);
this._headers = headers;
this._method = method;
this._path = path;
this._chunked = method !== "GET" && method !== "HEAD";
this._pendingWrite = null;
this._pendingFinal = null;
if (onresponse) this.once("response", onresponse);
}
get method() {
return this._method;
}
get path() {
return this._path;
}
// For Node.js compatibility
abort() {
return this.destroy();
}
_header() {
let h = `${this._method} ${this._path} HTTP/1.1\r
`;
let upgrade = false;
for (const name of Object.keys(this._headers)) {
const n = name.toLowerCase();
const v = this._headers[name];
if (n === "content-length") this._chunked = false;
if (n === "connection" && v && v.toLowerCase() === "upgrade") upgrade = true;
h += `${httpCase(n)}: ${v}\r
`;
}
if (upgrade) this._chunked = false;
if (this._chunked) h += "Transfer-Encoding: chunked\r\n";
h += "\r\n";
return h;
}
_write(data, encoding, cb) {
if (this._headersSent === false) this.flushHeaders();
if (this._chunked) {
this._socket.write(Buffer.from(data.byteLength.toString(16)));
this._socket.write(CHUNK_DELIMITER);
}
let flushed = this._socket.write(data);
if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER);
if (flushed) cb(null);
else this._pendingWrite = cb;
}
_final(cb) {
if (this._headersSent === false) this.flushHeaders();
if (this._chunked) this._socket.write(CHUNK_TERMINATOR);
this._pendingFinal = cb;
}
_predestroy() {
super._predestroy();
this._continueWrite();
this._continueFinal();
}
_continueWrite() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_continueFinal() {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(null);
}
};
function httpCase(n) {
let s = "";
for (const part of n.split("-")) {
s += (s ? "-" : "") + part.slice(0, 1).toUpperCase() + part.slice(1);
}
return s;
}
function hostHeader(host, port, defaultPort) {
const i = host.indexOf(":");
if (i !== -1 && host.includes(":", i + 1) && host.charCodeAt(0) !== 91) {
host = `[${host}]`;
}
if (port && +port !== defaultPort) {
host += ":" + port;
}
return host;
}
}
});
// ../../node_modules/bare-http1/index.js
var require_bare_http1 = __commonJS({
"../../node_modules/bare-http1/index.js"(exports) {
exports.IncomingMessage = require_incoming_message();
exports.OutgoingMessage = require_outgoing_message();
exports.Agent = require_agent();
exports.globalAgent = exports.Agent.global;
exports.Server = require_server();
exports.ServerResponse = require_server_response();
exports.ServerConnection = require_server_connection();
exports.ClientRequest = require_client_request();
exports.ClientConnection = require_client_connection();
exports.constants = require_constants3();
exports.errors = require_errors3();
exports.METHODS = Object.values(exports.constants.method);
exports.STATUS_CODES = exports.constants.status;
exports.createServer = function createServer(opts, onrequest) {
return new exports.Server(opts, onrequest);
};
exports.request = function request(url, opts, onresponse) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
if (typeof url === "string") url = new URL(url);
if (isURL(url)) {
opts = opts ? { ...url, ...opts } : { ...url };
opts.host = url.hostname;
opts.path = url.pathname + url.search;
opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url);
} else {
opts = url ? { ...url } : {};
opts.host = opts.hostname || opts.host;
opts.port = typeof opts.port === "string" ? parseInt(opts.port, 10) : opts.port;
}
return new exports.ClientRequest(opts, onresponse);
};
exports.get = function get(url, opts, onresponse) {
const req = exports.request(url, opts, onresponse);
req.end();
return req;
};
function defaultPort(url) {
switch (url.protocol) {
case "ftp:":
return 21;
case "http:":
case "ws:":
return 80;
case "https:":
case "wss:":
return 443;
}
return null;
}
function isURL(url) {
return url !== null && typeof url === "object" && typeof url.protocol === "string" && typeof url.hostname === "string" && typeof url.pathname === "string" && typeof url.search === "string";
}
}
});
// ../../node_modules/bare-tls/binding.js
var require_binding6 = __commonJS({
"../../node_modules/bare-tls/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tls/lib/constants.js
var require_constants4 = __commonJS({
"../../node_modules/bare-tls/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTED: 1,
ATTACHED: 2
}
};
}
});
// ../../node_modules/bare-tls/lib/errors.js
var require_errors7 = __commonJS({
"../../node_modules/bare-tls/lib/errors.js"(exports, module) {
module.exports = class TLSError extends Error {
constructor(msg, code, fn = TLSError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "TLSError";
}
static from(err) {
return new TLSError(err.message, err.code, TLSError.from);
}
};
}
});
// ../../node_modules/bare-pipe/binding.js
var require_binding7 = __commonJS({
"../../node_modules/bare-pipe/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-pipe/lib/constants.js
var require_constants5 = __commonJS({
"../../node_modules/bare-pipe/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTING: 1,
CONNECTED: 2,
BINDING: 4,
BOUND: 8,
READING: 16,
CLOSING: 32,
READABLE: 64,
WRITABLE: 128,
UNREFED: 256
}
};
}
});
// ../../node_modules/bare-pipe/lib/errors.js
var require_errors8 = __commonJS({
"../../node_modules/bare-pipe/lib/errors.js"(exports, module) {
module.exports = class PipeError extends Error {
constructor(msg, fn = PipeError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "PipeError";
}
static PIPE_ALREADY_CONNECTED(msg) {
return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED);
}
static SERVER_ALREADY_LISTENING(msg) {
return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING);
}
static SERVER_IS_CLOSED(msg) {
return new PipeError(msg, PipeError.SERVER_IS_CLOSED);
}
};
}
});
// ../../node_modules/bare-pipe/index.js
var require_bare_pipe = __commonJS({
"../../node_modules/bare-pipe/index.js"(exports, module) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var binding = require_binding7();
var constants = require_constants5();
var errors = require_errors8();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
module.exports = exports = class Pipe extends Duplex {
constructor(path, opts = {}) {
if (typeof path === "object" && path !== null) {
opts = path;
path = null;
}
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts;
super({ eagerOpen });
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._fd = -1;
this._path = null;
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
this._buffer = Buffer.alloc(readBufferSize);
this._handle = binding.init(
this._buffer,
this,
noop,
this._onconnect,
this._onwrite,
this._onfinal,
this._onread,
this._onclose
);
if (typeof path === "number") {
this.open(path);
} else if (typeof path === "string") {
this.connect(path);
}
}
get connecting() {
return (this._state & constants.state.CONNECTING) !== 0;
}
get pending() {
return (this._state & constants.state.CONNECTED) === 0;
}
get readyState() {
if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
return "open";
}
if (this._state & constants.state.READABLE) {
return "readOnly";
}
if (this._state & constants.state.WRITABLE) {
return "writeOnly";
}
return "opening";
}
open(fd, opts = {}, onconnect) {
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof fd === "object" && fd !== null) {
opts = fd || {};
fd = opts.fd;
}
try {
const status = binding.open(this._handle, fd);
this._state |= constants.state.CONNECTED;
this._fd = fd;
if (status & binding.READABLE) {
this._state |= constants.state.READABLE;
} else {
this.push(null);
}
if (status & binding.WRITABLE) {
this._state |= constants.state.WRITABLE;
} else {
this.end();
}
if (onconnect) this.once("connect", onconnect);
queueMicrotask(() => this.emit("connect"));
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
connect(path, opts = {}, onconnect) {
if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
throw errors.PIPE_ALREADY_CONNECTED("Pipe is already connected");
}
this._state |= constants.state.CONNECTING;
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
}
try {
binding.connect(this._handle, path);
this._path = path;
if (onconnect) this.once("connect", onconnect);
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
ref() {
binding.ref(this._handle);
return this;
}
unref() {
binding.unref(this._handle);
return this;
}
_open(cb) {
if (this._state & constants.state.CONNECTED) return cb(null);
this._pendingOpen = cb;
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(this._handle);
}
}
_writev(batch, cb) {
this._pendingWrite = [cb, batch];
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
}
_final(cb) {
if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
this._pendingFinal = cb;
binding.end(this._handle);
} else {
cb(null);
}
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
}
_continueOpen(err) {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite[0];
this._pendingWrite = null;
cb(err);
}
_continueFinal(err) {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_onconnect(err) {
if (err) {
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE;
this._state &= ~constants.state.CONNECTING;
this._continueOpen();
this.emit("connect");
}
_onread(err, read) {
if (err) {
this.destroy(err);
return;
}
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
if (this.push(copy) === false && this.destroying === false) {
this._state &= ~constants.state.READING;
binding.pause(this._handle);
}
}
_onwrite(err) {
this._continueWrite(err);
}
_onfinal(err) {
this._continueFinal(err === null || err.code === "ENOTCONN" ? null : err);
}
_onclose() {
this._continueDestroy();
}
_onspawn(readable, writable) {
this._state |= constants.state.CONNECTED;
if (readable) {
this._state |= constants.state.READABLE;
} else {
this.push(null);
}
if (writable) {
this._state |= constants.state.WRITABLE;
} else {
this.end();
}
this._continueOpen();
}
};
exports.Pipe = exports;
exports.pipe = function pipe() {
return binding.pipe();
};
exports.Server = class PipeServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = true,
pauseOnConnect = false
} = opts;
this._state = 0;
this._readBufferSize = readBufferSize;
this._allowHalfOpen = allowHalfOpen;
this._pauseOnConnect = pauseOnConnect;
this._path = null;
this._connections = /* @__PURE__ */ new Set();
this._error = null;
this._handle = null;
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return (this._state & constants.state.BOUND) !== 0;
}
address() {
if ((this._state & constants.state.BOUND) === 0) {
return null;
}
return this._path;
}
listen(path, backlog = 511, opts = {}, onlistening) {
if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
throw errors.SERVER_ALREADY_LISTENING("Server is already listening");
}
if (this._state & constants.state.CLOSING) {
throw errors.SERVER_IS_CLOSED("Server is closed");
}
this._state |= constants.state.BINDING;
if (typeof backlog === "function") {
onlistening = backlog;
backlog = 511;
} else if (typeof opts === "function") {
onlistening = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
backlog = opts.backlog || 511;
}
this._handle = binding.init(
empty,
this,
this._onconnection,
noop,
noop,
noop,
noop,
this._onclose
);
if (this._state & constants.state.UNREFED) binding.unref(this._handle);
try {
binding.bind(this._handle, path, backlog);
this._path = path;
this._state |= constants.state.BOUND;
this._state &= ~constants.state.BINDING;
if (onlistening) this.once("listening", onlistening);
queueMicrotask(() => this.emit("listening"));
} catch (err) {
this._error = err;
binding.close(this._handle);
}
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
this._closeMaybe();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._handle !== null) binding.ref(this._handle);
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._handle !== null) binding.unref(this._handle);
return this;
}
_closeMaybe() {
if (this._state & constants.state.CLOSING && this._connections.size === 0) {
if (this._handle !== null) binding.close(this._handle);
else queueMicrotask(() => this.emit("close"));
}
}
_onconnection(err) {
if (err) {
this.emit("error", err);
return;
}
if (this._state & constants.state.CLOSING) return;
const pipe = new exports.Pipe({
readBufferSize: this._readBufferSize,
allowHalfOpen: this._allowHalfOpen,
eagerOpen: !this._pauseOnConnect
});
try {
binding.accept(this._handle, pipe._handle);
pipe._path = this._path;
pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE;
this._connections.add(pipe);
pipe.on("close", () => {
this._connections.delete(pipe);
this._closeMaybe();
});
this.emit("connection", pipe);
} catch (err2) {
pipe.destroy();
throw err2;
}
}
_onclose() {
const err = this._error;
this._state &= ~constants.state.BINDING;
this._error = null;
this._handle = null;
if (err) this.emit("error", err);
else this.emit("close");
}
};
exports.constants = constants;
exports.errors = errors;
exports.createConnection = function createConnection(path, opts, onconnect) {
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
}
return new exports.Pipe(opts).connect(path, opts, onconnect);
};
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
function noop() {
}
}
});
// ../../node_modules/bare-net/lib/constants.js
var require_constants6 = __commonJS({
"../../node_modules/bare-net/lib/constants.js"(exports, module) {
module.exports = {
type: {
TCP: 1,
IPC: 2
},
state: {
UNREFED: 1
}
};
}
});
// ../../node_modules/bare-net/index.js
var require_bare_net = __commonJS({
"../../node_modules/bare-net/index.js"(exports) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var tcp = require_bare_tcp();
var pipe = require_bare_pipe();
var constants = require_constants6();
var defaultReadBufferSize = 65536;
exports.Socket = class NetSocket extends Duplex {
constructor(opts = {}) {
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = false,
eagerOpen = false
} = opts;
super({ eagerOpen, allowHalfOpen });
this._type = 0;
this._state = 0;
this._socket = null;
this._opts = { readBufferSize, allowHalfOpen, eagerOpen };
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
}
get connecting() {
return this._socket !== null && this._socket.connecting;
}
get pending() {
return this._socket === null || this._socket.pending;
}
get timeout() {
return this._socket === null ? void 0 : this._socket.timeout;
}
get readyState() {
return this._socket === null ? "opening" : this._socket.readyState;
}
get localAddress() {
return this._socket === null ? void 0 : this._socket.localAddress;
}
get localPort() {
return this._socket === null ? void 0 : this._socket.localPort;
}
get localFamily() {
return this._socket === null ? void 0 : this._socket.localFamily;
}
get remoteAddress() {
return this._socket === null ? void 0 : this._socket.remoteAddress;
}
get remotePort() {
return this._socket === null ? void 0 : this._socket.remotePort;
}
get remoteFamily() {
return this._socket === null ? void 0 : this._socket.remoteFamily;
}
connect(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
opts = { ...opts, ...this._opts };
if (opts.path) {
this._attach(constants.type.IPC, pipe.createConnection(opts));
} else {
this._attach(constants.type.TCP, tcp.createConnection(opts));
}
if (onconnect) this.once("connect", onconnect);
return this;
}
setKeepAlive(...args) {
if (this._socket !== null) this._socket.setKeepAlive(...args);
return this;
}
setNoDelay(...args) {
if (this._socket !== null) this._socket.setNoDelay(...args);
return this;
}
setTimeout(...args) {
if (this._socket !== null) this._socket.setTimeout(...args);
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._socket !== null) this._socket.ref();
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._socket !== null) this._socket.unref();
return this;
}
_attach(type, socket) {
this._type = type;
this._socket = socket;
this._socket.on("connect", this._onconnect.bind(this)).on("timeout", this._ontimeout.bind(this)).on("error", this._onerror.bind(this)).on("data", this._ondata.bind(this)).on("end", this._onend.bind(this)).on("finish", this._onfinish.bind(this)).on("drain", this._ondrain.bind(this)).on("close", this._onclose.bind(this));
if (this._state & constants.state.UNREFED) this._socket.unref();
this._continueOpen();
return this;
}
_open(cb) {
if (this._socket !== null) return cb(null);
this._pendingOpen = cb;
}
_write(data, encoding, cb) {
if (this._socket.write(data)) return cb(null);
this._pendingWrite = cb;
}
_final(cb) {
this._socket.end();
this._pendingFinal = cb;
}
_destroy(err, cb) {
if (this._socket === null || this._socket.destroyed) return cb(null);
this._socket.destroy(err);
this._pendingDestroy = cb;
}
_onconnect() {
this.emit("connect");
}
_ontimeout() {
this.emit("timeout");
}
_onerror(err) {
this.destroy(err);
}
_ondata(data) {
this.push(data);
}
_onend() {
this.push(null);
}
_onfinish() {
this._continueFinal();
}
_ondrain() {
this._continueWrite();
}
_onclose() {
this._continueWrite();
this._continueFinal();
if (this._pendingDestroy) this._continueDestroy();
else this.destroy();
}
_continueOpen() {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(null);
}
_continueWrite() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_continueFinal() {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(null);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
};
exports.Server = class NetServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = false,
pauseOnConnect = false
} = opts;
this._type = 0;
this._state = 0;
this._server = null;
this._opts = { readBufferSize, allowHalfOpen, pauseOnConnect };
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return this._server !== null && this._server.listening;
}
address() {
return this._server === null ? null : this._server.address();
}
listen(...args) {
let opts = {};
let onlistening;
if (typeof args[0] === "string") {
opts.path = args[0];
if (typeof args[1] === "function") {
onlistening = args[1];
} else {
opts.backlog = args[1];
onlistening = args[2];
}
} else {
if (typeof args[0] === "function") {
onlistening = args[0];
} else {
opts.port = args[0];
if (typeof args[1] === "function") {
onlistening = args[1];
} else {
opts.host = args[1];
if (typeof args[2] === "function") {
onlistening = args[2];
} else {
opts.backlog = args[2];
onlistening = args[3];
}
}
}
}
opts = { ...opts, ...this._opts };
if (opts.path) {
this._attach(constants.type.IPC, pipe.createServer(opts));
} else {
this._attach(constants.type.TCP, tcp.createServer(opts));
}
this._server.listen(opts);
if (onlistening) this.once("listening", onlistening);
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
this._server.close();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._server !== null) this._server.ref();
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._server !== null) this._server.unref();
return this;
}
_attach(type, server) {
this._type = type;
this._server = server;
this._server.on("listening", this._onlistening.bind(this)).on("connection", this._onconnection.bind(this)).on("error", this._onerror.bind(this)).on("close", this._onclose.bind(this));
if (this._state & constants.state.UNREFED) this._server.unref();
return this;
}
_onlistening() {
this.emit("listening");
}
_onconnection(socket) {
this.emit("connection", new exports.Socket(this._opts)._attach(this._type, socket));
}
_onerror(err) {
this.emit("error", err);
}
_onclose() {
this.emit("close");
}
};
exports.constants = constants;
exports.isIP = tcp.isIP;
exports.isIPv4 = tcp.isIPv4;
exports.isIPv6 = tcp.isIPv6;
exports.createConnection = function createConnection(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
return new exports.Socket(opts).connect(opts, onconnect);
};
exports.connect = exports.createConnection;
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
}
});
// ../../node_modules/bare-tls/net.js
var require_net = __commonJS({
"../../node_modules/bare-tls/net.js"(exports) {
var EventEmitter = require_bare_events();
var net = require_bare_net();
var tls = require_bare_tls();
var TLSNetSocket = class extends tls.Socket {
ref() {
this.socket.ref();
}
unref() {
this.socket.unref();
}
};
var TLSNetServer = class extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
const {
cert = null,
key = null,
host = null,
alpnProtocols = null,
eagerOpen = true,
allowHalfOpen = true
} = opts;
super();
this._opts = {
cert,
key,
host,
alpnProtocols,
eagerOpen,
allowHalfOpen
};
this._server = net.createServer(opts);
this._server.on("listening", this._onlistening.bind(this)).on("connection", this._onconnection.bind(this)).on("error", this._onerror.bind(this)).on("close", this._onclose.bind(this));
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return this._server.listening;
}
address() {
return this._server.address();
}
listen(...args) {
this._server.listen(...args);
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
this._server.close();
}
ref() {
this._server.ref();
}
unref() {
this._server.unref();
}
_onlistening() {
this.emit("listening");
}
_onconnection(socket) {
this.emit(
"connection",
new TLSNetSocket(socket, { ...this._opts, isServer: true })
);
}
_onerror(err) {
this.emit("error", err);
}
_onclose() {
this.emit("close");
}
};
exports.createConnection = function createConnection(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
return new TLSNetSocket(net.createConnection(opts, onconnect), opts);
};
exports.createServer = function createServer(opts, onconnection) {
return new TLSNetServer(opts, onconnection);
};
}
});
// ../../node_modules/bare-tls/index.js
var require_bare_tls = __commonJS({
"../../node_modules/bare-tls/index.js"(exports) {
var { Duplex, Writable } = require_bare_stream();
var binding = require_binding6();
var constants = require_constants4();
var errors = require_errors7();
var defaultReadBufferSize = 65536;
var context = binding.context();
exports.Socket = class TLSSocket extends Duplex {
constructor(socket, opts = {}) {
const {
isServer = false,
cert = null,
key = null,
host = null,
alpnProtocols = null,
eagerOpen = true,
allowHalfOpen = true,
readBufferSize = defaultReadBufferSize
} = opts;
super({ eagerOpen });
this._state = 0;
this._socket = socket;
this._key = key;
this._cert = cert;
this._allowHalfOpen = allowHalfOpen;
this._pendingOpen = null;
this._pendingWrite = null;
this._reading = Buffer.alloc(readBufferSize);
this._buffer = [];
this._buffered = 0;
let alpn = null;
if (alpnProtocols && alpnProtocols.length > 0) {
const parts = [];
for (const protocol of alpnProtocols) {
const encoded = Buffer.from(protocol);
if (encoded.byteLength === 0 || encoded.byteLength > 255) {
throw new RangeError("ALPN protocol name must be 1-255 bytes");
}
parts.push(Buffer.of(encoded.byteLength), encoded);
}
alpn = Buffer.concat(parts);
}
try {
this._handle = binding.init(
context,
isServer,
cert,
key,
host,
alpn,
this,
this._onread,
this._onwrite
);
} catch (err) {
this._handle = null;
this.destroy(err);
}
}
get socket() {
return this._socket;
}
get encrypted() {
return true;
}
get alpnProtocol() {
return binding.alpnProtocol(this._handle);
}
_onconnect() {
this._state |= constants.state.CONNECTED;
this.emit("connect");
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(null);
}
_ondata(data) {
this._buffer.push(data);
this._buffered += data.byteLength;
while (this._buffered > 0) {
if (this._state & constants.state.CONNECTED) {
let read;
try {
read = binding.read(this._handle, this._reading);
} catch (err) {
return this.destroy(errors.from(err));
}
if (read < 0) break;
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._reading.subarray(0, read));
this.push(copy);
} else {
try {
if (binding.handshake(this._handle)) this._onconnect();
else break;
} catch (err) {
if (this._pendingOpen) {
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(errors.from(err));
} else {
this.destroy(errors.from(err));
}
return;
}
}
}
}
_ondrain() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_onend() {
this.push(null);
}
_onerror(err) {
if (this._pendingOpen) {
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
} else {
this.destroy(err);
}
}
_onread(data) {
if (this._buffered < data.byteLength) return 0;
let offset = 0;
let remaining = data.byteLength;
while (remaining > 0) {
const chunk = this._buffer[0];
if (chunk.byteLength <= remaining) {
data.set(chunk, offset);
offset += chunk.byteLength;
remaining -= chunk.byteLength;
this._buffer.shift();
} else {
data.set(chunk.subarray(0, remaining), offset);
this._buffer[0] = chunk.subarray(remaining);
remaining = 0;
}
}
this._buffered -= data.byteLength;
return data.byteLength;
}
_onwrite(data) {
this._socket.write(Buffer.from(data.slice()));
return data.byteLength;
}
_attach() {
if (this._state & constants.state.ATTACHED) return;
this._state |= constants.state.ATTACHED;
this._ondata = this._ondata.bind(this);
this._ondrain = this._ondrain.bind(this);
this._onend = this._onend.bind(this);
this._onerror = this._onerror.bind(this);
this._socket.on("data", this._ondata).on("drain", this._ondrain).on("end", this._onend).on("error", this._onerror);
}
_detach() {
if (!(this._state & constants.state.ATTACHED)) return;
this._state &= ~constants.state.ATTACHED;
this._socket.off("data", this._ondata).off("drain", this._ondrain).off("end", this._onend).off("error", this._onerror);
}
_open(cb) {
this._pendingOpen = cb;
this._attach();
try {
if (binding.handshake(this._handle)) this._onconnect();
} catch (err) {
this._pendingOpen = null;
cb(errors.from(err));
}
}
_write(data, encoding, cb) {
try {
binding.write(this._handle, data);
if (Writable.isBackpressured(this._socket)) {
this._pendingWrite = cb;
} else {
cb(null);
}
} catch (err) {
this._pendingWrite = null;
cb(errors.from(err));
}
}
_final(cb) {
try {
binding.shutdown(this._handle);
cb(null);
} catch (err) {
cb(err);
}
this._socket.end();
}
_predestroy() {
if (!this._handle) return;
this._detach();
binding.destroy(this._handle);
this._handle = null;
}
_destroy(err, cb) {
if (!this._handle) return cb(err);
this._detach();
binding.destroy(this._handle);
this._handle = null;
cb(err);
}
};
exports.TLSSocket = exports.Socket;
exports.constants = constants;
exports.errors = errors;
var net = require_net();
exports.createConnection = net.createConnection;
exports.createServer = net.createServer;
exports.connect = exports.createConnection;
}
});
// ../../node_modules/bare-https/lib/socket.js
var require_socket = __commonJS({
"../../node_modules/bare-https/lib/socket.js"(exports, module) {
var TLSSocket = require_bare_tls().Socket;
module.exports = class HTTPSSocket extends TLSSocket {
setKeepAlive(...args) {
this.socket.setKeepAlive(...args);
return this;
}
setNoDelay(...args) {
this.socket.setNoDelay(...args);
return this;
}
setTimeout(...args) {
this.socket.setTimeout(...args);
return this;
}
ref() {
this.socket.ref();
return this;
}
unref() {
this.socket.unref();
return this;
}
};
}
});
// ../../node_modules/bare-https/lib/agent.js
var require_agent2 = __commonJS({
"../../node_modules/bare-https/lib/agent.js"(exports, module) {
var HTTPAgent = require_bare_http1().Agent;
var HTTPSSocket = require_socket();
var HTTPSAgent = class extends HTTPAgent {
constructor(opts = {}) {
super({ defaultPort: 443, ...opts });
}
createConnection(opts) {
return new HTTPSSocket(super.createConnection(opts), opts);
}
};
HTTPSAgent.global = new HTTPSAgent({ keepAlive: 1e3, timeout: 5e3 });
module.exports = HTTPSAgent;
}
});
// ../../node_modules/bare-https/lib/server.js
var require_server2 = __commonJS({
"../../node_modules/bare-https/lib/server.js"(exports, module) {
var TCPServer = require_bare_tcp().Server;
var HTTPServerConnection = require_bare_http1().ServerConnection;
var HTTPSSocket = require_socket();
module.exports = class HTTPSServer extends TCPServer {
constructor(opts = {}, onrequest) {
if (typeof opts === "function") {
onrequest = opts;
opts = {};
}
super({ allowHalfOpen: false });
this._timeout = 0;
this.on("connection", (socket) => {
new HTTPServerConnection(this, new HTTPSSocket(socket, { ...opts, isServer: true }), opts);
});
if (onrequest) this.on("request", onrequest);
}
get timeout() {
return this._timeout || void 0;
}
setTimeout(ms = 0, ontimeout) {
if (ontimeout) this.on("timeout", ontimeout);
this._timeout = ms;
return this;
}
close(onclose) {
super.close(onclose);
for (const socket of this.connections) {
const connection = HTTPServerConnection.for(socket);
if (connection === null || connection.idle) {
socket.destroy();
}
}
return this;
}
};
}
});
// ../../node_modules/bare-https/lib/client-request.js
var require_client_request2 = __commonJS({
"../../node_modules/bare-https/lib/client-request.js"(exports, module) {
var HTTPClientRequest = require_bare_http1().ClientRequest;
var HTTPSAgent = require_agent2();
module.exports = class HTTPSClientRequest extends HTTPClientRequest {
constructor(opts = {}, onresponse = null) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
opts = opts ? { ...opts } : {};
opts.agent = opts.agent === false ? new HTTPSAgent() : opts.agent || HTTPSAgent.global;
super(opts, onresponse);
}
};
}
});
// ../../node_modules/bare-https/index.js
var require_bare_https = __commonJS({
"../../node_modules/bare-https/index.js"(exports) {
exports.Agent = require_agent2();
exports.globalAgent = exports.Agent.global;
exports.Server = require_server2();
exports.ClientRequest = require_client_request2();
exports.createServer = function createServer(opts, onrequest) {
return new exports.Server(opts, onrequest);
};
exports.request = function request(url, opts, onresponse) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
if (typeof url === "string") url = new URL(url);
if (isURL(url)) {
opts = opts ? { ...url, ...opts } : { ...url };
opts.host = url.hostname;
opts.path = url.pathname + url.search;
opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url);
} else {
opts = url ? { ...url } : {};
opts.host = opts.hostname || opts.host;
opts.port = typeof opts.port === "string" ? parseInt(opts.port, 10) : opts.port;
}
return new exports.ClientRequest(opts, onresponse);
};
function defaultPort(url) {
switch (url.protocol) {
case "ftp:":
return 21;
case "http:":
case "ws:":
return 80;
case "https:":
case "wss:":
return 443;
}
return null;
}
function isURL(url) {
return url !== null && typeof url === "object" && typeof url.protocol === "string" && typeof url.hostname === "string" && typeof url.pathname === "string" && typeof url.search === "string";
}
}
});
// ../../node_modules/bare-os/binding.js
var require_binding8 = __commonJS({
"../../node_modules/bare-os/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-os/lib/errors.js
var require_errors9 = __commonJS({
"../../node_modules/bare-os/lib/errors.js"(exports, module) {
module.exports = class OSError extends Error {
constructor(msg, code, fn = OSError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "OSError";
}
static UNKNOWN_SIGNAL(msg) {
return new OSError(msg, "UNKNOWN_SIGNAL", OSError.UNKNOWN_SIGNAL);
}
static TITLE_OVERFLOW(msg) {
return new OSError(msg, "TITLE_OVERFLOW", OSError.TITLE_OVERFLOW);
}
};
}
});
// ../../node_modules/bare-os/lib/constants.js
var require_constants7 = __commonJS({
"../../node_modules/bare-os/lib/constants.js"(exports, module) {
var binding = require_binding8();
module.exports = {
signals: binding.signals,
errnos: binding.errnos,
priority: binding.priority
};
}
});
// ../../node_modules/bare-os/index.js
var require_bare_os = __commonJS({
"../../node_modules/bare-os/index.js"(exports) {
var binding = require_binding8();
var errors = require_errors9();
var constants = require_constants7();
exports.constants = constants;
exports.EOL = binding.platform === "win32" ? "\r\n" : "\n";
exports.devNull = binding.platform === "win32" ? "\\\\.\\nul" : "/dev/null";
exports.platform = function platform() {
return binding.platform;
};
exports.arch = function arch() {
return binding.arch;
};
exports.type = binding.type;
exports.version = binding.version;
exports.release = binding.release;
exports.machine = binding.machine;
exports.execPath = binding.execPath;
exports.pid = binding.pid;
exports.ppid = binding.ppid;
exports.cwd = binding.cwd;
exports.chdir = binding.chdir;
exports.tmpdir = binding.tmpdir;
exports.homedir = binding.homedir;
exports.hostname = binding.hostname;
exports.userInfo = binding.userInfo;
exports.networkInterfaces = function networkInterfaces() {
const result = {};
for (const entry of binding.networkInterfaces()) {
const { name, ...properties } = entry;
if (result[name]) result[name].push(properties);
else result[name] = [properties];
}
return result;
};
exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
if (typeof signal === "string") {
if (signal in constants.signals === false) {
throw errors.UNKNOWN_SIGNAL("Unknown signal: " + signal);
}
signal = constants.signals[signal];
}
binding.kill(pid, signal);
};
exports.endianness = function endianness() {
return binding.isLittleEndian ? "LE" : "BE";
};
exports.availableParallelism = binding.availableParallelism;
exports.cpuUsage = function cpuUsage(previous) {
const current = binding.cpuUsage();
if (previous) {
return {
user: current.user - previous.user,
system: current.system - previous.system
};
}
return current;
};
exports.threadCpuUsage = function threadCpuUsage(previous) {
const current = binding.threadCpuUsage();
if (previous) {
return {
user: current.user - previous.user,
system: current.system - previous.system
};
}
return current;
};
exports.resourceUsage = binding.resourceUsage;
exports.memoryUsage = binding.memoryUsage;
exports.freemem = binding.freemem;
exports.totalmem = binding.totalmem;
exports.availableMemory = binding.availableMemory;
exports.constrainedMemory = binding.constrainedMemory;
exports.uptime = binding.uptime;
exports.loadavg = binding.loadavg;
exports.cpus = binding.cpus;
exports.getProcessTitle = binding.getProcessTitle;
exports.setProcessTitle = function setProcessTitle(title) {
if (typeof title !== "string") title = title.toString();
if (title.length >= 256) {
throw errors.TITLE_OVERFLOW("Process title is too long");
}
binding.setProcessTitle(title);
};
exports.getPriority = function getPriority(pid = 0) {
return binding.getPriority(pid);
};
exports.setPriority = function setPriority(pid, priority) {
if (priority === void 0) {
priority = pid;
pid = 0;
}
binding.setPriority(pid, priority);
};
exports.getEnvKeys = binding.getEnvKeys;
exports.getEnv = binding.getEnv;
exports.hasEnv = binding.hasEnv;
exports.setEnv = binding.setEnv;
exports.unsetEnv = binding.unsetEnv;
}
});
// ../../node_modules/bare-path/lib/constants.js
var require_constants8 = __commonJS({
"../../node_modules/bare-path/lib/constants.js"(exports, module) {
module.exports = {
CHAR_UPPERCASE_A: 65,
CHAR_LOWERCASE_A: 97,
CHAR_UPPERCASE_Z: 90,
CHAR_LOWERCASE_Z: 122,
CHAR_DOT: 46,
CHAR_FORWARD_SLASH: 47,
CHAR_BACKWARD_SLASH: 92,
CHAR_COLON: 58,
CHAR_QUESTION_MARK: 63
};
}
});
// ../../node_modules/bare-path/lib/shared.js
var require_shared = __commonJS({
"../../node_modules/bare-path/lib/shared.js"(exports) {
var {
CHAR_DOT,
CHAR_FORWARD_SLASH
} = require_constants8();
exports.normalizeString = function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let code = 0;
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) {
code = path.charCodeAt(i);
} else if (isPathSeparator(code)) {
break;
} else {
code = CHAR_FORWARD_SLASH;
}
if (isPathSeparator(code)) {
if (lastSlash === i - 1 || dots === 1) ;
else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf(separator);
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.substring(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
}
lastSlash = i;
dots = 0;
continue;
} else if (res.length !== 0) {
res = "";
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? `${separator}..` : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `${separator}${path.substring(lastSlash + 1, i)}`;
} else {
res = path.substring(lastSlash + 1, i);
}
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === CHAR_DOT && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
};
}
});
// ../../node_modules/bare-path/lib/posix.js
var require_posix = __commonJS({
"../../node_modules/bare-path/lib/posix.js"(exports) {
var os = require_bare_os();
var { normalizeString } = require_shared();
var {
CHAR_DOT,
CHAR_FORWARD_SLASH
} = require_constants8();
function isPosixPathSeparator(code) {
return code === CHAR_FORWARD_SLASH;
}
exports.win32 = require_win32();
exports.posix = exports;
exports.sep = "/";
exports.delimiter = ":";
exports.resolve = function resolve(...args) {
let resolvedPath = "";
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
const path = i >= 0 ? args[i] : os.cwd();
if (path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
if (resolvedAbsolute) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : ".";
};
exports.normalize = function normalize(path) {
if (path.length === 0) return ".";
const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);
if (path.length === 0) {
if (isAbsolute) return "/";
return trailingSeparator ? "./" : ".";
}
if (trailingSeparator) path += "/";
return isAbsolute ? `/${path}` : path;
};
exports.isAbsolute = function isAbsolute(path) {
return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
};
exports.join = function join(...args) {
if (args.length === 0) return ".";
let joined;
for (let i = 0; i < args.length; ++i) {
const arg = args[i];
if (arg.length > 0) {
if (joined === void 0) joined = arg;
else joined += `/${arg}`;
}
}
if (joined === void 0) return ".";
return exports.normalize(joined);
};
exports.relative = function relative(from, to) {
if (from === to) return "";
from = exports.resolve(from);
to = exports.resolve(to);
if (from === to) return "";
const fromStart = 1;
const fromEnd = from.length;
const fromLen = fromEnd - fromStart;
const toStart = 1;
const toLen = to.length - toStart;
const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1;
let i = 0;
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i);
if (fromCode !== to.charCodeAt(toStart + i)) {
break;
} else if (fromCode === CHAR_FORWARD_SLASH) {
lastCommonSep = i;
}
}
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
return to.substring(toStart + i + 1);
}
if (i === 0) {
return to.substring(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
lastCommonSep = i;
} else if (i === 0) {
lastCommonSep = 0;
}
}
}
let out = "";
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
out += out.length === 0 ? ".." : "/..";
}
}
return `${out}${to.substring(toStart + lastCommonSep)}`;
};
exports.toNamespacedPath = function toNamespacedPath(path) {
return path;
};
exports.dirname = function dirname(path) {
if (path.length === 0) return ".";
const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
let end = -1;
let matchedSlash = true;
for (let i = path.length - 1; i >= 1; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
end = i;
break;
}
} else {
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? "/" : ".";
if (hasRoot && end === 1) return "//";
return path.substring(0, end);
};
exports.basename = function basename(path, suffix) {
let start = 0;
let end = -1;
let matchedSlash = true;
if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
if (suffix === path) {
return "";
}
let extIdx = suffix.length - 1;
let firstNonSlashEnd = -1;
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
if (code === suffix.charCodeAt(extIdx)) {
if (--extIdx === -1) {
end = i;
}
} else {
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;
else if (end === -1) end = path.length;
return path.substring(start, end);
}
for (let i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return "";
return path.substring(start, end);
};
exports.extname = function extname(path) {
let startDot = -1;
let startPart = 0;
let end = -1;
let matchedSlash = true;
let preDotState = 0;
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
matchedSlash = false;
end = i + 1;
}
if (code === CHAR_DOT) {
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
preDotState = -1;
}
}
if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return "";
}
return path.substring(startDot, end);
};
}
});
// ../../node_modules/bare-path/lib/win32.js
var require_win32 = __commonJS({
"../../node_modules/bare-path/lib/win32.js"(exports) {
var os = require_bare_os();
var { normalizeString } = require_shared();
var {
CHAR_UPPERCASE_A,
CHAR_LOWERCASE_A,
CHAR_UPPERCASE_Z,
CHAR_LOWERCASE_Z,
CHAR_DOT,
CHAR_FORWARD_SLASH,
CHAR_BACKWARD_SLASH,
CHAR_COLON,
CHAR_QUESTION_MARK
} = require_constants8();
function isWindowsPathSeparator(code) {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
}
function isWindowsDeviceRoot(code) {
return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z;
}
exports.posix = require_posix();
exports.win32 = exports;
exports.sep = "\\";
exports.delimiter = ";";
exports.resolve = function resolve(...args) {
let resolvedDevice = "";
let resolvedTail = "";
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1; i--) {
let path;
if (i >= 0) {
path = args[i];
if (path.length === 0) continue;
} else if (resolvedDevice.length === 0) {
path = os.cwd();
} else {
path = os.getEnv(`=${resolvedDevice}`) || os.cwd();
if (path === void 0 || path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
path = `${resolvedDevice}\\`;
}
}
const len = path.length;
let rootEnd = 0;
let device = "";
let isAbsolute = false;
const code = path.charCodeAt(0);
if (len === 1) {
if (isWindowsPathSeparator(code)) {
rootEnd = 1;
isAbsolute = true;
}
} else if (isWindowsPathSeparator(code)) {
isAbsolute = true;
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2;
let last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
const firstPart = path.substring(last, j);
last = j;
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j === len || j !== last) {
device = `\\\\${firstPart}\\${path.substring(last, j)}`;
rootEnd = j;
}
}
}
} else {
rootEnd = 1;
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.substring(0, 2);
rootEnd = 2;
if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
isAbsolute = true;
rootEnd = 3;
}
}
if (device.length > 0) {
if (resolvedDevice.length > 0) {
if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
continue;
}
} else {
resolvedDevice = device;
}
}
if (resolvedAbsolute) {
if (resolvedDevice.length > 0) {
break;
}
} else {
resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`;
resolvedAbsolute = isAbsolute;
if (isAbsolute && resolvedDevice.length > 0) {
break;
}
}
}
resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isWindowsPathSeparator);
return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
};
exports.normalize = function normalize(path) {
const len = path.length;
if (len === 0) return ".";
let rootEnd = 0;
let device;
let isAbsolute = false;
const code = path.charCodeAt(0);
if (len === 1) {
return code === CHAR_FORWARD_SLASH ? "\\" : path;
}
if (isWindowsPathSeparator(code)) {
isAbsolute = true;
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2;
let last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
const firstPart = path.substring(last, j);
last = j;
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j === len) {
return `\\\\${firstPart}\\${path.substring(last)}\\`;
}
if (j !== last) {
device = `\\\\${firstPart}\\${path.substring(last, j)}`;
rootEnd = j;
}
}
}
} else {
rootEnd = 1;
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.substring(0, 2);
rootEnd = 2;
if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
isAbsolute = true;
rootEnd = 3;
}
}
let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, "\\", isWindowsPathSeparator) : "";
if (tail.length === 0 && !isAbsolute) {
tail = ".";
}
if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
tail += "\\";
}
if (device === void 0) {
return isAbsolute ? `\\${tail}` : tail;
}
return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
};
exports.isAbsolute = function isAbsolute(path) {
const len = path.length;
if (len === 0) return false;
const code = path.charCodeAt(0);
return isWindowsPathSeparator(code) || len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2));
};
exports.join = function join(...args) {
if (args.length === 0) return ".";
let joined;
let firstPart;
for (let i = 0; i < args.length; ++i) {
const arg = args[i];
if (arg.length > 0) {
if (joined === void 0) joined = firstPart = arg;
else joined += `\\${arg}`;
}
}
if (joined === void 0) return ".";
let needsReplace = true;
let slashCount = 0;
if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
++slashCount;
const firstLen = firstPart.length;
if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
++slashCount;
if (firstLen > 2) {
if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
++slashCount;
} else {
needsReplace = false;
}
}
}
}
if (needsReplace) {
while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
slashCount++;
}
if (slashCount >= 2) {
joined = `\\${joined.substring(slashCount)}`;
}
}
return exports.normalize(joined);
};
exports.relative = function relative(from, to) {
if (from === to) return "";
const fromOrig = exports.resolve(from);
const toOrig = exports.resolve(to);
if (fromOrig === toOrig) return "";
from = fromOrig.toLowerCase();
to = toOrig.toLowerCase();
if (from === to) return "";
let fromStart = 0;
while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
fromStart++;
}
let fromEnd = from.length;
while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
fromEnd--;
}
const fromLen = fromEnd - fromStart;
let toStart = 0;
while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
toStart++;
}
let toEnd = to.length;
while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
toEnd--;
}
const toLen = toEnd - toStart;
const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1;
let i = 0;
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i);
if (fromCode !== to.charCodeAt(toStart + i)) {
break;
} else if (fromCode === CHAR_BACKWARD_SLASH) {
lastCommonSep = i;
}
}
if (i !== length) {
if (lastCommonSep === -1) return toOrig;
} else {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
return toOrig.substring(toStart + i + 1);
}
if (i === 2) {
return toOrig.substring(toStart + i);
}
}
if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
lastCommonSep = i;
} else if (i === 2) {
lastCommonSep = 3;
}
}
if (lastCommonSep === -1) lastCommonSep = 0;
}
let out = "";
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
out += out.length === 0 ? ".." : "\\..";
}
}
toStart += lastCommonSep;
if (out.length > 0) {
return `${out}${toOrig.substring(toStart, toEnd)}`;
}
if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
++toStart;
}
return toOrig.substring(toStart, toEnd);
};
exports.toNamespacedPath = function toNamespacedPath(path) {
if (path.length === 0) return path;
const resolvedPath = exports.resolve(path);
if (resolvedPath.length <= 2) return path;
if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
const code = resolvedPath.charCodeAt(2);
if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
return `\\\\?\\UNC\\${resolvedPath.substring(2)}`;
}
}
} else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
return `\\\\?\\${resolvedPath}`;
}
return path;
};
exports.dirname = function dirname(path) {
const len = path.length;
if (len === 0) return ".";
let rootEnd = -1;
let offset = 0;
const code = path.charCodeAt(0);
if (len === 1) {
return isWindowsPathSeparator(code) ? path : ".";
}
if (isWindowsPathSeparator(code)) {
rootEnd = offset = 1;
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2;
let last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j === len) {
return path;
}
if (j !== last) {
rootEnd = offset = j + 1;
}
}
}
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2;
offset = rootEnd;
}
let end = -1;
let matchedSlash = true;
for (let i = len - 1; i >= offset; --i) {
if (isWindowsPathSeparator(path.charCodeAt(i))) {
if (!matchedSlash) {
end = i;
break;
}
} else {
matchedSlash = false;
}
}
if (end === -1) {
if (rootEnd === -1) return ".";
end = rootEnd;
}
return path.substring(0, end);
};
exports.basename = function basename(path, suffix) {
let start = 0;
let end = -1;
let matchedSlash = true;
if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
start = 2;
}
if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
if (suffix === path) return "";
let extIdx = suffix.length - 1;
let firstNonSlashEnd = -1;
for (let i = path.length - 1; i >= start; --i) {
const code = path.charCodeAt(i);
if (isWindowsPathSeparator(code)) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
if (code === suffix.charCodeAt(extIdx)) {
if (--extIdx === -1) {
end = i;
}
} else {
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;
else if (end === -1) end = path.length;
return path.substring(start, end);
}
for (let i = path.length - 1; i >= start; --i) {
if (isWindowsPathSeparator(path.charCodeAt(i))) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return "";
return path.substring(start, end);
};
exports.extname = function extname(path) {
let start = 0;
let startDot = -1;
let startPart = 0;
let end = -1;
let matchedSlash = true;
let preDotState = 0;
if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
start = startPart = 2;
}
for (let i = path.length - 1; i >= start; --i) {
const code = path.charCodeAt(i);
if (isWindowsPathSeparator(code)) {
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
matchedSlash = false;
end = i + 1;
}
if (code === CHAR_DOT) {
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
preDotState = -1;
}
}
if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return "";
}
return path.substring(startDot, end);
};
}
});
// ../../node_modules/bare-path/index.js
var require_bare_path = __commonJS({
"../../node_modules/bare-path/index.js"(exports, module) {
if (Bare.platform === "win32") {
module.exports = require_win32();
} else {
module.exports = require_posix();
}
}
});
// ../../node_modules/bare-url/binding.js
var require_binding9 = __commonJS({
"../../node_modules/bare-url/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-url/lib/errors.js
var require_errors10 = __commonJS({
"../../node_modules/bare-url/lib/errors.js"(exports, module) {
module.exports = class URLError extends Error {
constructor(msg, fn = URLError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(this, fn);
}
get name() {
return "URLError";
}
static INVALID_URL(msg, input) {
const err = new URLError(msg, URLError.INVALID_URL);
err.input = input;
return err;
}
static INVALID_URL_SCHEME(msg = "Invalid URL") {
return new URLError(msg, URLError.INVALID_URL_SCHEME);
}
static INVALID_FILE_URL_HOST(msg = "Invalid file: URL host") {
return new URLError(msg, URLError.INVALID_FILE_URL_HOST);
}
static INVALID_FILE_URL_PATH(msg = "Invalid file: URL path") {
return new URLError(msg, URLError.INVALID_FILE_URL_PATH);
}
};
}
});
// ../../node_modules/bare-url/lib/url-search-params.js
var require_url_search_params = __commonJS({
"../../node_modules/bare-url/lib/url-search-params.js"(exports, module) {
var kind = Symbol.for("bare.url.search-params.kind");
var URLSearchParams = class _URLSearchParams {
static _urls = /* @__PURE__ */ new WeakMap();
static get [kind]() {
return 0;
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
constructor(init, url = null) {
this._params = /* @__PURE__ */ new Map();
if (url) _URLSearchParams._urls.set(this, url);
if (typeof init === "string") {
this._parse(init);
} else if (init) {
for (const [name, value] of typeof init[Symbol.iterator] === "function" ? init : Object.entries(init)) {
this.append(name, value);
}
}
}
get [kind]() {
return _URLSearchParams[kind];
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-size
get size() {
return this._params.length;
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
append(name, value = null) {
if (value === null) return;
let list = this._params.get(name);
if (list === void 0) {
list = [];
this._params.set(name, list);
}
list.push(value);
this._update();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
delete(name, value = null) {
if (value === null) this._params.delete(name);
else {
let list = this._params.get(name);
if (list === void 0) return;
list = list.filter((found) => found !== value);
if (list.length === 0) this._params.delete(name);
else this._params.set(name, list);
}
this._update();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
get(name) {
const list = this._params.get(name);
if (list === void 0) return null;
return list[0];
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
getAll(name) {
const list = this._params.get(name);
if (list === void 0) return [];
return Array.from(list);
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
has(name, value = null) {
const list = this._params.get(name);
if (list === void 0) return false;
if (value === null) return true;
return list.includes(value);
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
set(name, value = null) {
if (value === null) this._params.delete(name);
else this._params.set(name, [value]);
this._update();
}
toString() {
return this._serialize();
}
toJSON() {
return [...this];
}
*[Symbol.iterator]() {
for (const [name, values] of this._params) {
for (const value of values) yield [name, value];
}
}
[Symbol.for("bare.inspect")]() {
const object = {
__proto__: { constructor: _URLSearchParams }
};
for (const [name, values] of this._params) {
if (values.length === 1) object[name] = values[0];
else object[name] = values;
}
return object;
}
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
_update() {
const url = _URLSearchParams._urls.get(this);
if (url === void 0) return;
url.search = this._serialize();
}
// https://url.spec.whatwg.org/#concept-urlencoded-parser
_parse(input) {
if (input[0] === "?") input = input.substring(1);
this._params = /* @__PURE__ */ new Map();
for (const sequence of input.split("&")) {
if (sequence.length === 0) continue;
let i = sequence.indexOf("=");
if (i === -1) i = sequence.length;
const name = decodeURIComponent(sequence.substring(0, i));
const value = decodeURIComponent(sequence.substring(i + 1, sequence.length));
let list = this._params.get(name);
if (list === void 0) {
list = [];
this._params.set(name, list);
}
list.push(value);
}
}
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
_serialize() {
let output = "";
for (let [name, values] of this._params) {
name = encodeURIComponent(name);
for (const value of values) {
if (output) output += "&";
output += name + "=" + encodeURIComponent(value);
}
}
return output;
}
};
module.exports = exports = URLSearchParams;
exports.isURLSearchParams = function isURLSearchParams(value) {
if (value instanceof URLSearchParams) return true;
return typeof value === "object" && value !== null && value[kind] === URLSearchParams[kind];
};
}
});
// ../../node_modules/bare-url/index.js
var require_bare_url = __commonJS({
"../../node_modules/bare-url/index.js"(exports, module) {
var path = require_bare_path();
var binding = require_binding9();
var errors = require_errors10();
var URLSearchParams = require_url_search_params();
var kind = Symbol.for("bare.url.kind");
var isWindows = Bare.platform === "win32";
var URL2 = class _URL {
static get [kind]() {
return 0;
}
constructor(input, base, opts = {}) {
if (arguments.length === 0) throw errors.INVALID_URL();
input = String(input);
if (base !== void 0) base = String(base);
this._components = new Uint32Array(8);
this._parse(input, base, opts.throw !== false);
if (this._href) this._params = new URLSearchParams(this.search, this);
}
get [kind]() {
return _URL[kind];
}
// https://url.spec.whatwg.org/#dom-url-href
get href() {
return this._href;
}
set href(value) {
this._update(value);
this._params._parse(this.search);
}
// https://url.spec.whatwg.org/#dom-url-protocol
get protocol() {
return this._slice(0, this._components[0]) + ":";
}
set protocol(value) {
this._update(this._replace(value.replace(/:+$/, ""), 0, this._components[0]));
}
// https://url.spec.whatwg.org/#dom-url-username
get username() {
return this._slice(this._components[0] + 3, this._components[1]);
}
set username(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
if (this.username === "") value += "@";
this._update(this._replace(value, this._components[0] + 3, this._components[1]));
}
// https://url.spec.whatwg.org/#dom-url-password
get password() {
return this._href.slice(
this._components[1] + 1,
this._components[2] - 1
/* @ */
);
}
set password(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
let start = this._components[1] + 1;
let end = this._components[2] - 1;
if (this.password === "") {
value = ":" + value;
start--;
}
if (this.username === "") {
value += "@";
end++;
}
this._update(this._replace(value, start, end));
}
// https://url.spec.whatwg.org/#dom-url-host
get host() {
return this._slice(this._components[2], this._components[5]);
}
set host(value) {
if (hasOpaquePath(this)) {
return;
}
this._update(
this._replace(value, this._components[2], this._components[value.includes(":") ? 5 : 3])
);
}
// https://url.spec.whatwg.org/#dom-url-hostname
get hostname() {
return this._slice(this._components[2], this._components[3]);
}
set hostname(value) {
if (hasOpaquePath(this)) {
return;
}
this._update(this._replace(value, this._components[2], this._components[3]));
}
// https://url.spec.whatwg.org/#dom-url-port
get port() {
return this._slice(this._components[3] + 1, this._components[5]);
}
set port(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
let start = this._components[3] + 1;
if (this.port === "") {
value = ":" + value;
start--;
}
this._update(this._replace(value, start, this._components[5]));
}
// https://url.spec.whatwg.org/#dom-url-pathname
get pathname() {
return this._slice(
this._components[5],
this._components[6] - 1
/* ? */
);
}
set pathname(value) {
if (hasOpaquePath(this)) {
return;
}
if (value[0] !== "/" && value[0] !== "\\") {
value = "/" + value;
}
this._update(this._replace(
value,
this._components[5],
this._components[6] - 1
/* ? */
));
}
// https://url.spec.whatwg.org/#dom-url-search
get search() {
return this._slice(
this._components[6] - 1,
this._components[7] - 1
/* # */
);
}
set search(value) {
if (value && value[0] !== "?") value = "?" + value;
this._update(
this._replace(
value,
this._components[6] - 1,
this._components[7] - 1
/* # */
)
);
this._params._parse(this.search);
}
// https://url.spec.whatwg.org/#dom-url-searchparams
get searchParams() {
return this._params;
}
// https://url.spec.whatwg.org/#dom-url-hash
get hash() {
return this._slice(
this._components[7] - 1
/* # */
);
}
set hash(value) {
if (value && value[0] !== "#") value = "#" + value;
this._update(this._replace(
value,
this._components[7] - 1
/* # */
));
}
toString() {
return this._href;
}
toJSON() {
return this._href;
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _URL },
href: this.href,
protocol: this.protocol,
username: this.username,
password: this.password,
host: this.host,
hostname: this.hostname,
port: this.port,
pathname: this.pathname,
search: this.search,
searchParams: this.searchParams,
hash: this.hash
};
}
_slice(start, end = this._href.length) {
return this._href.slice(start, end);
}
_replace(replacement, start, end = this._href.length) {
return this._slice(0, start) + replacement + this._slice(end);
}
_parse(input, base, shouldThrow) {
try {
this._href = binding.parse(
String(input),
base ? String(base) : null,
this._components,
shouldThrow
);
} catch (err) {
if (err instanceof TypeError) throw err;
throw errors.INVALID_URL(`Invalid URL '${input}'`, input);
}
}
_update(input) {
try {
this._parse(input, null, true);
} catch (err) {
if (err instanceof TypeError) throw err;
}
}
};
module.exports = exports = URL2;
function hasOpaquePath(url) {
return url.pathname[0] !== "/";
}
function cannotHaveCredentialsOrPort(url) {
return url.hostname === "" || url.protocol === "file:";
}
exports.URL = URL2;
exports.URLSearchParams = URLSearchParams;
exports.errors = errors;
exports.isURL = function isURL(value) {
if (value instanceof URL2) return true;
return typeof value === "object" && value !== null && value[kind] === URL2[kind];
};
exports.isURLSearchParams = URLSearchParams.isURLSearchParams;
exports.parse = function parse(input, base) {
const url = new URL2(input, base, { throw: false });
return url._href ? url : null;
};
exports.canParse = function canParse(input, base) {
return binding.canParse(String(input), base ? String(base) : null);
};
exports.fileURLToPath = function fileURLToPath(url) {
if (typeof url === "string") {
url = new URL2(url);
}
if (url.protocol !== "file:") {
throw errors.INVALID_URL_SCHEME("The URL must use the file: protocol");
}
if (isWindows) {
if (/%2f|%5c/i.test(url.pathname)) {
throw errors.INVALID_FILE_URL_PATH(
"The file: URL path must not include encoded \\ or / characters"
);
}
} else {
if (url.hostname) {
throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty");
}
if (/%2f/i.test(url.pathname)) {
throw errors.INVALID_FILE_URL_PATH("The file: URL path must not include encoded / characters");
}
}
const pathname = path.normalize(decodeURIComponent(url.pathname));
if (isWindows) {
if (url.hostname) return "\\\\" + url.hostname + pathname;
const letter = pathname.charCodeAt(1) | 32;
if (letter < 97 || letter > 122 || pathname.charCodeAt(2) !== 58) {
throw errors.INVALID_FILE_URL_PATH("The file: URL path must be absolute");
}
return pathname.slice(1);
}
return pathname;
};
exports.pathToFileURL = function pathToFileURL(pathname) {
let resolved = path.resolve(pathname);
if (pathname[pathname.length - 1] === "/") {
resolved += "/";
} else if (isWindows && pathname[pathname.length - 1] === "\\") {
resolved += "\\";
}
resolved = resolved.replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("?", "%3f").replaceAll("\n", "%0a").replaceAll("\r", "%0d").replaceAll(" ", "%09");
if (!isWindows) {
resolved = resolved.replaceAll("\\", "%5c");
}
return new URL2("file:" + resolved);
};
exports.format = function format(parts) {
const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts;
let result = "";
if (typeof protocol === "string") {
result += protocol;
if (protocol[protocol.length - 1] !== ":") {
result += ":";
}
if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
result += "//";
}
}
if (typeof auth === "string") {
if (host || hostname) result += auth + "@";
}
if (typeof host === "string") result += host;
else {
result += hostname;
if (port) result += ":" + port;
}
if (typeof pathname === "string" && pathname !== "") {
if (pathname[0] !== "/") result += "/";
result += pathname;
}
if (typeof search === "string") {
if (search[0] !== "?") result += "?";
result += search;
} else if (typeof query === "object" && query !== null) {
result += "?" + new URLSearchParams(query);
}
if (typeof hash === "string") {
if (hash[0] !== "#") result += "#";
result += hash;
}
return result;
};
}
});
// ../../node_modules/bare-buffer/binding.js
var require_binding10 = __commonJS({
"../../node_modules/bare-buffer/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-buffer/lib/constants.js
var require_constants9 = __commonJS({
"../../node_modules/bare-buffer/lib/constants.js"(exports, module) {
var binding = require_binding10();
module.exports = binding.constants;
}
});
// ../../node_modules/bare-buffer/lib/ascii.js
var require_ascii = __commonJS({
"../../node_modules/bare-buffer/lib/ascii.js"(exports) {
var binding = require_binding10();
exports.byteLength = function byteLength(string) {
return string.length;
};
exports.toString = function toString(buffer) {
const len = buffer.byteLength;
let result = "";
for (let i = 0; i < len; i++) {
result += String.fromCharCode(buffer[i] & 127);
}
return result;
};
exports.write = function write(buffer, string) {
const len = buffer.byteLength;
for (let i = 0; i < len; i++) {
buffer[i] = string.charCodeAt(i);
}
return len;
};
exports.validate = function validate(buffer) {
return binding.validateAscii(buffer.buffer, buffer.byteLength);
};
}
});
// ../../node_modules/bare-buffer/lib/base64.js
var require_base64 = __commonJS({
"../../node_modules/bare-buffer/lib/base64.js"(exports) {
var binding = require_binding10();
exports.byteLength = function byteLength(string) {
let len = string.length;
if (string.charCodeAt(len - 1) === 61) len--;
if (len > 1 && string.charCodeAt(len - 1) === 61) len--;
return len * 3 >>> 2;
};
exports.toString = function toString(buffer) {
return binding.toStringBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.write = function write(buffer, string) {
return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string);
};
}
});
// ../../node_modules/bare-buffer/lib/base64url.js
var require_base64url = __commonJS({
"../../node_modules/bare-buffer/lib/base64url.js"(exports) {
var binding = require_binding10();
exports.byteLength = function byteLength(string) {
let len = string.length;
if (string.charCodeAt(len - 1) === 61) len--;
if (len > 1 && string.charCodeAt(len - 1) === 61) len--;
return len * 3 >>> 2;
};
exports.toString = function toString(buffer) {
return binding.toStringBase64URL(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.write = function write(buffer, string) {
return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string);
};
}
});
// ../../node_modules/bare-buffer/lib/hex.js
var require_hex = __commonJS({
"../../node_modules/bare-buffer/lib/hex.js"(exports) {
var binding = require_binding10();
exports.byteLength = function byteLength(string) {
return string.length >>> 1;
};
exports.toString = function toString(buffer) {
return binding.toStringHex(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.write = function write(buffer, string) {
return binding.writeHex(buffer.buffer, buffer.byteOffset, buffer.byteLength, string);
};
}
});
// ../../node_modules/bare-buffer/lib/utf8.js
var require_utf8 = __commonJS({
"../../node_modules/bare-buffer/lib/utf8.js"(exports) {
var binding = require_binding10();
exports.byteLength = function byteLength(string) {
return binding.byteLengthUTF8(string);
};
exports.toString = function toString(buffer) {
return binding.toStringUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.write = function write(buffer, string) {
return binding.writeUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength, string);
};
exports.validate = function validate(buffer) {
return binding.validateUTF8(buffer.buffer, buffer.byteLength);
};
}
});
// ../../node_modules/bare-buffer/lib/utf16le.js
var require_utf16le = __commonJS({
"../../node_modules/bare-buffer/lib/utf16le.js"(exports) {
var binding = require_binding10();
exports.byteLength = function byteLength(string) {
return string.length * 2;
};
exports.toString = function toString(buffer) {
return binding.toStringUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.write = function write(buffer, string) {
return binding.writeUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength, string);
};
}
});
// ../../node_modules/bare-buffer/lib/latin1.js
var require_latin1 = __commonJS({
"../../node_modules/bare-buffer/lib/latin1.js"(exports) {
var binding = require_binding10();
exports.byteLength = function byteLength(string) {
return string.length;
};
exports.toString = function toString(buffer) {
return binding.toStringLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.write = function write(buffer, string) {
return binding.writeLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength, string);
};
}
});
// ../../node_modules/bare-buffer/index.js
var require_bare_buffer = __commonJS({
"../../node_modules/bare-buffer/index.js"(exports, module) {
var constants = require_constants9();
var ascii = require_ascii();
var base64 = require_base64();
var base64url = require_base64url();
var hex = require_hex();
var utf8 = require_utf8();
var utf16le = require_utf16le();
var latin1 = require_latin1();
var binding = require_binding10();
var kind = Symbol.for("bare.buffer.kind");
var poolSize = 0;
module.exports = exports = class Buffer3 extends Uint8Array {
static get [kind]() {
return 0;
}
static get poolSize() {
return poolSize;
}
static set poolSize(value) {
poolSize = Math.max(0, value);
}
constructor(arrayBuffer, offset, length, opts = {}) {
if (typeof arrayBuffer === "number") {
opts = offset || {};
const { uninitialized = false } = opts;
offset = 0;
length = arrayBuffer;
if (length > constants.MAX_LENGTH) {
throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`);
}
arrayBuffer = uninitialized ? binding.allocUnsafe(length) : binding.alloc(length);
} else {
if (length > constants.MAX_LENGTH) {
throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`);
}
if (typeof offset === "object" && offset !== null) {
opts = offset;
offset = 0;
length = arrayBuffer.byteLength;
} else if (typeof length === "length" && length !== null) {
opts = length;
length = arrayBuffer.byteLength - offset;
}
}
super(arrayBuffer, offset, length);
}
get [kind]() {
return Buffer3[kind];
}
copy(target, targetStart = 0, sourceStart = 0, sourceEnd = this.byteLength) {
let source = this;
if (targetStart < 0) targetStart = 0;
if (targetStart >= target.byteLength) return 0;
const targetLength = target.byteLength - targetStart;
if (sourceStart < 0) sourceStart = 0;
if (sourceStart >= source.byteLength) return 0;
if (sourceEnd <= sourceStart) return 0;
if (sourceEnd > source.byteLength) sourceEnd = source.byteLength;
if (sourceEnd - sourceStart > targetLength) {
sourceEnd = sourceStart + targetLength;
}
const sourceLength = sourceEnd - sourceStart;
if (source === target) {
target.copyWithin(targetStart, sourceStart, sourceEnd);
} else {
if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
source = source.subarray(sourceStart, sourceEnd);
}
target.set(source, targetStart);
}
return sourceLength;
}
equals(target) {
const source = this;
if (source === target) return true;
if (source.byteLength !== target.byteLength) return false;
return binding.compare(
source.buffer,
source.byteOffset,
source.byteLength,
target.buffer,
target.byteOffset,
target.byteLength
) === 0;
}
compare(target, targetStart = 0, targetEnd = target.byteLength, sourceStart = 0, sourceEnd = this.byteLength) {
let source = this;
if (source === target) return 0;
if (arguments.length > 1) {
if (targetStart < 0) targetStart = 0;
if (targetStart > target.byteLength) targetStart = target.byteLength;
if (targetEnd < targetStart) targetEnd = targetStart;
if (targetEnd > target.byteLength) targetEnd = target.byteLength;
if (sourceStart < 0) sourceStart = 0;
if (sourceStart > source.byteLength) sourceStart = source.byteLength;
if (sourceEnd < sourceStart) sourceEnd = sourceStart;
if (sourceEnd > source.byteLength) sourceEnd = source.byteLength;
if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
source = source.subarray(sourceStart, sourceEnd);
}
if (targetStart !== 0 || targetEnd !== target.byteLength) {
target = target.subarray(targetStart, targetEnd);
}
}
return binding.compare(
source.buffer,
source.byteOffset,
source.byteLength,
target.buffer,
target.byteOffset,
target.byteLength
);
}
fill(value, offset = 0, end = this.byteLength, encoding = "utf8") {
if (typeof value === "string") {
if (typeof offset === "string") {
encoding = offset;
offset = 0;
end = this.byteLength;
} else if (typeof end === "string") {
encoding = end;
end = this.byteLength;
}
} else if (typeof value === "number") {
value = value & 255;
} else if (typeof value === "boolean") {
value = +value;
}
if (offset < 0) offset = 0;
if (offset >= this.byteLength) return this;
if (end <= offset) return this;
if (end > this.byteLength) end = this.byteLength;
if (typeof value === "number") return super.fill(value, offset, end);
if (typeof value === "string") value = exports.from(value, encoding);
const length = value.byteLength;
for (let i = 0, n = end - offset; i < n; ++i) {
this[i + offset] = value[i % length];
}
return this;
}
includes(value, offset, encoding) {
return this.indexOf(value, offset, encoding) !== -1;
}
indexOf(value, offset = 0, encoding) {
if (typeof value === "boolean") value = +value;
if (typeof value === "number") {
return super.indexOf(value & 255, offset);
}
return bidirectionalIndexOf(
this,
value,
offset,
encoding,
true
/* first */
);
}
lastIndexOf(value, offset = this.byteLength - 1, encoding) {
if (typeof value === "boolean") value = +value;
if (typeof value === "number") {
return super.lastIndexOf(value & 255, offset);
}
return bidirectionalIndexOf(
this,
value,
offset,
encoding,
false
/* last */
);
}
swap16() {
const length = this.byteLength;
if (length % 2 !== 0) {
throw new RangeError("Buffer size must be a multiple of 16-bits");
}
for (let i = 0; i < length; i += 2) swap(this, i, i + 1);
return this;
}
swap32() {
const length = this.byteLength;
if (length % 4 !== 0) {
throw new RangeError("Buffer size must be a multiple of 32-bits");
}
for (let i = 0; i < length; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
}
swap64() {
const length = this.byteLength;
if (length % 8 !== 0) {
throw new RangeError("Buffer size must be a multiple of 64-bits");
}
for (let i = 0; i < length; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
}
toString(encoding = "utf8", start = 0, end = this.byteLength) {
if (arguments.length === 0) return utf8.toString(this);
if (arguments.length === 1) return codecFor(encoding).toString(this);
if (start < 0) start = 0;
if (start >= this.byteLength) return "";
if (end <= start) return "";
if (end > this.byteLength) end = this.byteLength;
let buffer = this;
if (start !== 0 || end !== this.byteLength) {
buffer = buffer.subarray(start, end);
}
return codecFor(encoding).toString(buffer);
}
toJSON() {
return Array.from(this);
}
write(string, offset = 0, length = this.byteLength - offset, encoding = "utf8") {
if (arguments.length === 1) return utf8.write(this, string);
if (typeof offset === "string") {
encoding = offset;
offset = 0;
length = this.byteLength;
} else if (typeof length === "string") {
encoding = length;
length = this.byteLength - offset;
}
length = Math.min(length, exports.byteLength(string, encoding));
let start = offset;
if (start < 0) start = 0;
if (start >= this.byteLength) return 0;
let end = offset + length;
if (end <= start) return 0;
if (end > this.byteLength) end = this.byteLength;
let buffer = this;
if (start !== 0 || end !== this.byteLength) {
buffer = buffer.subarray(start, end);
}
return codecFor(encoding).write(buffer, string);
}
readBigInt64BE(offset = 0) {
return viewOf(this).getBigInt64(offset, false);
}
readBigInt64LE(offset = 0) {
return viewOf(this).getBigInt64(offset, true);
}
readBigUint64BE(offset = 0) {
return viewOf(this).getBigUint64(offset, false);
}
readBigUint64LE(offset = 0) {
return viewOf(this).getBigUint64(offset, true);
}
readDoubleBE(offset = 0) {
return viewOf(this).getFloat64(offset, false);
}
readDoubleLE(offset = 0) {
return viewOf(this).getFloat64(offset, true);
}
readFloatBE(offset = 0) {
return viewOf(this).getFloat32(offset, false);
}
readFloatLE(offset = 0) {
return viewOf(this).getFloat32(offset, true);
}
readInt8(offset = 0) {
return viewOf(this).getInt8(offset);
}
readInt16BE(offset = 0) {
return viewOf(this).getInt16(offset, false);
}
readInt16LE(offset = 0) {
return viewOf(this).getInt16(offset, true);
}
readInt32BE(offset = 0) {
return viewOf(this).getInt32(offset, false);
}
readInt32LE(offset = 0) {
return viewOf(this).getInt32(offset, true);
}
readIntBE(offset, byteLength) {
if (byteLength === 6) return readInt48BE(viewOf(this), offset);
if (byteLength === 5) return readInt40BE(viewOf(this), offset);
if (byteLength === 3) return readInt24BE(viewOf(this), offset);
if (byteLength === 4) return this.readInt32BE(offset);
if (byteLength === 2) return this.readInt16BE(offset);
if (byteLength === 1) return this.readInt8(offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
readIntLE(offset, byteLength) {
if (byteLength === 6) return readInt48LE(viewOf(this), offset);
if (byteLength === 5) return readInt40LE(viewOf(this), offset);
if (byteLength === 3) return readInt24LE(viewOf(this), offset);
if (byteLength === 4) return this.readInt32LE(offset);
if (byteLength === 2) return this.readInt16LE(offset);
if (byteLength === 1) return this.readInt8(offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
readUint8(offset = 0) {
return viewOf(this).getUint8(offset);
}
readUint16BE(offset = 0) {
return viewOf(this).getUint16(offset, false);
}
readUint16LE(offset = 0) {
return viewOf(this).getUint16(offset, true);
}
readUint32BE(offset = 0) {
return viewOf(this).getUint32(offset, false);
}
readUint32LE(offset = 0) {
return viewOf(this).getUint32(offset, true);
}
readUintBE(offset, byteLength) {
if (byteLength === 6) return readUint48BE(viewOf(this), offset);
if (byteLength === 5) return readUint40BE(viewOf(this), offset);
if (byteLength === 3) return readUint24BE(viewOf(this), offset);
if (byteLength === 4) return this.readUint32BE(offset);
if (byteLength === 2) return this.readUint16BE(offset);
if (byteLength === 1) return this.readUint8(offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
readUintLE(offset, byteLength) {
if (byteLength === 6) return readUint48LE(viewOf(this), offset);
if (byteLength === 5) return readUint40LE(viewOf(this), offset);
if (byteLength === 3) return readUint24LE(viewOf(this), offset);
if (byteLength === 4) return this.readUint32LE(offset);
if (byteLength === 2) return this.readUint16LE(offset);
if (byteLength === 1) return this.readUint8(offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
readBigUInt64BE(...args) {
return this.readBigUint64BE(...args);
}
readBigUInt64LE(...args) {
return this.readBigUint64LE(...args);
}
readUInt8(...args) {
return this.readUint8(...args);
}
readUInt16BE(...args) {
return this.readUint16BE(...args);
}
readUInt16LE(...args) {
return this.readUint16LE(...args);
}
readUInt32BE(...args) {
return this.readUint32BE(...args);
}
readUInt32LE(...args) {
return this.readUint32LE(...args);
}
readUIntBE(...args) {
return this.readUintBE(...args);
}
readUIntLE(...args) {
return this.readUintLE(...args);
}
writeBigInt64BE(value, offset = 0) {
viewOf(this).setBigInt64(offset, value, false);
return offset + 8;
}
writeBigInt64LE(value, offset = 0) {
viewOf(this).setBigInt64(offset, value, true);
return offset + 8;
}
writeBigUint64BE(value, offset = 0) {
viewOf(this).setBigUint64(offset, value, false);
return offset + 8;
}
writeBigUint64LE(value, offset = 0) {
viewOf(this).setBigUint64(offset, value, true);
return offset + 8;
}
writeDoubleBE(value, offset = 0) {
viewOf(this).setFloat64(offset, value, false);
return offset + 8;
}
writeDoubleLE(value, offset = 0) {
viewOf(this).setFloat64(offset, value, true);
return offset + 8;
}
writeFloatBE(value, offset = 0) {
viewOf(this).setFloat32(offset, value, false);
return offset + 4;
}
writeFloatLE(value, offset = 0) {
viewOf(this).setFloat32(offset, value, true);
return offset + 4;
}
writeInt8(value, offset = 0) {
viewOf(this).setInt8(offset, value);
return offset + 1;
}
writeInt16BE(value, offset = 0) {
viewOf(this).setInt16(offset, value, false);
return offset + 2;
}
writeInt16LE(value, offset = 0) {
viewOf(this).setInt16(offset, value, true);
return offset + 2;
}
writeInt32BE(value, offset = 0) {
viewOf(this).setInt32(offset, value, false);
return offset + 4;
}
writeInt32LE(value, offset = 0) {
viewOf(this).setInt32(offset, value, true);
return offset + 4;
}
writeIntBE(value, offset, byteLength) {
if (byteLength === 6) return writeInt48BE(value, viewOf(this), offset);
if (byteLength === 5) return writeInt40BE(value, viewOf(this), offset);
if (byteLength === 3) return writeInt24BE(value, viewOf(this), offset);
if (byteLength === 4) return this.writeInt32BE(value, offset);
if (byteLength === 2) return this.writeInt16BE(value, offset);
if (byteLength === 1) return this.writeInt8(value, offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
writeIntLE(value, offset, byteLength) {
if (byteLength === 6) return writeInt48LE(value, viewOf(this), offset);
if (byteLength === 5) return writeInt40LE(value, viewOf(this), offset);
if (byteLength === 3) return writeInt24LE(value, viewOf(this), offset);
if (byteLength === 4) return this.writeInt32LE(value, offset);
if (byteLength === 2) return this.writeInt16LE(value, offset);
if (byteLength === 1) return this.writeInt8(value, offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
writeUint8(value, offset = 0) {
viewOf(this).setUint8(offset, value, true);
return offset + 1;
}
writeUint16BE(value, offset = 0) {
viewOf(this).setUint16(offset, value, false);
return offset + 2;
}
writeUint16LE(value, offset = 0) {
viewOf(this).setUint16(offset, value, true);
return offset + 2;
}
writeUint32LE(value, offset = 0) {
viewOf(this).setUint32(offset, value, true);
return offset + 4;
}
writeUint32BE(value, offset = 0) {
viewOf(this).setUint32(offset, value, false);
return offset + 4;
}
writeUintBE(value, offset, byteLength) {
if (byteLength === 6) return writeUint48BE(value, viewOf(this), offset);
if (byteLength === 5) return writeUint40BE(value, viewOf(this), offset);
if (byteLength === 3) return writeUint24BE(value, viewOf(this), offset);
if (byteLength === 4) return this.writeUint32BE(value, offset);
if (byteLength === 2) return this.writeUint16BE(value, offset);
if (byteLength === 1) return this.writeUint8(value, offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
writeUintLE(value, offset, byteLength) {
if (byteLength === 6) return writeUint48LE(value, viewOf(this), offset);
if (byteLength === 5) return writeUint40LE(value, viewOf(this), offset);
if (byteLength === 3) return writeUint24LE(value, viewOf(this), offset);
if (byteLength === 4) return this.writeUint32LE(value, offset);
if (byteLength === 2) return this.writeUint16LE(value, offset);
if (byteLength === 1) return this.writeUint8(value, offset);
throw new RangeError(`Byte length must be between 1 and 6`);
}
writeBigUInt64BE(...args) {
return this.writeBigUint64BE(...args);
}
writeBigUInt64LE(...args) {
return this.writeBigUint64LE(...args);
}
writeUInt8(...args) {
return this.writeUint8(...args);
}
writeUInt16BE(...args) {
return this.writeUint16BE(...args);
}
writeUInt16LE(...args) {
return this.writeUint16LE(...args);
}
writeUInt32BE(...args) {
return this.writeUint32BE(...args);
}
writeUInt32LE(...args) {
return this.writeUint32LE(...args);
}
writeUIntBE(...args) {
return this.writeUintBE(...args);
}
writeUIntLE(...args) {
return this.writeUintLE(...args);
}
};
var Buffer2 = exports;
exports.Buffer = Buffer2;
exports.constants = constants;
var codecs = /* @__PURE__ */ Object.create(null);
codecs.ascii = ascii;
codecs.base64 = base64;
codecs.base64url = base64url;
codecs.hex = hex;
codecs.utf8 = codecs["utf-8"] = utf8;
codecs.utf16le = codecs.ucs2 = codecs["utf-16le"] = codecs["ucs-2"] = utf16le;
codecs.latin1 = codecs.binary = latin1;
function codecFor(encoding = "utf8") {
if (encoding in codecs) return codecs[encoding];
encoding = encoding.toLowerCase();
if (encoding in codecs) return codecs[encoding];
throw new Error(`Unknown encoding '${encoding}'`);
}
var views = /* @__PURE__ */ new WeakMap();
function viewOf(buffer) {
let view = views.get(buffer);
if (view === void 0) {
view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
views.set(buffer, view);
}
return view;
}
exports.isBuffer = function isBuffer(value) {
if (value instanceof Buffer2) return true;
return typeof value === "object" && value !== null && value[kind] === Buffer2[kind];
};
exports.isEncoding = function isEncoding(encoding) {
try {
codecFor(encoding);
return true;
} catch {
return false;
}
};
exports.isASCII = function isASCII(buffer) {
return ascii.validate(buffer);
};
exports.isAscii = exports.isASCII;
exports.isUTF8 = function isUTF8(buffer) {
return utf8.validate(buffer);
};
exports.isUtf8 = exports.isUTF8;
exports.alloc = function alloc(size, fill, encoding) {
const buffer = new Buffer2(size);
if (fill !== void 0) buffer.fill(fill, 0, buffer.byteLength, encoding);
return buffer;
};
exports.allocUnsafe = function allocUnsafe(size) {
return new Buffer2(size, { uninitialized: true });
};
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
return exports.allocUnsafe(size);
};
exports.byteLength = function byteLength(string, encoding) {
if (typeof string === "string") {
return codecFor(encoding).byteLength(string);
}
return string.byteLength;
};
exports.compare = function compare(a, b) {
return binding.compare(a.buffer, a.byteOffset, a.byteLength, b.buffer, b.byteOffset, b.byteLength);
};
exports.concat = function concat(buffers, length) {
if (length === void 0) {
length = buffers.reduce((length2, buffer) => length2 + buffer.byteLength, 0);
}
const result = new Buffer2(length);
for (let i = 0, n = buffers.length, offset = 0; i < n; i++) {
const buffer = buffers[i];
if (offset + buffer.byteLength > result.byteLength) {
result.set(buffer.subarray(0, result.byteLength - offset), offset);
return result;
}
result.set(buffer, offset);
offset += buffer.byteLength;
}
return result;
};
exports.coerce = function coerce(buffer) {
if (exports.isBuffer(buffer)) return buffer;
return new Buffer2(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.copyBytesFrom = function copyBytesFrom(view, offset = 0, length = view.length - offset) {
if (offset + length > view.length) {
throw new RangeError("View length is out of range");
}
if (offset !== 0 || length !== view.length) {
view = view.subarray(offset, offset + length);
}
return new Buffer2(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
};
exports.from = function from(value, encodingOrOffset, length) {
if (typeof value === "string") return fromString(value, encodingOrOffset);
if (Array.isArray(value)) return fromArray(value);
if (ArrayBuffer.isView(value)) return fromBuffer(value);
return fromArrayBuffer(value, encodingOrOffset, length);
};
function fromString(string, encoding) {
const codec = codecFor(encoding);
const buffer = new Buffer2(codec.byteLength(string));
codec.write(buffer, string);
return buffer;
}
function fromArray(array) {
const buffer = new Buffer2(array.length);
buffer.set(array);
return buffer;
}
function fromBuffer(buffer) {
const copy = new Buffer2(buffer.byteLength);
copy.set(buffer);
return copy;
}
function fromArrayBuffer(arrayBuffer, offset, length) {
return new Buffer2(arrayBuffer, offset, length);
}
function bidirectionalIndexOf(buffer, value, offset, encoding, first) {
if (buffer.byteLength === 0) return -1;
if (typeof offset === "string") {
encoding = offset;
offset = 0;
} else if (offset === void 0) {
offset = first ? 0 : buffer.byteLength - 1;
} else if (offset < 0) {
offset += buffer.byteLength;
}
if (offset >= buffer.byteLength) {
if (first) return -1;
else offset = buffer.byteLength - 1;
} else if (offset < 0) {
if (first) offset = 0;
else return -1;
}
if (typeof value === "string") value = exports.from(value, encoding);
if (value.byteLength === 0) return -1;
if (first) {
let foundIndex = -1;
for (let i = offset; i < buffer.byteLength; i++) {
if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === value.byteLength) return foundIndex;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (offset + value.byteLength > buffer.byteLength) {
offset = buffer.byteLength - value.byteLength;
}
for (let i = offset; i >= 0; i--) {
let found = true;
for (let j = 0; j < value.byteLength; j++) {
if (buffer[i + j] !== value[j]) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
function swap(buffer, n, m) {
const i = buffer[n];
buffer[n] = buffer[m];
buffer[m] = i;
}
exports.atob = function atob(data) {
return Buffer2.from(data, "base64").toString("latin1");
};
exports.btoa = function btoa(data) {
if (typeof data !== "string") data = String(data);
return Buffer2.from(data, "latin1").toString("base64");
};
exports.transcode = function transcode(buffer, from, to) {
return Buffer2.from(buffer.toString(from), to);
};
function readInt48BE(view, offset) {
const hi = view.getUint16(offset, false);
const lo = view.getUint32(offset + 2, false);
let value = lo + hi * 4294967296;
if (hi & 32768) value -= 281474976710656;
return value;
}
function readInt48LE(view, offset) {
const lo = view.getUint32(offset, true);
const hi = view.getUint16(offset + 4, true);
let value = lo + hi * 4294967296;
if (hi & 32768) value -= 281474976710656;
return value;
}
function readInt40BE(view, offset) {
const hi = view.getUint8(offset);
const lo = view.getUint32(offset + 1, false);
let value = lo + hi * 4294967296;
if (hi & 128) value -= 1099511627776;
return value;
}
function readInt40LE(view, offset) {
const lo = view.getUint32(offset, true);
const hi = view.getUint8(offset + 4);
let value = lo + hi * 4294967296;
if (hi & 128) value -= 1099511627776;
return value;
}
function readInt24BE(view, offset) {
const value = view.getUint8(offset) << 16 | view.getUint8(offset + 1) << 8 | view.getUint8(offset + 2);
return value & 8388608 ? value - 16777216 : value;
}
function readInt24LE(view, offset) {
const value = view.getUint8(offset) | view.getUint8(offset + 1) << 8 | view.getUint8(offset + 2) << 16;
return value & 8388608 ? value - 16777216 : value;
}
function readUint48BE(view, offset) {
const hi = view.getUint16(offset, false);
const lo = view.getUint32(offset + 2, false);
return lo + hi * 4294967296;
}
function readUint48LE(view, offset) {
const lo = view.getUint32(offset, true);
const hi = view.getUint16(offset + 4, true);
return lo + hi * 4294967296;
}
function readUint40BE(view, offset) {
const hi = view.getUint8(offset);
const lo = view.getUint32(offset + 1, false);
return lo + hi * 4294967296;
}
function readUint40LE(view, offset) {
const lo = view.getUint32(offset, true);
const hi = view.getUint8(offset + 4);
return lo + hi * 4294967296;
}
function readUint24BE(view, offset) {
return view.getUint8(offset) << 16 | view.getUint8(offset + 1) << 8 | view.getUint8(offset + 2);
}
function readUint24LE(view, offset) {
return view.getUint8(offset) | view.getUint8(offset + 1) << 8 | view.getUint8(offset + 2) << 16;
}
function writeInt48BE(value, view, offset) {
if (value < 0) value += 281474976710656;
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint16(offset, hi, false);
view.setUint32(offset + 2, lo, false);
return offset + 6;
}
function writeInt48LE(value, view, offset) {
if (value < 0) value += 281474976710656;
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint32(offset, lo, true);
view.setUint16(offset + 4, hi, true);
return offset + 6;
}
function writeInt40BE(value, view, offset) {
if (value < 0) value += 1099511627776;
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint8(offset, hi);
view.setUint32(offset + 1, lo, false);
return offset + 5;
}
function writeInt40LE(value, view, offset) {
if (value < 0) value += 1099511627776;
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint32(offset, lo, true);
view.setUint8(offset + 4, hi);
return offset + 5;
}
function writeInt24BE(value, view, offset) {
if (value < 0) value += 16777216;
view.setUint8(offset, value >> 16 & 255);
view.setUint8(offset + 1, value >> 8 & 255);
view.setUint8(offset + 2, value & 255);
return offset + 3;
}
function writeInt24LE(value, view, offset) {
if (value < 0) value += 16777216;
view.setUint8(offset, value & 255);
view.setUint8(offset + 1, value >> 8 & 255);
view.setUint8(offset + 2, value >> 16 & 255);
return offset + 3;
}
function writeUint48BE(value, view, offset) {
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint16(offset, hi, false);
view.setUint32(offset + 2, lo, false);
return offset + 6;
}
function writeUint48LE(value, view, offset) {
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint32(offset, lo, true);
view.setUint16(offset + 4, hi, true);
return offset + 6;
}
function writeUint40BE(value, view, offset) {
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint8(offset, hi);
view.setUint32(offset + 1, lo, false);
return offset + 5;
}
function writeUint40LE(value, view, offset) {
const hi = Math.floor(value / 4294967296);
const lo = value >>> 0;
view.setUint32(offset, lo, true);
view.setUint8(offset + 4, hi);
return offset + 5;
}
function writeUint24BE(value, view, offset) {
view.setUint8(offset, value >> 16 & 255);
view.setUint8(offset + 1, value >> 8 & 255);
view.setUint8(offset + 2, value & 255);
return offset + 3;
}
function writeUint24LE(value, view, offset) {
view.setUint8(offset, value & 255);
view.setUint8(offset + 1, value >> 8 & 255);
view.setUint8(offset + 2, value >> 16 & 255);
return offset + 3;
}
}
});
// ../../node_modules/bare-form-data/lib/errors.js
var require_errors11 = __commonJS({
"../../node_modules/bare-form-data/lib/errors.js"(exports, module) {
module.exports = class FormDataError extends Error {
constructor(msg, code, fn = FormDataError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "FormDataError";
}
static INVALID_MIME_TYPE(msg) {
return new FormDataError(msg, "INVALID_MIME_TYPE", FormDataError.INVALID_MIME_TYPE);
}
};
}
});
// ../../node_modules/bare-form-data/index.js
var require_bare_form_data = __commonJS({
"../../node_modules/bare-form-data/index.js"(exports, module) {
var { ReadableStream } = require_web2();
var { isBuffer } = require_bare_buffer();
var errors = require_errors11();
var FormData = class _FormData {
constructor() {
this._entries = [];
}
append(name, value, filename) {
if (typeof value !== "string") {
if (!isFile(value) || filename) {
value = new File([value], filename || "blob", { type: value.type });
}
}
this._entries.push([name, value]);
}
delete(name) {
this._entries = this._entries.filter((entry) => entry[0] !== name);
}
get(name) {
const entry = this._entries.find((entry2) => entry2[0] === name);
return entry ? entry[1] : null;
}
getAll(name) {
const entries = [];
for (const entry of this._entries) {
if (entry[0] === name) entries.push(entry[1]);
}
return entries;
}
has(name) {
return this._entries.findIndex((entry) => entry[0] === name) !== -1;
}
set(name, value, filename) {
this.delete(name);
this.append(name, value, filename);
}
[Symbol.iterator]() {
return this._entries[Symbol.iterator]();
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _FormData },
entries: this._entries
};
}
};
module.exports = exports = FormData;
exports.FormData = FormData;
function isFormData(value) {
return value instanceof FormData;
}
exports.isFormData = isFormData;
var Blob = class _Blob {
// https://w3c.github.io/FileAPI/#dom-blob-blob
constructor(parts, options = {}) {
const { type = "" } = options;
this._bytes = processBlobParts(parts);
this._type = type;
}
// https://w3c.github.io/FileAPI/#dfn-size
get size() {
return this._bytes.byteLength;
}
// https://w3c.github.io/FileAPI/#dfn-type
get type() {
return this._type;
}
// https://w3c.github.io/FileAPI/#stream-method-algo
stream() {
const bytes = this._bytes;
return new ReadableStream({
start(controller) {
controller.enqueue(bytes);
controller.close();
}
});
}
async buffer() {
return Buffer.from(this._bytes);
}
// https://w3c.github.io/FileAPI/#bytes-method-algo
async bytes() {
return this.buffer();
}
// https://w3c.github.io/FileAPI/#arraybuffer-method-algo
async arrayBuffer() {
const buffer = new ArrayBuffer(this._bytes.byteLength);
buffer.set(this._bytes);
return buffer;
}
// https://w3c.github.io/FileAPI/#text-method-algo
async text() {
return this._bytes.toString();
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _Blob },
size: this.size,
type: this.type
};
}
};
exports.Blob = Blob;
function isBlob(value) {
return value instanceof Blob;
}
exports.isBlob = Blob.isBlob = isBlob;
var File = class _File extends Blob {
// https://w3c.github.io/FileAPI/#dom-file-file
constructor(parts, name, options = {}) {
const { lastModified = Date.now() } = options;
super(parts, options);
this._name = name;
this._lastModified = lastModified;
}
// https://w3c.github.io/FileAPI/#dfn-name
get name() {
return this._name;
}
// https://w3c.github.io/FileAPI/#dfn-lastModified
get lastModified() {
return this._lastModified;
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _File },
size: this.size,
type: this.type,
name: this.name,
lastModified: this.lastModified
};
}
};
exports.File = File;
function isFile(value) {
return value instanceof File;
}
exports.isFile = File.isFile = isFile;
function processBlobParts(parts) {
const chunks = [];
for (const part of parts) {
if (typeof part === "string") {
const buffer = Buffer.from(part);
if (parts.length === 1) return buffer;
chunks.push(buffer);
} else if (isBlob(part)) {
chunks.push(part._bytes);
} else if (isBuffer(part)) {
chunks.push(part);
} else if (ArrayBuffer.isView(part)) {
chunks.push(Buffer.from(part.buffer, part.byteOffset, part.byteLength));
} else {
chunks.push(Buffer.from(part));
}
}
return Buffer.concat(chunks);
}
function toBlob(formData, mimeType = "multipart/form-data") {
switch (mimeType) {
case "multipart/form-data":
return toMultipartBlob(formData);
default:
throw errors.INVALID_MIME_TYPE(`Invalid MIME type '${mimeType}'`);
}
}
exports.toBlob = toBlob;
function escape(value) {
return value.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
}
function normalizeLinefeeds(value) {
return value.replace(/\r?\n|\r/g, "\r\n");
}
var linefeed = Buffer.from("\r\n");
function toMultipartBlob(formData) {
const boundary = Math.random().toString(16).slice(2, 18).padStart(16, "0");
const prefix = `--${boundary}\r
Content-Disposition: form-data`;
const parts = [];
for (const [name, value] of formData) {
if (typeof value === "string") {
const chunk = Buffer.from(
prefix + `; name="${escape(normalizeLinefeeds(name))}"\r
\r
${normalizeLinefeeds(value)}\r
`
);
parts.push(chunk);
} else {
const chunk = Buffer.from(
prefix + `; name="${escape(normalizeLinefeeds(name))}"; filename="${escape(value.name)}"\r
Content-Type: ${value.type || "application/octet-stream"}\r
\r
`
);
parts.push(chunk, value, linefeed);
}
}
parts.push(Buffer.from(`--${boundary}--\r
`));
return new Blob(parts, {
type: "multipart/form-data; boundary=" + boundary
});
}
}
});
// ../../node_modules/bare-fetch/lib/errors.js
var require_errors12 = __commonJS({
"../../node_modules/bare-fetch/lib/errors.js"(exports, module) {
module.exports = class FetchError extends Error {
constructor(msg, fn = FetchError, code = fn.name, opts = {}) {
if (typeof code === "object" && code !== null) {
opts = code;
code = fn.name;
}
super(`${code}: ${msg}`, opts);
this.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(this, fn);
}
get name() {
return "FetchError";
}
static INVALID_URL(msg, cause) {
return new FetchError(msg, FetchError.INVALID_URL, { cause });
}
static NETWORK_ERROR(msg, cause) {
return new FetchError(msg, FetchError.NETWORK_ERROR, { cause });
}
static TOO_MANY_REDIRECTS(msg) {
return new FetchError(msg, FetchError.TOO_MANY_REDIRECTS);
}
static UNKNOWN_PROTOCOL(msg) {
return new FetchError(msg, FetchError.UNKNOWN_PROTOCOL);
}
static BODY_UNUSABLE(msg) {
return new FetchError(msg, FetchError.BODY_UNUSABLE);
}
};
}
});
// ../../node_modules/bare-fetch/lib/body.js
var require_body = __commonJS({
"../../node_modules/bare-fetch/lib/body.js"(exports, module) {
var { ReadableStream, isReadableStream, isReadableStreamDisturbed } = require_web2();
var { isURLSearchParams } = require_bare_url();
var { FormData, isFormData, isBlob } = require_bare_form_data();
var errors = require_errors12();
var empty = Buffer.from(new ArrayBuffer(0));
module.exports = exports = class Body {
constructor(body = null, type = null) {
if (isReadableStream(body)) {
if (isReadableStreamDisturbed(body) || body.locked) {
throw errors.BODY_UNUSABLE("Body has already been consumed");
}
} else {
if (typeof body === "string") body = Buffer.from(body);
else if (isFormData(body)) body = FormData.toBlob(body);
else if (isURLSearchParams(body)) {
body = body.toString();
type = "application/x-www-form-urlencoded;charset=UTF-8";
}
if (isBlob(body)) {
type = body.type || null;
body = body.stream();
} else if (body !== null) {
if (ArrayBuffer.isView(body)) {
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
} else {
body = Buffer.from(body);
}
body = new ReadableStream({
start(controller) {
controller.enqueue(body);
controller.close();
}
});
}
}
this._type = type;
this._body = body;
}
// https://fetch.spec.whatwg.org/#dom-body-body
get body() {
return this._body;
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
get bodyUsed() {
return this._body !== null && isReadableStreamDisturbed(this._body);
}
async buffer() {
if (this._body === null) return empty;
if (Body.isUnusable(this)) {
throw errors.BODY_UNUSABLE("Body has already been consumed");
}
const chunks = [];
let length = 0;
for await (const chunk of this._body) {
chunks.push(chunk);
length += chunk.byteLength;
}
const result = Buffer.from(new ArrayBuffer(length));
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.byteLength;
}
return result;
}
// https://fetch.spec.whatwg.org/#dom-body-bytes
async bytes() {
return this.buffer();
}
// https://fetch.spec.whatwg.org/#dom-body-arraybuffer
async arrayBuffer() {
return (await this.buffer()).buffer;
}
// https://fetch.spec.whatwg.org/#dom-body-text
async text() {
return (await this.buffer()).toString();
}
// https://fetch.spec.whatwg.org/#dom-body-json
async json() {
return JSON.parse(await this.text());
}
};
exports.isUnusable = function isUsable(body) {
return body._body !== null && (isReadableStreamDisturbed(body._body) || body._body.locked);
};
exports.clone = function clone(body) {
if (body._body === null) return null;
const [out1, out2] = body._body.tee();
body._body = out1;
return out2;
};
}
});
// ../../node_modules/bare-fetch/lib/headers.js
var require_headers = __commonJS({
"../../node_modules/bare-fetch/lib/headers.js"(exports, module) {
module.exports = class Headers {
// https://fetch.spec.whatwg.org/#dom-headers
constructor(init) {
this._headers = /* @__PURE__ */ new Map();
if (init) {
for (const [key, value] of typeof init[Symbol.iterator] === "function" ? init : Object.entries(init)) {
this.append(key, value);
}
}
}
// https://fetch.spec.whatwg.org/#dom-headers-append
append(name, value) {
name = name.toLowerCase();
value = value.trim();
let list = this._headers.get(name);
if (list === void 0) {
list = [];
this._headers.set(name, list);
}
list.push(value);
}
// https://fetch.spec.whatwg.org/#dom-headers-delete
delete(name) {
name = name.toLowerCase();
this._headers.delete(name);
}
// https://fetch.spec.whatwg.org/#dom-headers-get
get(name) {
name = name.toLowerCase();
const list = this._headers.get(name);
if (list === void 0) return null;
return list.join(", ");
}
// https://fetch.spec.whatwg.org/#dom-headers-has
has(name) {
name = name.toLowerCase();
return this._headers.has(name);
}
// https://fetch.spec.whatwg.org/#dom-headers-set
set(name, value) {
name = name.toLowerCase();
value = value.trim();
this._headers.set(name, [value]);
}
// https://webidl.spec.whatwg.org/#idl-iterable
entries() {
return this[Symbol.iterator]();
}
// https://webidl.spec.whatwg.org/#idl-iterable
*keys() {
for (const [name] of this) {
yield name;
}
}
// https://webidl.spec.whatwg.org/#idl-iterable
*values() {
for (const [, value] of this) {
yield value;
}
}
// https://webidl.spec.whatwg.org/#idl-iterable
forEach(callback, thisArg) {
for (const [name, value] of this) {
callback.call(thisArg, value, name, this);
}
}
*[Symbol.iterator]() {
const names = [...this._headers.keys()].sort();
for (const name of names) {
yield [name, this.get(name)];
}
}
};
}
});
// ../../node_modules/bare-fetch/lib/request.js
var require_request = __commonJS({
"../../node_modules/bare-fetch/lib/request.js"(exports, module) {
var { isURL } = require_bare_url();
var Body = require_body();
var Headers = require_headers();
var errors = require_errors12();
module.exports = class Request extends Body {
// https://fetch.spec.whatwg.org/#dom-request
constructor(input, init = {}) {
let url;
try {
if (isURL(input)) {
url = input;
input = {};
} else if (typeof input === "string") {
url = new URL(input);
input = {};
} else {
url = new URL(input.url);
}
} catch (err) {
throw errors.INVALID_URL("Invalid URL", err);
}
const {
body = input.body || null,
method = input.method || "GET",
headers = input.headers,
signal = null,
agent = input.agent || null
} = init;
super(body);
this._url = url;
this._method = /^(delete|get|head|options|post|put)$/i.test(method) ? method.toUpperCase() : method;
this._headers = new Headers(headers);
this._signal = signal;
this._agent = agent;
}
// https://fetch.spec.whatwg.org/#dom-request-url
get url() {
return this._url.href;
}
// https://fetch.spec.whatwg.org/#dom-request-method
get method() {
return this._method;
}
// https://fetch.spec.whatwg.org/#dom-request-headers
get headers() {
return this._headers;
}
// https://fetch.spec.whatwg.org/#dom-request-signal
get signal() {
return this._signal;
}
// https://fetch.spec.whatwg.org/#dom-request-clone
clone() {
if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE("Body has already been consumed");
return new Request(this, { body: Body.clone(this) });
}
};
}
});
// ../../node_modules/bare-fetch/lib/response.js
var require_response = __commonJS({
"../../node_modules/bare-fetch/lib/response.js"(exports, module) {
var Body = require_body();
var Headers = require_headers();
var errors = require_errors12();
module.exports = class Response extends Body {
// https://fetch.spec.whatwg.org/#dom-response
constructor(body = null, init = {}) {
const { status = 200, statusText = "", headers } = init;
super(body);
this._urls = [];
this._status = status;
this._statusText = statusText;
this._headers = new Headers(headers);
}
// https://fetch.spec.whatwg.org/#dom-response-url
get url() {
return this._urls.length === 0 ? null : this._urls[this._urls.length - 1].href;
}
// https://fetch.spec.whatwg.org/#dom-response-redirected
get redirected() {
return this._urls.length > 1;
}
// https://fetch.spec.whatwg.org/#dom-response-status
get status() {
return this._status;
}
// https://fetch.spec.whatwg.org/#dom-response-ok
get ok() {
return this._status >= 200 && this._status <= 299;
}
// https://fetch.spec.whatwg.org/#dom-response-statustext
get statusText() {
return this._statusText;
}
// https://fetch.spec.whatwg.org/#dom-response-headers
get headers() {
return this._headers;
}
// https://fetch.spec.whatwg.org/#dom-response-clone
clone() {
if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE("Body has already been consumed");
return new Response(Body.clone(this), this);
}
};
}
});
// ../../node_modules/bare-zlib/binding.js
var require_binding11 = __commonJS({
"../../node_modules/bare-zlib/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-zlib/lib/constants.js
var require_constants10 = __commonJS({
"../../node_modules/bare-zlib/lib/constants.js"(exports, module) {
var binding = require_binding11();
module.exports = binding.constants;
}
});
// ../../node_modules/bare-zlib/lib/errors.js
var require_errors13 = __commonJS({
"../../node_modules/bare-zlib/lib/errors.js"(exports, module) {
module.exports = class ZlibError extends Error {
constructor(msg, code, fn = ZlibError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "ZlibError";
}
static STREAM_CLOSED(msg) {
return new ZlibError(msg, "STREAM_CLOSED", ZlibError.STREAM_CLOSED);
}
static STREAM_ERROR(msg) {
return new ZlibError(msg, "STREAM_ERROR", ZlibError.STREAM_ERROR);
}
static DATA_ERROR(msg) {
return new ZlibError(msg, "DATA_ERROR", ZlibError.DATA_ERROR);
}
static MEM_ERROR(msg) {
return new ZlibError(msg, "MEM_ERROR", ZlibError.MEM_ERROR);
}
static BUF_ERROR(msg) {
return new ZlibError(msg, "BUF_ERROR", ZlibError.BUF_ERROR);
}
static VERSION_ERROR(msg) {
return new ZlibError(msg, "VERSION_ERROR", ZlibError.VERSION_ERROR);
}
static UNKNOWN_ERROR(msg) {
return new ZlibError(msg, "UNKNOWN_ERROR", ZlibError.UNKNOWN_ERROR);
}
};
}
});
// ../../node_modules/bare-zlib/index.js
var require_bare_zlib = __commonJS({
"../../node_modules/bare-zlib/index.js"(exports) {
var { Transform, Writable } = require_bare_stream();
var binding = require_binding11();
var constants = require_constants10();
var errors = require_errors13();
exports.constants = constants;
exports.errors = errors;
var ZlibState = class {
constructor(mode, opts = {}) {
const {
flush = constants.Z_NO_FLUSH,
finishFlush = constants.Z_FINISH,
chunkSize = constants.Z_DEFAULT_CHUNK,
level = constants.Z_DEFAULT_LEVEL,
windowBits = constants.Z_DEFAULT_WINDOWBITS,
memLevel = constants.Z_DEFAULT_MEMLEVEL,
strategy = constants.Z_DEFAULT_STRATEGY
} = opts;
this._mode = mode;
this._flushMode = flush;
this._finishFlushMode = finishFlush;
this._allocations = [];
this._buffer = Buffer.allocUnsafe(chunkSize);
this._handle = binding.init(
this._mode,
this._buffer,
level,
windowBits,
memLevel,
strategy,
this,
this._onalloc,
this._onfree
);
}
_onalloc(size) {
const buffer = Buffer.allocUnsafe(size);
const view = new Uint32Array(
buffer.buffer,
buffer.byteOffset,
buffer.byteLength / 4
);
view[0] = this._allocations.push(view) - 1;
return buffer;
}
_onfree(id) {
const last = this._allocations.pop();
if (last[0] !== id) {
this._allocations[last[0] = id] = last;
}
}
reset() {
binding.reset(this._handle);
}
*transform(data) {
binding.load(this._handle, data);
let available;
do {
try {
available = binding.transform(this._handle, this._flushMode);
} catch (err) {
throw errors[err.code](err.message);
}
const read = this._buffer.length - available;
if (read) {
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
yield copy;
}
} while (available === 0);
}
*flush() {
let available;
try {
available = binding.transform(this._handle, this._finishFlushMode);
} catch (err) {
throw errors[err.code](err.message);
}
const read = this._buffer.length - available;
if (read) yield this._buffer.subarray(0, read);
try {
binding.end(this._handle);
} catch (err) {
throw errors[err.code](err.message);
}
this._handle = null;
}
};
var ZlibStream = class extends Transform {
constructor(mode, opts = {}) {
super();
this._state = new ZlibState(mode, opts);
}
async flush(mode = constants.Z_FULL_FLUSH, cb) {
if (typeof mode === "function") {
cb = mode;
mode = constants.Z_FULL_FLUSH;
}
const previousMode = this._state._flushMode;
this._state._flushMode = mode;
await Writable.drained(this);
this._state._flushMode = previousMode;
if (cb) cb(null);
}
reset() {
if (this._state === null) {
throw errors.STREAM_CLOSED("Stream has already closed");
}
this._state.flush();
}
_transform(data, encoding, cb) {
let err = null;
try {
for (const chunk of this._state.transform(data)) {
this.push(chunk);
}
} catch (e) {
err = e;
}
cb(err);
}
_flush(cb) {
let err = null;
try {
for (const chunk of this._state.flush()) {
this.push(chunk);
}
} catch (e) {
err = e;
}
this._state = null;
cb(err);
}
};
function readAsBuffer(stream, buffer, cb) {
const chunks = [];
stream.on("data", ondata).on("end", onend).on("error", onerror).end(buffer);
function ondata(chunk) {
chunks.push(chunk);
}
function onend() {
cb(null, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
}
function onerror(err) {
stream.off("end", onend);
cb(err);
}
}
function transformToBuffer(mode, buffer, opts) {
if (typeof buffer === "string") buffer = Buffer.from(buffer);
const state = new ZlibState(mode, opts);
const chunks = [];
for (const chunk of state.transform(buffer)) {
chunks.push(chunk);
}
for (const chunk of state.flush()) {
chunks.push(chunk);
}
return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
}
exports.Deflate = class ZlibDeflateStream extends ZlibStream {
constructor(opts) {
super(binding.DEFLATE, opts);
}
};
exports.createDeflate = function createDeflate(opts) {
return new exports.Deflate(opts);
};
exports.deflate = function deflate(buffer, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
readAsBuffer(new exports.Deflate(opts), buffer, cb);
};
exports.deflateSync = function deflateSync(buffer, opts) {
return transformToBuffer(binding.DEFLATE, buffer, opts);
};
exports.Inflate = class ZlibInflateStream extends ZlibStream {
constructor(opts) {
super(binding.INFLATE, opts);
}
};
exports.createInflate = function createInflate(opts) {
return new exports.Inflate(opts);
};
exports.inflate = function inflate(buffer, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
readAsBuffer(new exports.Inflate(opts), buffer, cb);
};
exports.inflateSync = function inflateSync(buffer, opts) {
return transformToBuffer(binding.INFLATE, buffer, opts);
};
exports.DeflateRaw = class ZlibDeflateRawStream extends ZlibStream {
constructor(opts) {
super(binding.DEFLATE_RAW, opts);
}
};
exports.createDeflateRaw = function createDeflateRaw(opts) {
return new exports.DeflateRaw(opts);
};
exports.deflateRaw = function deflateRaw(buffer, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
readAsBuffer(new exports.DeflateRaw(opts), buffer, cb);
};
exports.deflateRawSync = function deflateRawSync(buffer, opts) {
return transformToBuffer(binding.DEFLATE_RAW, buffer, opts);
};
exports.InflateRaw = class ZlibInflateRawStream extends ZlibStream {
constructor(opts) {
super(binding.INFLATE_RAW, opts);
}
};
exports.createInflateRaw = function createInflateRaw(opts) {
return new exports.InflateRaw(opts);
};
exports.inflateRaw = function inflateRaw(buffer, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
readAsBuffer(new exports.InflateRaw(opts), buffer, cb);
};
exports.inflateRawSync = function inflateRawSync(buffer, opts) {
return transformToBuffer(binding.INFLATE_RAW, buffer, opts);
};
exports.Gzip = class ZlibGzipStream extends ZlibStream {
constructor(opts) {
super(binding.GZIP, opts);
}
};
exports.createGzip = function createGzip(opts) {
return new exports.Gzip(opts);
};
exports.gzip = function gzip(buffer, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
readAsBuffer(new exports.Gzip(opts), buffer, cb);
};
exports.gzipSync = function gzipSync(buffer, opts) {
return transformToBuffer(binding.GZIP, buffer, opts);
};
exports.Gunzip = class ZlibGunzipStream extends ZlibStream {
constructor(opts) {
super(binding.GUNZIP, opts);
}
};
exports.createGunzip = function createGunzip(opts) {
return new exports.Gunzip(opts);
};
exports.gunzip = function gunzip(buffer, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
readAsBuffer(new exports.Gunzip(opts), buffer, cb);
};
exports.gunzipSync = function gunzipSync(buffer, opts) {
return transformToBuffer(binding.GUNZIP, buffer, opts);
};
}
});
// ../../node_modules/bare-fetch/lib/response-stream.js
var require_response_stream = __commonJS({
"../../node_modules/bare-fetch/lib/response-stream.js"(exports, module) {
var { Readable } = require_bare_stream();
var { Gunzip, Deflate } = require_bare_zlib();
module.exports = class ResponseStream extends Readable {
constructor(response) {
super();
this._response = response;
this._response.socket.unref();
const encoding = response.headers["content-encoding"];
switch (encoding) {
case "gzip":
this._decoder = new Gunzip();
break;
case "deflate":
this._decoder = new Deflate();
break;
default:
this._decoder = null;
}
}
_open(cb) {
if (this._response.socket) this._response.socket.ref();
const stream = this._decoder ? this._response.pipe(this._decoder) : this._response;
stream.on("data", this._ondata.bind(this)).on("end", this._onend.bind(this)).on("error", this._onerror.bind(this));
cb(null);
}
_read() {
this._response.resume();
}
_predestroy() {
this._response.destroy();
}
_ondata(data) {
if (this.push(data) === false) {
this._response.pause();
}
}
_onend() {
this.push(null);
}
_onerror(err) {
this.destroy(err);
}
};
}
});
// ../../node_modules/bare-fetch/index.js
var require_bare_fetch = __commonJS({
"../../node_modules/bare-fetch/index.js"(exports, module) {
var http = require_bare_http1();
var https = require_bare_https();
var { ReadableStream } = require_web2();
var Request = require_request();
var Response = require_response();
var ResponseStream = require_response_stream();
var Headers = require_headers();
var errors = require_errors12();
module.exports = exports = function fetch(input, init = {}) {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const response = new Response();
process(input);
return promise;
async function process(input2, origin = null) {
let request;
try {
request = new Request(input2, init);
} catch (err) {
return reject(err);
}
if (request.signal) {
if (request.signal.aborted) return abort(reject, request, response);
request.signal.addEventListener("abort", (event) => abort(reject, request, response));
}
if (response._urls.length > 20) {
return reject(errors.TOO_MANY_REDIRECTS("Redirect count exceeded"));
}
if (origin && !isSameOrigin(request._url, origin)) {
request.headers.delete("authorization");
}
let protocol;
if (request._url.protocol === "http:") {
protocol = http;
} else if (request._url.protocol === "https:") {
protocol = https;
} else {
return reject(errors.UNKNOWN_PROTOCOL(`Unknown protocol '${request._url.protocol}'`));
}
response._urls.push(request._url);
if (!request._headers.has("user-agent")) {
request._headers.set("user-agent", `Bare/${Bare.version.substring(1)}`);
}
if (!request._headers.has("content-type") && request._type) {
request._headers.set("content-type", request._type);
}
const agent = request._agent || protocol.globalAgent;
while (agent.suspended) await agent.resumed;
const req = protocol.request(
request._url,
{
agent,
method: request._method,
headers: Object.fromEntries(request._headers)
},
(res) => {
if (request.signal && request.signal.aborted) {
res.resume();
return abort(reject, request, response);
}
if (res.headers.location && isRedirectStatus(res.statusCode)) {
res.resume();
let url;
try {
url = new URL(res.headers.location, request._url);
} catch (err) {
return reject(errors.INVALID_URL("Invalid URL", err));
}
return process(url, request._url);
}
response._body = new ReadableStream(new ResponseStream(res));
response._status = res.statusCode;
response._statusText = res.statusMessage;
for (const [name, value] of Object.entries(res.headers)) {
response._headers.set(name, value);
}
resolve(response);
}
);
req.on("error", (err) => reject(errors.NETWORK_ERROR("Network error", err)));
try {
if (request._body) {
for await (const data of request._body) req.write(data);
}
req.end();
} catch (err) {
req.destroy(err);
}
}
};
exports.Request = Request;
exports.Response = Response;
exports.Headers = Headers;
function isRedirectStatus(status) {
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
}
function isSameOrigin(a, b) {
return a.protocol === b.protocol && a.host === b.host;
}
function abort(reject, req, res) {
const { reason } = req.signal;
if (req._body !== null) req._body.cancel(reason);
if (res._body !== null) res._body.cancel(reason);
reject(reason);
}
}
});
// ../../node_modules/bare-fetch/global.js
var require_global5 = __commonJS({
"../../node_modules/bare-fetch/global.js"() {
var fetch = require_bare_fetch();
global.fetch = fetch;
global.Request = fetch.Request;
global.Response = fetch.Response;
global.Headers = fetch.Headers;
}
});
// ../../node_modules/bare-node-runtime/node_modules/bare-performance/lib/constants.js
var require_constants11 = __commonJS({
"../../node_modules/bare-node-runtime/node_modules/bare-performance/lib/constants.js"(exports, module) {
module.exports = {
observerType: {
UNDEFINED: 1,
SINGLE: 2,
MULTIPLE: 3
}
};
}
});
// ../../node_modules/bare-node-runtime/node_modules/bare-performance/lib/errors.js
var require_errors14 = __commonJS({
"../../node_modules/bare-node-runtime/node_modules/bare-performance/lib/errors.js"(exports) {
var InvalidModificationError = class extends Error {
get name() {
return "InvalidModificationError";
}
};
exports.InvalidModificationError = InvalidModificationError;
}
});
// ../../node_modules/bare-node-runtime/node_modules/bare-performance/binding.js
var require_binding12 = __commonJS({
"../../node_modules/bare-node-runtime/node_modules/bare-performance/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-node-runtime/node_modules/bare-performance/index.js
var require_bare_performance = __commonJS({
"../../node_modules/bare-node-runtime/node_modules/bare-performance/index.js"(exports) {
var { observerType } = require_constants11();
var { InvalidModificationError } = require_errors14();
var binding = require_binding12();
var { TIME_ORIGIN } = binding;
exports.now = function now() {
return binding.now() / 1e6 - TIME_ORIGIN;
};
exports.eventLoopUtilization = function eventLoopUtilization(prevUtil, secUtil) {
if (secUtil) {
const idle2 = prevUtil.idle - secUtil.idle;
const active2 = prevUtil.active - secUtil.active;
return { idle: idle2, active: active2, utilization: active2 / (idle2 + active2) };
}
let idle = exports.idleTime();
if (idle === 0) return { idle: 0, active: 0, utilization: 0 };
let active = exports.now() - idle;
if (!prevUtil) return { idle, active, utilization: active / (idle + active) };
idle = idle - prevUtil.idle;
active = active - prevUtil.active;
return { idle, active, utilization: active / (idle + active) };
};
exports.idleTime = function idleTime() {
return binding.idleTime();
};
exports.metricsInfo = function metricsInfo() {
return binding.metricsInfo();
};
exports.timeOrigin = TIME_ORIGIN;
exports.performance = exports;
var PerformanceNodeTiming = class {
get idleTime() {
return exports.idleTime();
}
get uvMetricsInfo() {
return exports.metricsInfo();
}
};
exports.nodeTiming = new PerformanceNodeTiming();
var globalObservers = /* @__PURE__ */ new Set();
var globalPendingObservers = /* @__PURE__ */ new Set();
var globalBuffer = [];
var pending = false;
var PerformanceEntry = class {
constructor(name, type, start, duration) {
this._name = name;
this._type = type;
this._start = start;
this._duration = duration;
}
get name() {
return this._name;
}
get entryType() {
return this._type;
}
get startTime() {
return this._start;
}
get duration() {
return this._duration;
}
};
exports.PerformanceEntry = PerformanceEntry;
var PerformanceMark = class extends PerformanceEntry {
constructor(name, opts = {}) {
const { startTime = exports.now(), detail = null } = opts;
super(name, "mark", startTime, 0);
this._detail = detail;
}
get detail() {
return this._detail;
}
};
exports.PerformanceMark = PerformanceMark;
var PerformanceMeasure = class extends PerformanceEntry {
constructor(name, startTime, duration, opts = {}) {
const { detail = null } = opts;
super(name, "measure", startTime, duration);
this._detail = detail;
}
get detail() {
return this._detail;
}
};
exports.PerformanceMeasure = PerformanceMeasure;
var PerformanceObserverEntryList = class {
constructor(entryList) {
this._list = entryList;
}
getEntries() {
return this._list;
}
getEntriesByType(type) {
return this._list.filter((entry) => entry.entryType === type);
}
getEntriesByName(name) {
return this._list.filter((entry) => entry.name === name);
}
};
exports.PerformanceObserverEntryList = PerformanceObserverEntryList;
var PerformanceObserver = class _PerformanceObserver {
constructor(cb) {
this._entryTypes = /* @__PURE__ */ new Set();
this._type = observerType.UNDEFINED;
this._buffer = [];
this._cb = cb;
}
static get supportedEntryTypes() {
return ["mark", "measure"];
}
observe(opts = {}) {
if (!opts.entryTypes && !opts.type || opts.entryTypes && opts.type) {
throw new TypeError("opts.entryTypes OR opts.type must be specified");
}
if (this._type === observerType.MULTIPLE && opts.type || this._type === observerType.SINGLE && opts.entryTypes) {
throw new InvalidModificationError("Cannot change the PerformanceObserver type");
}
if (this._type === observerType.UNDEFINED) {
this._type = opts.entryTypes ? observerType.MULTIPLE : observerType.SINGLE;
}
this._entryTypes.clear();
if (this._type === observerType.MULTIPLE) {
for (const entryType of opts.entryTypes) {
if (_PerformanceObserver.supportedEntryTypes.includes(entryType)) {
this._entryTypes.add(entryType);
}
}
} else {
if (_PerformanceObserver.supportedEntryTypes.includes(opts.type)) {
this._entryTypes.add(opts.type);
if (opts.buffered === true) {
const bufferedEntries = globalBuffer.filter((entry) => entry.entryType === opts.type);
if (bufferedEntries.length > 0) {
this._buffer.push(...bufferedEntries);
globalPendingObservers.add(this);
processPendingObservers();
}
}
}
}
if (this._entryTypes.size > 0) {
globalObservers.add(this);
} else {
this.disconnect();
}
}
takeRecords() {
const buf = this._buffer;
this._buffer = [];
return buf;
}
disconnect() {
globalObservers.delete(this);
this._entryTypes.clear();
this._type = observerType.UNDEFINED;
}
};
exports.PerformanceObserver = PerformanceObserver;
exports.mark = function mark(name, opts) {
const mark2 = new PerformanceMark(name, opts);
processEntry(mark2);
globalBuffer.push(mark2);
return mark2;
};
exports.clearMarks = function clearMarks(name) {
if (name) {
globalBuffer = globalBuffer.filter((entry) => entry.name !== name && entry.entryType !== "mark");
} else {
globalBuffer = globalBuffer.filter((entry) => entry.entryType !== "mark");
}
};
exports.measure = function measure(name, start, end) {
let opts = {};
if (typeof start === "object" && start !== null && Object.keys(start).length > 0) {
opts = start;
if (!opts.start && !opts.end) {
throw new TypeError("opts.start or opts.end must be specified");
}
if (opts.name && opts.end && opts.duration) {
throw new TypeError("One of opts.name, opts.end or opts.duration must not be specified");
}
start = opts.start;
end = opts.end;
}
let endTime;
if (end) {
endTime = toTimestamp(end);
} else if (start && opts.duration) {
endTime = toTimestamp(start) + toTimestamp(duration);
} else {
endTime = exports.now();
}
let startTime;
if (start) {
startTime = toTimestamp(start);
} else if (end && opts.duration) {
startTime = toTimestamp(end) - toTimestamp(duration);
} else {
startTime = 0;
}
const duration = endTime - startTime;
const measure2 = new PerformanceMeasure(name, startTime, duration, opts);
processEntry(measure2);
globalBuffer.push(measure2);
return measure2;
};
exports.clearMeasures = function clearMeasures(name) {
if (name) {
globalBuffer = globalBuffer.filter(
(entry) => entry.name !== name && entry.entryType !== "measure"
);
} else {
globalBuffer = globalBuffer.filter((entry) => entry.entryType !== "measure");
}
};
exports.getEntries = function getEntries() {
return new PerformanceObserverEntryList(globalBuffer).getEntries();
};
exports.getEntriesByName = function getEntriesByName(name) {
return new PerformanceObserverEntryList(globalBuffer).getEntriesByName(name);
};
exports.getEntriesByType = function getEntriesByType(type) {
return new PerformanceObserverEntryList(globalBuffer).getEntriesByType(type);
};
function processEntry(entry) {
for (const observer of globalObservers) {
if (observer._entryTypes.has(entry.entryType)) {
observer._buffer.push(entry);
globalPendingObservers.add(observer);
processPendingObservers();
}
}
}
function processPendingObservers() {
if (pending) return;
pending = true;
setImmediate(() => {
pending = false;
const observers = Array.from(globalPendingObservers.values());
globalPendingObservers.clear();
for (const observer of observers) {
observer._cb(new exports.PerformanceObserverEntryList(observer.takeRecords()), observer);
}
});
}
function toTimestamp(mark) {
if (typeof mark === "string") {
const performanceMark = globalBuffer.findLast(
(entry) => entry.name === mark && entry.entryType === "mark"
);
if (performanceMark === void 0) {
throw new SyntaxError(`Mark ${mark} not found`);
}
return performanceMark.startTime;
} else if (typeof mark === "number") {
return mark;
}
}
var Histogram = class {
constructor(opts = {}) {
const { lowest = 1, highest = Number.MAX_SAFE_INTEGER, figures = 3 } = opts;
this._handle = binding.histogramInit(this, lowest, highest, figures);
this._count = 0;
this._exceeds = 0;
}
get max() {
return binding.histogramMax(this._handle);
}
get min() {
return binding.histogramMin(this._handle);
}
get mean() {
return binding.histogramMean(this._handle);
}
get percentiles() {
return new Map(binding.histogramPercentiles(this._handle));
}
get stddev() {
return binding.histogramStddev(this._handle);
}
get count() {
return this._count;
}
get exceeds() {
return this._exceeds;
}
percentile(percentile) {
return binding.histogramPercentile(this._handle, percentile);
}
reset() {
this._count = 0;
this._exceeds = 0;
binding.histogramReset(this._handle);
}
};
var RecordableHistogram = class extends Histogram {
add(other) {
this._count += other._count;
this._exceeds += other._exceeds;
binding.histogramAdd(this._handle, other._handle);
}
record(value) {
if (binding.histogramRecord(this._handle, value)) this._count++;
else this._exceeds++;
}
};
exports.createHistogram = function createHistogram(opts) {
return new RecordableHistogram(opts);
};
var IntervalHistogram = class extends Histogram {
constructor(opts = {}) {
const { resolution = 10 } = opts;
super({
lowest: 1,
highest: 36e11
// One hour in nanoseconds
});
this._resolution = resolution;
this._enabled = false;
this._timerId = -1;
this._timerStartTime = -1;
}
enable() {
if (this._enabled === true) return false;
this._timerStartTime = binding.now();
this._timerId = setInterval(this._oninterval.bind(this), this._resolution);
this._enabled = true;
return true;
}
disable() {
if (this._enabled === false) return false;
clearInterval(this._timerId);
this._enabled = false;
return true;
}
_oninterval() {
const now = binding.now();
const actual = now - this._timerStartTime;
const expected = this._resolution * 1e6;
const hasDelay = actual > expected;
if (hasDelay) {
const delay = actual - expected;
if (binding.histogramRecord(this._handle, delay)) this._count++;
else this._exceeds++;
}
this._timerStartTime = now;
}
[Symbol.dispose]() {
this.disable();
}
};
exports.monitorEventLoopDelay = function monitorEventLoopDelay(opts) {
return new IntervalHistogram(opts);
};
}
});
// ../../node_modules/bare-node-runtime/node_modules/bare-performance/global.js
var require_global6 = __commonJS({
"../../node_modules/bare-node-runtime/node_modules/bare-performance/global.js"() {
var performance = require_bare_performance();
global.performance = performance;
global.PerformanceEntry = performance.PerformanceEntry;
global.PerformanceMark = performance.PerformanceMark;
global.PerformanceMeasure = performance.PerformanceMeasure;
global.PerformanceObserver = performance.PerformanceObserver;
global.PerformanceObserverEntryList = performance.PerformanceObserverEntryList;
}
});
// ../../node_modules/bare-abort/binding.js
var require_binding13 = __commonJS({
"../../node_modules/bare-abort/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-abort/index.js
var require_bare_abort = __commonJS({
"../../node_modules/bare-abort/index.js"(exports, module) {
var binding = require_binding13();
module.exports = binding.abort;
}
});
// ../../node_modules/bare-signals/binding.js
var require_binding14 = __commonJS({
"../../node_modules/bare-signals/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-signals/lib/errors.js
var require_errors15 = __commonJS({
"../../node_modules/bare-signals/lib/errors.js"(exports, module) {
module.exports = class SignalError extends Error {
constructor(msg, fn = SignalError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "SignalError";
}
static UNKNOWN_SIGNAL(msg) {
return new SignalError(msg, SignalError.UNKNOWN_SIGNAL);
}
static SIGNAL_CLOSED(msg) {
return new SignalError(msg, SignalError.SIGNAL_CLOSED);
}
};
}
});
// ../../node_modules/bare-signals/lib/emitter.js
var require_emitter = __commonJS({
"../../node_modules/bare-signals/lib/emitter.js"(exports, module) {
var EventEmitter = require_bare_events();
var Signal = require_bare_signals();
module.exports = class SignalEmitter extends EventEmitter {
constructor() {
super();
this._signals = /* @__PURE__ */ new Map();
this._unrefed = false;
this.on("newListener", this._onnewlistener).on(
"removeListener",
this._onremovelistener
);
}
ref() {
this._unrefed = false;
for (const signal of this._signals.values()) signal.ref();
return this;
}
unref() {
this._unrefed = true;
for (const signal of this._signals.values()) signal.unref();
return this;
}
_onnewlistener(name) {
if (name === "newListener" || name === "removeListener") return;
if (this.listenerCount(name) === 0) {
const signal = new Signal(name);
signal.on("signal", this._onsignal.bind(this, name)).start();
if (this._unrefed) signal.unref();
this._signals.set(name, signal);
}
}
_onremovelistener(name) {
if (name === "newListener" || name === "removeListener") return;
if (this.listenerCount(name) === 0) {
const signal = this._signals.get(name);
if (this._unrefed) signal.ref();
signal.close();
this._signals.delete(name);
}
}
_onsignal(name) {
this.emit(name, name, Signal.constants[name]);
}
};
}
});
// ../../node_modules/bare-signals/index.js
var require_bare_signals = __commonJS({
"../../node_modules/bare-signals/index.js"(exports, module) {
var EventEmitter = require_bare_events();
var os = require_bare_os();
var binding = require_binding14();
var errors = require_errors15();
var signals = os.constants.signals;
module.exports = exports = class Signal extends EventEmitter {
constructor(signum) {
super();
if (typeof signum === "string") {
if (signum in signals === false) {
throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`);
}
signum = signals[signum];
}
this._signum = signum;
this._closing = null;
this._handle = binding.init(this, this._onsignal, this._onclose);
}
start() {
if (this._closing) throw errors.SIGNAL_CLOSED("Signal is closed");
binding.start(this._handle, this._signum);
return this;
}
stop() {
if (this._closing) return this;
binding.stop(this._handle);
return this;
}
ref() {
if (this._closing) return this;
binding.ref(this._handle);
return this;
}
unref() {
if (this._closing) return this;
binding.unref(this._handle);
return this;
}
close() {
if (this._closing) return this._closing;
this._closing = EventEmitter.once(this, "close");
binding.close(this._handle);
return this._closing;
}
_onsignal() {
this.emit("signal", this._signum);
}
_onclose() {
this._handle = null;
this.emit("close");
}
static send(signum, pid = os.pid()) {
os.kill(pid, signum);
}
};
exports.Emitter = require_emitter();
exports.constants = signals;
exports.errors = errors;
}
});
// ../../node_modules/bare-env/index.js
var require_bare_env = __commonJS({
"../../node_modules/bare-env/index.js"(exports, module) {
var os = require_bare_os();
module.exports = new Proxy(/* @__PURE__ */ Object.create(null), {
ownKeys(target) {
return os.getEnvKeys();
},
get(target, property) {
if (typeof property !== "string") return;
return os.getEnv(property);
},
has(target, property) {
if (typeof property !== "string") return false;
return os.hasEnv(property);
},
set(target, property, value) {
if (typeof property !== "string") return;
const type = typeof value;
if (type !== "string" && type !== "number" && type !== "boolean") {
throw new Error("Environment variable must be of type string, number, or boolean");
}
value = String(value);
os.setEnv(property, value);
return true;
},
deleteProperty(target, property) {
if (typeof property !== "string") return;
os.unsetEnv(property);
},
getOwnPropertyDescriptor(target, property) {
return {
value: this.get(target, property),
enumerable: true,
configurable: true,
writable: true
};
}
});
}
});
// ../../node_modules/bare-hrtime/binding.js
var require_binding15 = __commonJS({
"../../node_modules/bare-hrtime/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-hrtime/index.js
var require_bare_hrtime = __commonJS({
"../../node_modules/bare-hrtime/index.js"(exports, module) {
var binding = require_binding15();
module.exports = exports = function hrtime(past) {
let now = binding.hrtime();
if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1]);
return [Number(now / 1000000000n), Number(now % 1000000000n)];
};
exports.bigint = function hrtime() {
return binding.hrtime();
};
}
});
// ../../node_modules/bare-fs/binding.js
var require_binding16 = __commonJS({
"../../node_modules/bare-fs/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-fs/lib/constants.js
var require_constants12 = __commonJS({
"../../node_modules/bare-fs/lib/constants.js"(exports, module) {
var binding = require_binding16();
module.exports = {
O_RDWR: binding.O_RDWR,
O_RDONLY: binding.O_RDONLY,
O_WRONLY: binding.O_WRONLY,
O_CREAT: binding.O_CREAT,
O_TRUNC: binding.O_TRUNC,
O_APPEND: binding.O_APPEND,
F_OK: binding.F_OK || 0,
R_OK: binding.R_OK || 0,
W_OK: binding.W_OK || 0,
X_OK: binding.X_OK || 0,
S_IFMT: binding.S_IFMT,
S_IFREG: binding.S_IFREG,
S_IFDIR: binding.S_IFDIR,
S_IFCHR: binding.S_IFCHR,
S_IFLNK: binding.S_IFLNK,
S_IFBLK: binding.S_IFBLK || 0,
S_IFIFO: binding.S_IFIFO || 0,
S_IFSOCK: binding.S_IFSOCK || 0,
S_IRUSR: binding.S_IRUSR || 0,
S_IWUSR: binding.S_IWUSR || 0,
S_IXUSR: binding.S_IXUSR || 0,
S_IRGRP: binding.S_IRGRP || 0,
S_IWGRP: binding.S_IWGRP || 0,
S_IXGRP: binding.S_IXGRP || 0,
S_IROTH: binding.S_IROTH || 0,
S_IWOTH: binding.S_IWOTH || 0,
S_IXOTH: binding.S_IXOTH || 0,
UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,
COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
};
}
});
// ../../node_modules/bare-fs/lib/errors.js
var require_errors16 = __commonJS({
"../../node_modules/bare-fs/lib/errors.js"(exports, module) {
var os = require_bare_os();
module.exports = class FileError extends Error {
constructor(msg, opts = {}) {
const { code, operation = null, path = null, destination = null, fd = -1 } = opts;
if (operation !== null) msg += describe(operation, opts);
super(`${code}: ${msg}`);
this.code = code;
if (operation !== null) this.operation = operation;
if (path !== null) this.path = path;
if (destination !== null) this.destination = destination;
if (fd !== -1) this.fd = fd;
}
get name() {
return "FileError";
}
// For Node.js compatibility
get errno() {
return os.constants.errnos[this.code];
}
// For Node.js compatibility
get syscall() {
return this.operation;
}
// For Node.js compatibility
get dest() {
return this.destination;
}
};
function describe(operation, opts) {
const { path = null, destination = null, fd = -1 } = opts;
let result = `, ${operation}`;
if (path !== null) {
result += ` ${JSON.stringify(path)}`;
if (destination !== null) {
result += ` -> ${JSON.stringify(destination)}`;
}
} else if (fd !== -1) {
result += ` ${fd}`;
}
return result;
}
}
});
// ../../node_modules/bare-fs/promises.js
var require_promises = __commonJS({
"../../node_modules/bare-fs/promises.js"(exports) {
var EventEmitter = require_bare_events();
var fs = require_bare_fs();
var FileHandle = class extends EventEmitter {
constructor(fd) {
super();
this.fd = fd;
}
async close() {
await fs.close(this.fd);
this.fd = -1;
this.emit("close");
}
async read(buffer, ...args) {
return {
bytesRead: await fs.read(this.fd, buffer, ...args),
buffer
};
}
async readv(buffers, ...args) {
return {
bytesRead: await fs.readv(this.fd, buffers, ...args),
buffers
};
}
async write(buffer, ...args) {
return {
bytesWritten: await fs.write(this.fd, buffer, ...args),
buffer
};
}
async writev(buffers, ...args) {
return {
bytesWritten: await fs.writev(this.fd, buffers, ...args),
buffers
};
}
async stat() {
return fs.fstat(this.fd);
}
async chmod(mode) {
await fs.fchmod(this.fd, mode);
}
createReadStream(opts) {
return fs.createReadStream(null, { ...opts, fd: this.fd });
}
createWriteStream(opts) {
return fs.createWriteStream(null, { ...opts, fd: this.fd });
}
async [Symbol.asyncDispose]() {
await this.close();
}
};
exports.open = async function open(filepath, flags, mode) {
return new FileHandle(await fs.open(filepath, flags, mode));
};
exports.access = fs.access;
exports.appendFile = fs.appendFile;
exports.chmod = fs.chmod;
exports.constants = fs.constants;
exports.copyFile = fs.copyFile;
exports.cp = fs.cp;
exports.lstat = fs.lstat;
exports.mkdir = fs.mkdir;
exports.opendir = fs.opendir;
exports.readFile = fs.readFile;
exports.readdir = fs.readdir;
exports.readlink = fs.readlink;
exports.realpath = fs.realpath;
exports.rename = fs.rename;
exports.rm = fs.rm;
exports.rmdir = fs.rmdir;
exports.stat = fs.stat;
exports.symlink = fs.symlink;
exports.unlink = fs.unlink;
exports.utimes = fs.utimes;
exports.watch = fs.watch;
exports.writeFile = fs.writeFile;
}
});
// ../../node_modules/bare-fs/index.js
var require_bare_fs = __commonJS({
"../../node_modules/bare-fs/index.js"(exports) {
var FIFO = require_fast_fifo();
var EventEmitter = require_bare_events();
var path = require_bare_path();
var { isURL, fileURLToPath } = require_bare_url();
var { Readable, Writable } = require_bare_stream();
var binding = require_binding16();
var constants = require_constants12();
var FileError = require_errors16();
var isWindows = Bare.platform === "win32";
exports.constants = constants;
var FileRequest = class _FileRequest {
static borrow() {
if (this._free.length > 0) return this._free.pop();
return new _FileRequest();
}
static return(req) {
if (this._free.length < 32) this._free.push(req.reset());
else req.destroy();
}
constructor() {
this._reset();
this._handle = binding.requestInit(this, this._onresult);
}
get handle() {
return this._handle;
}
retain(value) {
this._retain = value;
}
reset() {
if (this._handle === null) return this;
binding.requestReset(this._handle);
this._reset();
return this;
}
destroy() {
if (this._handle === null) return this;
binding.requestDestroy(this._handle);
this._reset();
this._handle = null;
return this;
}
then(resolve, reject) {
return this._promise.then(resolve, reject);
}
return() {
if (this._handle === null) return this;
_FileRequest.return(this);
return this;
}
_reset() {
this._promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
this._retain = null;
}
_onresult(err, status) {
if (err) this._reject(err);
else this._resolve(status);
}
};
FileRequest._free = [];
function ok(result, cb) {
if (typeof result === "function") {
cb = result;
result = void 0;
}
if (cb) cb(null, result);
else return result;
}
function fail(err, cb) {
if (cb) cb(err);
else throw err;
}
function done(err, result, cb) {
if (typeof result === "function") {
cb = result;
result = void 0;
}
if (err) fail(err, cb);
else return ok(result, cb);
}
async function open(filepath, flags = "r", mode = 438, cb) {
if (typeof flags === "function") {
cb = flags;
flags = "r";
mode = 438;
} else if (typeof mode === "function") {
cb = mode;
mode = 438;
}
if (typeof flags === "string") flags = toFlags(flags);
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let fd;
let err = null;
try {
binding.open(req.handle, filepath, flags, mode);
fd = await req;
} catch (e) {
err = new FileError(e.message, {
operation: "open",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, fd, cb);
}
function openSync(filepath, flags = "r", mode = 438) {
if (typeof flags === "string") flags = toFlags(flags);
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
return binding.openSync(req.handle, filepath, flags, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "open",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function close(fd, cb) {
const req = FileRequest.borrow();
let err = null;
try {
binding.close(req.handle, fd);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "close", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function closeSync(fd) {
const req = FileRequest.borrow();
try {
binding.closeSync(req.handle, fd);
} catch (e) {
throw new FileError(e.message, { operation: "close", code: e.code, fd });
} finally {
req.return();
}
}
async function access(filepath, mode = constants.F_OK, cb) {
if (typeof mode === "function") {
cb = mode;
mode = constants.F_OK;
}
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.access(req.handle, filepath, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "access",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function accessSync(filepath, mode = constants.F_OK) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.accessSync(req.handle, filepath, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "access",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function exists(filepath, cb) {
let ok2 = true;
try {
await access(filepath);
} catch {
ok2 = false;
}
return done(null, ok2, cb);
}
function existsSync(filepath) {
try {
accessSync(filepath);
} catch {
return false;
}
return true;
}
async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
if (typeof offset === "function") {
cb = offset;
offset = 0;
len = buffer.byteLength;
pos = -1;
} else if (typeof len === "function") {
cb = len;
len = buffer.byteLength - offset;
pos = -1;
} else if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.read(req.handle, fd, buffer, offset, len, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "read", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
const req = FileRequest.borrow();
try {
return binding.readSync(req.handle, fd, buffer, offset, len, pos);
} catch (e) {
throw new FileError(e.message, { operation: "read", code: e.code, fd });
} finally {
req.return();
}
}
async function readv(fd, buffers, pos = -1, cb) {
if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.readv(req.handle, fd, buffers, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "readv", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function readvSync(fd, buffers, pos = -1) {
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
try {
return binding.readvSync(req.handle, fd, buffers, pos);
} catch (e) {
throw new FileError(e.message, { operation: "readv", code: e.code, fd });
} finally {
req.return();
}
}
async function write(fd, data, offset, len, pos = -1, cb) {
if (typeof data === "string") {
let encoding = len;
cb = pos;
pos = offset;
if (typeof pos === "function") {
cb = pos;
pos = -1;
encoding = "utf8";
} else if (typeof encoding === "function") {
cb = encoding;
encoding = "utf8";
}
if (typeof pos === "string") {
encoding = pos;
pos = -1;
}
data = Buffer.from(data, encoding);
offset = 0;
len = data.byteLength;
} else if (typeof offset === "function") {
cb = offset;
offset = 0;
len = data.byteLength;
pos = -1;
} else if (typeof len === "function") {
cb = len;
len = data.byteLength - offset;
pos = -1;
} else if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof offset !== "number") offset = 0;
if (typeof len !== "number") len = data.byteLength - offset;
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.write(req.handle, fd, data, offset, len, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "write", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function writeSync(fd, data, offset, len, pos = -1) {
if (typeof data === "string") {
let encoding = len;
pos = offset;
if (typeof pos === "string") {
encoding = pos;
pos = -1;
}
data = Buffer.from(data, encoding);
offset = 0;
len = data.byteLength;
}
if (typeof offset !== "number") offset = 0;
if (typeof len !== "number") len = data.byteLength - offset;
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
try {
return binding.writeSync(req.handle, fd, data, offset, len, pos);
} catch (e) {
throw new FileError(e.message, { operation: "write", code: e.code, fd });
} finally {
req.return();
}
}
async function writev(fd, buffers, pos = -1, cb) {
if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.writev(req.handle, fd, buffers, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "writev", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function writevSync(fd, buffers, pos = -1) {
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
try {
return binding.writevSync(req.handle, fd, buffers, pos);
} catch (e) {
throw new FileError(e.message, { operation: "writev", code: e.code, fd });
} finally {
req.return();
}
}
async function stat(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let st;
let err = null;
try {
binding.stat(req.handle, filepath);
await req;
st = new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
err = new FileError(e.message, {
operation: "stat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, st, cb);
}
function statSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.statSync(req.handle, filepath);
return new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
throw new FileError(e.message, {
operation: "stat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function lstat(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let st;
let err = null;
try {
binding.lstat(req.handle, filepath);
await req;
st = new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
err = new FileError(e.message, {
operation: "lstat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, st, cb);
}
function lstatSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.lstatSync(req.handle, filepath);
return new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
throw new FileError(e.message, {
operation: "lstat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function fstat(fd, cb) {
const req = FileRequest.borrow();
let st;
let err = null;
try {
binding.fstat(req.handle, fd);
await req;
st = new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
err = new FileError(e.message, { operation: "fstat", code: e.code, fd });
} finally {
req.return();
}
return done(err, st, cb);
}
function fstatSync(fd) {
const req = FileRequest.borrow();
try {
binding.fstatSync(req.handle, fd);
return new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
throw new FileError(e.message, { operation: "fstat", code: e.code, fd });
} finally {
req.return();
}
}
async function ftruncate(fd, len = 0, cb) {
if (typeof len === "function") {
cb = len;
len = 0;
}
if (typeof len !== "number") len = 0;
const req = FileRequest.borrow();
let err = null;
try {
binding.ftruncate(req.handle, fd, len);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "ftruncate", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function ftruncateSync(fd, len = 0) {
if (typeof len !== "number") len = 0;
const req = FileRequest.borrow();
try {
binding.ftruncateSync(req.handle, fd, len);
} catch (e) {
throw new FileError(e.message, { operation: "ftruncate", code: e.code, fd });
} finally {
req.return();
}
}
async function chmod(filepath, mode, cb) {
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.chmod(req.handle, filepath, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "chmod",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function chmodSync(filepath, mode) {
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.chmodSync(req.handle, filepath, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "chmod",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function fchmod(fd, mode, cb) {
if (typeof mode === "string") mode = toMode(mode);
const req = FileRequest.borrow();
let err = null;
try {
binding.fchmod(req.handle, fd, mode);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "fchmod", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function fchmodSync(fd, mode) {
if (typeof mode === "string") mode = toMode(mode);
const req = FileRequest.borrow();
try {
binding.fchmodSync(req.handle, fd, mode);
} catch (e) {
throw new FileError(e.message, { operation: "fchmod", code: e.code, fd });
} finally {
req.return();
}
}
async function utimes(filepath, atime, mtime, cb) {
if (typeof atime !== "number") atime = atime.getTime() / 1e3;
if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.utimes(req.handle, filepath, atime, mtime);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "utimes",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function utimesSync(filepath, atime, mtime) {
if (typeof atime !== "number") atime = atime.getTime() / 1e3;
if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.utimesSync(req.handle, filepath, atime, mtime);
} catch (e) {
throw new FileError(e.message, {
operation: "utimes",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function mkdir(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = { mode: 511 };
}
if (typeof opts === "number") opts = { mode: opts };
else if (!opts) opts = {};
const mode = typeof opts.mode === "number" ? opts.mode : 511;
filepath = toNamespacedPath(filepath);
if (opts.recursive) {
let err2 = null;
try {
try {
await mkdir(filepath, { mode });
} catch (err3) {
if (err3.code !== "ENOENT") {
if (!(await stat(filepath)).isDirectory()) throw err3;
} else {
while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1);
const i = filepath.lastIndexOf(path.sep);
if (i <= 0) throw err3;
await mkdir(filepath.slice(0, i), { mode, recursive: true });
try {
await mkdir(filepath, { mode });
} catch (err4) {
if (!(await stat(filepath)).isDirectory()) throw err4;
}
}
}
} catch (e) {
err2 = e;
}
return done(err2, cb);
}
const req = FileRequest.borrow();
let err = null;
try {
binding.mkdir(req.handle, filepath, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "mkdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function mkdirSync(filepath, opts) {
if (typeof opts === "number") opts = { mode: opts };
else if (!opts) opts = {};
const mode = typeof opts.mode === "number" ? opts.mode : 511;
filepath = toNamespacedPath(filepath);
if (opts.recursive) {
try {
mkdirSync(filepath, { mode });
} catch (err) {
if (err.code !== "ENOENT") {
if (!statSync(filepath).isDirectory()) throw err;
} else {
while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1);
const i = filepath.lastIndexOf(path.sep);
if (i <= 0) throw err;
mkdirSync(filepath.slice(0, i), { mode, recursive: true });
try {
mkdirSync(filepath, { mode });
} catch (err2) {
if (!statSync(filepath).isDirectory()) throw err2;
}
}
}
return;
}
const req = FileRequest.borrow();
try {
binding.mkdirSync(req.handle, filepath, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "mkdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function rmdir(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.rmdir(req.handle, filepath);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "rmdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function rmdirSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.rmdirSync(req.handle, filepath);
} catch (e) {
throw new FileError(e.message, {
operation: "rmdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function rm(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
let err = null;
try {
const st = await lstat(filepath);
if (st.isDirectory()) {
if (opts.recursive) {
try {
await rmdir(filepath);
} catch (err2) {
if (err2.code !== "ENOTEMPTY") throw err2;
const files = await readdir(filepath);
for (const file of files) {
await rm(filepath + path.sep + file, opts);
}
await rmdir(filepath);
}
} else {
throw new FileError("is a directory", {
operation: "rm",
code: "EISDIR",
path: filepath
});
}
} else {
await unlink(filepath);
}
} catch (e) {
if (e.code !== "ENOENT" || !opts.force) err = e;
}
return done(err, cb);
}
function rmSync(filepath, opts) {
if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
try {
const st = lstatSync(filepath);
if (st.isDirectory()) {
if (opts.recursive) {
try {
rmdirSync(filepath);
} catch (err) {
if (err.code !== "ENOTEMPTY") throw err;
const files = readdirSync(filepath);
for (const file of files) {
rmSync(filepath + path.sep + file, opts);
}
rmdirSync(filepath);
}
} else {
throw new FileError("is a directory", {
operation: "rm",
code: "EISDIR",
path: filepath
});
}
} else {
unlinkSync(filepath);
}
} catch (err) {
if (err.code !== "ENOENT" || !opts.force) throw err;
}
}
async function unlink(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.unlink(req.handle, filepath);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "unlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function unlinkSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.unlinkSync(req.handle, filepath);
} catch (e) {
throw new FileError(e.message, {
operation: "unlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function rename(src, dst, cb) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
let err = null;
try {
binding.rename(req.handle, src, dst);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "rename",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
return done(err, cb);
}
function renameSync(src, dst) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
try {
binding.renameSync(req.handle, src, dst);
} catch (e) {
throw new FileError(e.message, {
operation: "rename",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
}
async function copyFile(src, dst, mode = 0, cb) {
if (typeof mode === "function") {
cb = mode;
mode = 0;
}
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
let err = null;
try {
binding.copyfile(req.handle, src, dst, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "copyfile",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
return done(err, cb);
}
function copyFileSync(src, dst, mode = 0) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
try {
binding.copyfileSync(req.handle, src, dst, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "copyfile",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
}
async function cp(src, dst, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (!opts) opts = {};
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
let err = null;
try {
const st = await lstat(src);
if (st.isDirectory()) {
if (opts.recursive !== true) {
throw new FileError("is a directory", { operation: "cp", code: "EISDIR", path: src });
}
try {
await lstat(dst);
} catch (e) {
if (e.code !== "ENOENT") throw e;
await mkdir(dst, { mode: st.mode, recursive: true });
}
const dir = await opendir(src);
for await (const { name } of dir) {
await cp(path.join(src, name), path.join(dst, name), opts);
}
} else if (st.isFile()) {
await copyFile(src, dst);
await chmod(dst, st.mode);
}
} catch (e) {
err = e;
}
return done(err, cb);
}
function cpSync(src, dst, opts = {}) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const st = lstatSync(src);
if (st.isDirectory()) {
if (opts.recursive !== true) {
throw new FileError("is a directory", { operation: "cp", code: "EISDIR", path: src });
}
try {
lstatSync(dst);
} catch (e) {
if (e.code !== "ENOENT") throw e;
mkdirSync(dst, { mode: st.mode, recursive: true });
}
const dir = opendirSync(src);
for (const { name } of dir) {
cpSync(path.join(src, name), path.join(dst, name), opts);
}
} else if (st.isFile()) {
copyFileSync(src, dst);
chmodSync(dst, st.mode);
}
}
async function realpath(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let res;
let err = null;
try {
binding.realpath(req.handle, filepath);
await req;
res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
} catch (e) {
err = new FileError(e.message, {
operation: "realpath",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, res, cb);
}
function realpathSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.realpathSync(req.handle, filepath);
let res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
return res;
} catch (e) {
throw new FileError(e.message, {
operation: "realpath",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function readlink(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let res;
let err = null;
try {
binding.readlink(req.handle, filepath);
await req;
res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
} catch (e) {
err = new FileError(e.message, {
operation: "readlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, res, cb);
}
function readlinkSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.readlinkSync(req.handle, filepath);
let res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
return res;
} catch (e) {
throw new FileError(e.message, {
operation: "readlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
function normalizeSymlinkTarget(target, type, filepath) {
if (isWindows) {
if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, "..", target);
if (path.isAbsolute(target)) return path.toNamespacedPath(target);
return target.replace(/\//g, path.sep);
}
return target;
}
async function symlink(target, filepath, type, cb) {
if (typeof type === "function") {
cb = type;
type = null;
}
filepath = toNamespacedPath(filepath);
if (typeof type === "string") {
switch (type) {
case "dir":
type = constants.UV_FS_SYMLINK_DIR;
break;
case "junction":
type = constants.UV_FS_SYMLINK_JUNCTION;
break;
case "file":
default:
type = 0;
break;
}
} else if (typeof type !== "number") {
if (isWindows) {
target = path.resolve(filepath, "..", target);
try {
type = (await stat(target)).isDirectory() ? constants.UV_FS_SYMLINK_DIR : constants.UV_FS_SYMLINK_JUNCTION;
} catch {
type = 0;
}
} else {
type = 0;
}
}
target = normalizeSymlinkTarget(target, type, filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.symlink(req.handle, target, filepath, type);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "symlink",
code: e.code,
path: target,
destination: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function symlinkSync(target, filepath, type) {
filepath = toNamespacedPath(filepath);
if (typeof type === "string") {
switch (type) {
case "dir":
type = constants.UV_FS_SYMLINK_DIR;
break;
case "junction":
type = constants.UV_FS_SYMLINK_JUNCTION;
break;
case "file":
default:
type = 0;
break;
}
} else if (typeof type !== "number") {
if (isWindows) {
target = path.resolve(filepath, "..", target);
try {
type = statSync(target).isDirectory() ? constants.UV_FS_SYMLINK_DIR : constants.UV_FS_SYMLINK_JUNCTION;
} catch {
type = 0;
}
} else {
type = 0;
}
}
target = normalizeSymlinkTarget(target, type, filepath);
const req = FileRequest.borrow();
try {
binding.symlinkSync(req.handle, target, filepath, type);
} catch (e) {
throw new FileError(e.message, {
operation: "symlink",
code: e.code,
path: target,
destination: filepath
});
} finally {
req.return();
}
}
async function opendir(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let dir;
let err = null;
try {
binding.opendir(req.handle, filepath);
await req;
dir = new Dir(filepath, binding.requestResultDir(req.handle), opts);
} catch (e) {
err = new FileError(e.message, {
operation: "opendir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, dir, cb);
}
function opendirSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.opendirSync(req.handle, filepath);
return new Dir(filepath, binding.requestResultDir(req.handle), opts);
} catch (e) {
throw new FileError(e.message, {
operation: "opendir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function readdir(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { withFileTypes = false } = opts;
filepath = toNamespacedPath(filepath);
let result = [];
let err = null;
try {
const dir = await opendir(filepath);
for await (const entry of dir) {
result.push(withFileTypes ? entry : entry.name);
}
} catch (e) {
result = [];
err = e;
}
return done(err, result, cb);
}
function readdirSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { withFileTypes = false } = opts;
filepath = toNamespacedPath(filepath);
const dir = opendirSync(filepath, opts);
const result = [];
for (const entry of dir) {
result.push(withFileTypes ? entry : entry.name);
}
return result;
}
async function readFile(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "buffer" } = opts;
let fd = -1;
let buffer = null;
let err = null;
try {
fd = await open(filepath, opts.flag || "r");
const st = await fstat(fd);
let len = 0;
if (st.size === 0) {
const buffers = [];
while (true) {
buffer = Buffer.allocUnsafe(8192);
const r = await read(fd, buffer);
len += r;
if (r === 0) break;
buffers.push(buffer.subarray(0, r));
}
buffer = Buffer.concat(buffers);
} else {
buffer = Buffer.allocUnsafe(st.size);
while (true) {
const r = await read(fd, len ? buffer.subarray(len) : buffer);
len += r;
if (r === 0 || len === buffer.byteLength) break;
}
if (len !== buffer.byteLength) buffer = buffer.subarray(0, len);
}
if (encoding !== "buffer") buffer = buffer.toString(encoding);
} catch (e) {
err = e;
} finally {
if (fd !== -1) await close(fd);
}
return done(err, buffer, cb);
}
function readFileSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "buffer" } = opts;
let fd = -1;
try {
fd = openSync(filepath, opts.flag || "r");
const st = fstatSync(fd);
let buffer;
let len = 0;
if (st.size === 0) {
const buffers = [];
while (true) {
buffer = Buffer.allocUnsafe(8192);
const r = readSync(fd, buffer);
len += r;
if (r === 0) break;
buffers.push(buffer.subarray(0, r));
}
buffer = Buffer.concat(buffers);
} else {
buffer = Buffer.allocUnsafe(st.size);
while (true) {
const r = readSync(fd, len ? buffer.subarray(len) : buffer);
len += r;
if (r === 0 || len === buffer.byteLength) break;
}
if (len !== buffer.byteLength) buffer = buffer.subarray(0, len);
}
if (encoding !== "buffer") buffer = buffer.toString(encoding);
return buffer;
} finally {
if (fd !== -1) closeSync(fd);
}
}
async function writeFile(filepath, data, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (typeof data === "string") data = Buffer.from(data, opts.encoding);
let fd = -1;
let len = 0;
let err = null;
try {
fd = await open(filepath, opts.flag || "w", opts.mode || 438);
while (true) {
len += await write(fd, len ? data.subarray(len) : data);
if (len === data.byteLength) break;
}
} catch (e) {
err = e;
} finally {
if (fd !== -1) await close(fd);
}
return done(err, len, cb);
}
function writeFileSync(filepath, data, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (typeof data === "string") data = Buffer.from(data, opts.encoding);
let fd = -1;
try {
fd = openSync(filepath, opts.flag || "w", opts.mode || 438);
let len = 0;
while (true) {
len += writeSync(fd, len ? data.subarray(len) : data);
if (len === data.byteLength) break;
}
} finally {
if (fd !== -1) closeSync(fd);
}
}
function appendFile(filepath, data, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (!opts.flag) opts = { ...opts, flag: "a" };
return writeFile(filepath, data, opts, cb);
}
function appendFileSync(filepath, data, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (!opts.flag) opts = { ...opts, flag: "a" };
return writeFileSync(filepath, data, opts);
}
function watch(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
return new Watcher(filepath, opts, cb);
}
var Stats = class {
constructor(dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atimeMs, mtimeMs, ctimeMs, birthtimeMs) {
this.dev = dev;
this.mode = mode;
this.nlink = nlink;
this.uid = uid;
this.gid = gid;
this.rdev = rdev;
this.blksize = blksize;
this.ino = ino;
this.size = size;
this.blocks = blocks;
this.atimeMs = atimeMs;
this.mtimeMs = mtimeMs;
this.ctimeMs = ctimeMs;
this.birthtimeMs = birthtimeMs;
this.atime = new Date(atimeMs);
this.mtime = new Date(mtimeMs);
this.ctime = new Date(ctimeMs);
this.birthtime = new Date(birthtimeMs);
}
isDirectory() {
return (this.mode & constants.S_IFMT) === constants.S_IFDIR;
}
isFile() {
return (this.mode & constants.S_IFMT) === constants.S_IFREG;
}
isBlockDevice() {
return (this.mode & constants.S_IFMT) === constants.S_IFBLK;
}
isCharacterDevice() {
return (this.mode & constants.S_IFMT) === constants.S_IFCHR;
}
isFIFO() {
return (this.mode & constants.S_IFMT) === constants.S_IFIFO;
}
isSymbolicLink() {
return (this.mode & constants.S_IFMT) === constants.S_IFLNK;
}
isSocket() {
return (this.mode & constants.S_IFMT) === constants.S_IFSOCK;
}
};
var Dir = class {
constructor(path2, handle, opts = {}) {
const { encoding = "utf8", bufferSize = 32 } = opts;
this.path = path2;
this._encoding = encoding;
this._capacity = bufferSize;
this._buffer = new FIFO();
this._ended = false;
this._handle = handle;
}
async read(cb) {
if (this._buffer.length) return ok(this._buffer.shift(), cb);
if (this._ended) return ok(null, cb);
const req = FileRequest.borrow();
let entries;
let err = null;
try {
req.retain(binding.readdir(req.handle, this._handle, this._capacity));
await req;
entries = binding.requestResultDirents(req.handle);
} catch (e) {
err = new FileError(e.message, {
operation: "readdir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
if (err) return fail(err, cb);
if (entries.length === 0) {
this._ended = true;
return ok(null, cb);
}
for (const entry of entries) {
let name = Buffer.from(entry.name);
if (this._encoding !== "buffer") name = name.toString(this._encoding);
this._buffer.push(new Dirent(this.path, name, entry.type));
}
return ok(this._buffer.shift(), cb);
}
readSync() {
if (this._buffer.length) return this._buffer.shift();
if (this._ended) return null;
const req = FileRequest.borrow();
let entries;
try {
req.retain(binding.readdirSync(req.handle, this._handle, this._capacity));
entries = binding.requestResultDirents(req.handle);
} catch (e) {
throw new FileError(e.message, {
operation: "readdir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
if (entries.length === 0) {
this._ended = true;
return null;
}
for (const entry of entries) {
let name = Buffer.from(entry.name);
if (this._encoding !== "buffer") name = name.toString(this._encoding);
this._buffer.push(new Dirent(this.path, name, entry.type));
}
return this._buffer.shift();
}
async close(cb) {
const req = FileRequest.borrow();
let err = null;
try {
binding.closedir(req.handle, this._handle);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "closedir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
this._handle = null;
return done(err, cb);
}
closeSync() {
const req = FileRequest.borrow();
try {
binding.closedirSync(req.handle, this._handle);
} catch (e) {
throw new FileError(e.message, {
operation: "closedir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
this._handle = null;
}
[Symbol.dispose]() {
this.closeSync();
}
async [Symbol.asyncDispose]() {
await this.close();
}
*[Symbol.iterator]() {
while (true) {
const entry = this.readSync();
if (entry === null) break;
yield entry;
}
this.closeSync();
}
async *[Symbol.asyncIterator]() {
while (true) {
const entry = await this.read();
if (entry === null) break;
yield entry;
}
await this.close();
}
};
var Dirent = class {
constructor(parentPath, name, type) {
this.parentPath = parentPath;
this.name = name;
this.type = type;
}
isFile() {
return this.type === constants.UV_DIRENT_FILE;
}
isDirectory() {
return this.type === constants.UV_DIRENT_DIR;
}
isSymbolicLink() {
return this.type === constants.UV_DIRENT_LINK;
}
isFIFO() {
return this.type === constants.UV_DIRENT_FIFO;
}
isSocket() {
return this.type === constants.UV_DIRENT_SOCKET;
}
isCharacterDevice() {
return this.type === constants.UV_DIRENT_CHAR;
}
isBlockDevice() {
return this.type === constants.UV_DIRENT_BLOCK;
}
};
var FileReadStream = class extends Readable {
constructor(path2, opts = {}) {
const { eagerOpen = true } = opts;
super({ eagerOpen, ...opts });
this.path = path2;
this.fd = typeof opts.fd === "number" ? opts.fd : -1;
this.flags = opts.flags || "r";
this.mode = opts.mode || 438;
this._offset = opts.start || 0;
this._missing = 0;
if (opts.length) {
this._missing = opts.length;
} else if (typeof opts.end === "number") {
this._missing = opts.end - this._offset + 1;
} else {
this._missing = -1;
}
}
async _open(cb) {
let err;
if (this.fd === -1) {
err = null;
try {
this.fd = await open(this.path, this.flags, this.mode);
} catch (e) {
err = e;
}
if (err) return cb(err);
}
let st;
err = null;
try {
st = await fstat(this.fd);
} catch (e) {
err = e;
}
if (err) return cb(err);
if (this._missing === -1) this._missing = st.size;
if (st.size < this._offset) {
this._offset = st.size;
this._missing = 0;
} else if (st.size < this._offset + this._missing) {
this._missing = st.size - this._offset;
}
cb(null);
}
async _read(size) {
if (this._missing <= 0) return this.push(null);
const data = Buffer.allocUnsafe(Math.min(this._missing, size));
let len;
let err = null;
try {
len = await read(this.fd, data, 0, data.byteLength, this._offset);
} catch (e) {
err = e;
}
if (err) return this.destroy(err);
if (len === 0) return this.push(null);
if (this._missing < len) len = this._missing;
this._missing -= len;
this._offset += len;
this.push(data.subarray(0, len));
}
async _destroy(err, cb) {
if (this.fd === -1) return cb(err);
try {
await close(this.fd);
} catch (e) {
err = err || e;
}
cb(err);
}
};
var FileWriteStream = class extends Writable {
constructor(path2, opts = {}) {
const { eagerOpen = true } = opts;
super({ eagerOpen, ...opts });
this.path = path2;
this.fd = typeof opts.fd === "number" ? opts.fd : -1;
this.flags = opts.flags || "w";
this.mode = opts.mode || 438;
}
async _open(cb) {
if (this.fd !== -1) return cb(null);
let err = null;
try {
this.fd = await open(this.path, this.flags, this.mode);
} catch (e) {
err = e;
}
cb(err);
}
async _writev(batch, cb) {
let err = null;
try {
await writev(
this.fd,
batch.map(({ chunk }) => chunk)
);
} catch (e) {
err = e;
}
cb(err);
}
async _destroy(err, cb) {
if (this.fd === -1) return cb(err);
try {
await close(this.fd);
} catch (e) {
err = err || e;
}
cb(err);
}
};
var Watcher = class extends EventEmitter {
constructor(path2, opts, onchange) {
if (typeof opts === "function") {
onchange = opts;
opts = {};
}
if (!opts) opts = {};
const { persistent = true, recursive = false, encoding = "utf8" } = opts;
super();
this._closed = false;
this._encoding = encoding;
this._handle = binding.watcherInit(path2, recursive, this, this._onevent, this._onclose);
if (!persistent) this.unref();
if (onchange) this.on("change", onchange);
}
close() {
if (this._closed) return;
this._closed = true;
binding.watcherClose(this._handle);
}
ref() {
if (this._handle) binding.watcherRef(this._handle);
return this;
}
unref() {
if (this._handle) binding.watcherUnref(this._handle);
return this;
}
[Symbol.asyncIterator]() {
const buffer = [];
let done2 = false;
let error = null;
let next = null;
this.on("change", (eventType, filename) => {
if (next) {
next.resolve({ done: false, value: { eventType, filename } });
next = null;
} else {
buffer.push({ eventType, filename });
}
}).on("error", (err) => {
done2 = true;
error = err;
if (next) {
next.reject(error);
next = null;
}
}).on("close", () => {
done2 = true;
if (next) {
next.resolve({ done: done2 });
next = null;
}
});
return {
next: () => new Promise((resolve, reject) => {
if (error) return reject(error);
if (buffer.length) return resolve({ done: false, value: buffer.shift() });
if (done2) return resolve({ done: done2 });
next = { resolve, reject };
})
};
}
_onevent(err, events, filename) {
if (err) {
this.close();
this.emit("error", err);
} else {
const path2 = this._encoding === "buffer" ? Buffer.from(filename) : Buffer.from(filename).toString(this._encoding);
if (events & binding.UV_RENAME) {
this.emit("change", "rename", path2);
}
if (events & binding.UV_CHANGE) {
this.emit("change", "change", path2);
}
}
}
_onclose() {
this._handle = null;
this.emit("close");
}
};
exports.access = access;
exports.appendFile = appendFile;
exports.chmod = chmod;
exports.close = close;
exports.copyFile = copyFile;
exports.cp = cp;
exports.exists = exists;
exports.fchmod = fchmod;
exports.fstat = fstat;
exports.ftruncate = ftruncate;
exports.lstat = lstat;
exports.mkdir = mkdir;
exports.open = open;
exports.opendir = opendir;
exports.read = read;
exports.readFile = readFile;
exports.readdir = readdir;
exports.readlink = readlink;
exports.readv = readv;
exports.realpath = realpath;
exports.rename = rename;
exports.rm = rm;
exports.rmdir = rmdir;
exports.stat = stat;
exports.symlink = symlink;
exports.unlink = unlink;
exports.utimes = utimes;
exports.watch = watch;
exports.write = write;
exports.writeFile = writeFile;
exports.writev = writev;
exports.accessSync = accessSync;
exports.appendFileSync = appendFileSync;
exports.chmodSync = chmodSync;
exports.closeSync = closeSync;
exports.copyFileSync = copyFileSync;
exports.cpSync = cpSync;
exports.existsSync = existsSync;
exports.fchmodSync = fchmodSync;
exports.fstatSync = fstatSync;
exports.ftruncateSync = ftruncateSync;
exports.lstatSync = lstatSync;
exports.mkdirSync = mkdirSync;
exports.openSync = openSync;
exports.opendirSync = opendirSync;
exports.readFileSync = readFileSync;
exports.readSync = readSync;
exports.readdirSync = readdirSync;
exports.readlinkSync = readlinkSync;
exports.readvSync = readvSync;
exports.realpathSync = realpathSync;
exports.renameSync = renameSync;
exports.rmSync = rmSync;
exports.rmdirSync = rmdirSync;
exports.statSync = statSync;
exports.symlinkSync = symlinkSync;
exports.unlinkSync = unlinkSync;
exports.utimesSync = utimesSync;
exports.writeFileSync = writeFileSync;
exports.writeSync = writeSync;
exports.writevSync = writevSync;
exports.promises = require_promises();
exports.Stats = Stats;
exports.Dir = Dir;
exports.Dirent = Dirent;
exports.Watcher = Watcher;
exports.ReadStream = FileReadStream;
exports.createReadStream = function createReadStream(path2, opts) {
return new FileReadStream(path2, opts);
};
exports.WriteStream = FileWriteStream;
exports.createWriteStream = function createWriteStream(path2, opts) {
return new FileWriteStream(path2, opts);
};
function toNamespacedPath(filepath) {
if (typeof filepath !== "string") {
if (isURL(filepath)) filepath = fileURLToPath(filepath);
else filepath = filepath.toString();
}
return path.toNamespacedPath(filepath);
}
function toFlags(flags) {
switch (flags) {
case "r":
return constants.O_RDONLY;
case "rs":
// Fall through.
case "sr":
return constants.O_RDONLY | constants.O_SYNC;
case "r+":
return constants.O_RDWR;
case "rs+":
// Fall through.
case "sr+":
return constants.O_RDWR | constants.O_SYNC;
case "w":
return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY;
case "wx":
// Fall through.
case "xw":
return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL;
case "w+":
return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR;
case "wx+":
// Fall through.
case "xw+":
return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL;
case "a":
return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY;
case "ax":
// Fall through.
case "xa":
return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL;
case "as":
// Fall through.
case "sa":
return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC;
case "a+":
return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR;
case "ax+":
// Fall through.
case "xa+":
return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL;
case "as+":
// Fall through.
case "sa+":
return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC;
default:
return 0;
}
}
function toMode(mode) {
return parseInt(mode, 8);
}
}
});
// ../../node_modules/bare-tty/binding.js
var require_binding17 = __commonJS({
"../../node_modules/bare-tty/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tty/lib/constants.js
var require_constants13 = __commonJS({
"../../node_modules/bare-tty/lib/constants.js"(exports, module) {
var binding = require_binding17();
module.exports = exports = {
mode: {
NORMAL: binding.MODE_NORMAL,
RAW: binding.MODE_RAW,
IO: binding.MODE_IO || 0
},
state: {
READING: 1,
CLOSING: 2
}
};
exports.MODE_NORMAL = exports.mode.NORMAL;
exports.MODE_RAW = exports.mode.RAW;
exports.MODE_IO = exports.mode.IO;
}
});
// ../../node_modules/bare-tty/index.js
var require_bare_tty = __commonJS({
"../../node_modules/bare-tty/index.js"(exports) {
var { Readable, Writable } = require_bare_stream();
var Signal = require_bare_signals();
var binding = require_binding17();
var constants = require_constants13();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
exports.ReadStream = class TTYReadStream extends Readable {
constructor(fd, opts = {}) {
super();
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts;
this._fd = fd;
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._buffer = Buffer.alloc(readBufferSize);
this._pendingDestroy = null;
this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose);
}
get fd() {
return this._fd;
}
get isTTY() {
return true;
}
setMode(mode) {
binding.setMode(this._handle, mode);
return this;
}
setRawMode(enabled) {
return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL);
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(this._handle);
}
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_onread(err, read) {
if (err) {
this.destroy(err);
return;
}
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
if (this.push(copy) === false && this.destroying === false) {
this._state &= ~constants.state.READING;
binding.pause(this._handle);
}
}
_onclose() {
this._handle = null;
this._continueDestroy();
}
};
exports.WriteStream = class TTYWriteStream extends Writable {
constructor(fd, opts = {}) {
super();
this._fd = fd;
this._state = 0;
this._size = null;
this._pendingWrite = null;
this._pendingDestroy = null;
this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose);
this._size = this.getWindowSize();
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start();
TTYWriteStream._streams.add(this);
}
get fd() {
return this._fd;
}
get isTTY() {
return true;
}
get columns() {
return this._size[0];
}
get rows() {
return this._size[1];
}
getWindowSize() {
return binding.getWindowSize(this._handle);
}
_writev(batch, cb) {
this._pendingWrite = [cb, batch];
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
TTYWriteStream._streams.delete(this);
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop();
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
TTYWriteStream._streams.delete(this);
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop();
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite[0];
this._pendingWrite = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_onwrite(err) {
this._continueWrite(err);
}
_onclose() {
this._handle = null;
this._continueDestroy();
}
_onresize() {
this._size = this.getWindowSize();
this.emit("resize");
}
static _streams = /* @__PURE__ */ new Set();
static _resize = new Signal("SIGWINCH");
};
exports.constants = constants;
exports.isTTY = binding.isTTY;
exports.isatty = exports.isTTY;
exports.WriteStream._resize.on("signal", () => {
for (const stream of exports.WriteStream._streams) {
stream._onresize();
}
}).unref();
function noop() {
}
}
});
// ../../node_modules/bare-stdio/binding.js
var require_binding18 = __commonJS({
"../../node_modules/bare-stdio/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-stdio/index.js
var require_bare_stdio = __commonJS({
"../../node_modules/bare-stdio/index.js"(exports, module) {
var fs = require_bare_fs();
var tty = require_bare_tty();
var Pipe = require_bare_pipe();
var binding = require_binding18();
var { TTY, NAMED_PIPE } = binding;
var IO = class {
constructor() {
this._in = null;
this._out = null;
this._err = null;
}
get in() {
if (this._in === null) {
switch (binding.guessType(0)) {
case TTY:
this._in = new tty.ReadStream(0);
break;
case NAMED_PIPE:
this._in = new Pipe(0, { eagerOpen: false });
break;
default:
this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false });
}
}
return this._in;
}
get out() {
if (this._out === null) {
switch (binding.guessType(1)) {
case TTY:
this._out = new tty.WriteStream(1);
break;
case NAMED_PIPE:
this._out = new Pipe(1, { eagerOpen: false });
this._out.unref();
break;
default:
this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false });
}
}
return this._out;
}
get err() {
if (this._err === null) {
switch (binding.guessType(2)) {
case TTY:
this._err = new tty.WriteStream(2);
break;
case NAMED_PIPE:
this._err = new Pipe(2, { eagerOpen: false });
this._err.unref();
break;
default:
this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false });
}
}
return this._err;
}
};
module.exports = new IO();
}
});
// ../../node_modules/bare-process/index.js
var require_bare_process = __commonJS({
"../../node_modules/bare-process/index.js"(exports, module) {
var abort = require_bare_abort();
var EventEmitter = require_bare_events();
var Signal = require_bare_signals();
var os = require_bare_os();
var env = require_bare_env();
var hrtime = require_bare_hrtime();
var stdio = require_bare_stdio();
var Process = class _Process extends EventEmitter {
constructor() {
super();
this._startTime = hrtime.bigint();
EventEmitter.forward(Bare, this, [
"uncaughtException",
"unhandledRejection",
"beforeExit",
"exit",
"suspend",
"wakeup",
"idle",
"resume"
]);
const signals = new Signal.Emitter();
signals.unref();
EventEmitter.forward(signals, this, Object.keys(os.constants.signals));
}
get stdin() {
return stdio.in;
}
get stdout() {
return stdio.out;
}
get stderr() {
return stdio.err;
}
get platform() {
return os.platform();
}
get arch() {
return os.arch();
}
get title() {
return os.getProcessTitle();
}
set title(title) {
os.setProcessTitle(title);
}
get pid() {
return os.pid();
}
get ppid() {
return os.ppid();
}
get argv() {
return Bare.argv;
}
get execPath() {
return os.execPath();
}
get exitCode() {
return Bare.exitCode;
}
set exitCode(code) {
Bare.exitCode = code;
}
get version() {
return Bare.version;
}
get versions() {
return Bare.versions;
}
get env() {
return env;
}
get hrtime() {
return hrtime;
}
abort() {
abort();
}
exit(code) {
Bare.exit(code);
}
suspend() {
Bare.suspend();
}
resume() {
Bare.resume();
}
cwd() {
return os.cwd();
}
chdir(directory) {
os.chdir(directory);
}
kill(pid, signal) {
os.kill(pid, signal);
}
uptime() {
return Number(hrtime.bigint() - this._startTime) / 1e9;
}
cpuUsage(previous) {
return os.cpuUsage(previous);
}
threadCpuUsage(previous) {
return os.threadCpuUsage(previous);
}
resourceUsage() {
return os.resourceUsage();
}
availableMemory() {
return os.availableMemory();
}
constrainedMemory() {
return os.constrainedMemory();
}
memoryUsage() {
return os.memoryUsage();
}
nextTick(cb, ...args) {
queueMicrotask(cb.bind(null, ...args));
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _Process },
platform: this.platform,
arch: this.arch,
title: this.title,
pid: this.pid,
ppid: this.ppid,
argv: this.argv,
execPath: this.execPath,
exitCode: this.exitCode,
version: this.version,
versions: this.versions,
env: this.env
};
}
};
module.exports = new Process();
}
});
// ../../node_modules/bare-process/global.js
var require_global7 = __commonJS({
"../../node_modules/bare-process/global.js"() {
global.process = require_bare_process();
}
});
// ../../node_modules/bare-stream/global.js
var require_global8 = __commonJS({
"../../node_modules/bare-stream/global.js"() {
var stream = require_web2();
global.ReadableStream = stream.ReadableStream;
global.ReadableStreamDefaultController = stream.ReadableStreamDefaultController;
global.ReadableStreamDefaultReader = stream.ReadableStreamDefaultReader;
global.CountQueuingStrategy = stream.CountQueuingStrategy;
global.ByteLengthQueuingStrategy = stream.ByteLengthQueuingStrategy;
global.WritableStream = stream.WritableStream;
global.WritableStreamDefaultController = stream.WritableStreamDefaultController;
global.WritableStreamDefaultReader = stream.WritableStreamDefaultReader;
}
});
// ../../node_modules/bare-ws/lib/constants.js
var require_constants14 = __commonJS({
"../../node_modules/bare-ws/lib/constants.js"(exports) {
exports.EOL = "\r\n";
exports.EOF = exports.EOL.repeat(2);
exports.GUID = Buffer.from("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
exports.opcode = {
CONTINUATION: 0,
TEXT: 1,
BINARY: 2,
CLOSE: 8,
PING: 9,
PONG: 10
};
exports.status = {
PROTOCOL_ERROR: 1002,
MESSAGE_TOO_LARGE: 1009
};
}
});
// ../../node_modules/bare-ws/lib/errors.js
var require_errors17 = __commonJS({
"../../node_modules/bare-ws/lib/errors.js"(exports, module) {
var { status } = require_constants14();
module.exports = class WebSocketError extends Error {
constructor(msg, code, status2, fn = WebSocketError, cause) {
super(`${code}: ${msg}`, { cause });
this.code = code;
this.status = status2;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "WebSocketError";
}
static NETWORK_ERROR(msg, cause) {
return new WebSocketError(msg, "NETWORK_ERROR", 0, WebSocketError.NETWORK_ERROR, cause);
}
static NOT_CONNECTED(msg = "Socket is not connected") {
return new WebSocketError(msg, "NOT_CONNECTED", 0, WebSocketError.NOT_CONNECTED);
}
static UNEXPECTED_RSV1(msg = "RSV1 must be unset") {
return new WebSocketError(
msg,
"UNEXPECTED_RSV1",
status.PROTOCOL_ERROR,
WebSocketError.UNEXPECTED_RSV1
);
}
static UNEXPECTED_RSV2(msg = "RSV2 must be unset") {
return new WebSocketError(
msg,
"UNEXPECTED_RSV2",
status.PROTOCOL_ERROR,
WebSocketError.UNEXPECTED_RSV2
);
}
static UNEXPECTED_RSV3(msg = "RSV3 must be unset") {
return new WebSocketError(
msg,
"UNEXPECTED_RSV3",
status.PROTOCOL_ERROR,
WebSocketError.UNEXPECTED_RSV3
);
}
static EXPECTED_MASK(msg = "MASK must be set") {
return new WebSocketError(
msg,
"EXPECTED_MASK",
status.PROTOCOL_ERROR,
WebSocketError.EXPECTED_MASK
);
}
static UNEXPECTED_MASK(msg = "MASK must be unset") {
return new WebSocketError(
msg,
"UNEXPECTED_MASK",
status.PROTOCOL_ERROR,
WebSocketError.UNEXPECTED_MASK
);
}
static EXPECTED_CONTINUATION(msg = "Expected a continuation frame") {
return new WebSocketError(
msg,
"EXPECTED_CONTINUATION",
status.PROTOCOL_ERROR,
WebSocketError.EXPECTED_CONTINUATION
);
}
static UNEXPECTED_CONTINUATION(msg = "Unexpected continuation frame") {
return new WebSocketError(
msg,
"UNEXPECTED_CONTINUATION",
status.PROTOCOL_ERROR,
WebSocketError.UNEXPECTED_CONTINUATION
);
}
static UNEXPECTED_CONTROL(msg = "Unexpected control frame") {
return new WebSocketError(
msg,
"UNEXPECTED_CONTROL",
status.PROTOCOL_ERROR,
WebSocketError.UNEXPECTED_CONTROL
);
}
static INVALID_ENCODING(msg = "Invalid encoding") {
return new WebSocketError(
msg,
"INVALID_ENCODING",
status.PROTOCOL_ERROR,
WebSocketError.INVALID_ENCODING
);
}
static INVALID_UPGRADE_HEADER(msg = "Invalid Upgrade header") {
return new WebSocketError(
msg,
"INVALID_UPGRADE_HEADER",
status.PROTOCOL_ERROR,
WebSocketError.INVALID_UPGRADE_HEADER
);
}
static INVALID_VERSION_HEADER(msg = "Invalid Sec-WebSocket-Version header") {
return new WebSocketError(
msg,
"INVALID_VERSION_HEADER",
status.PROTOCOL_ERROR,
WebSocketError.INVALID_VERSION_HEADER
);
}
static INVALID_KEY_HEADER(msg = "Invalid Sec-WebSocket-Key header") {
return new WebSocketError(
msg,
"INVALID_KEY_HEADER",
status.PROTOCOL_ERROR,
WebSocketError.INVALID_KEY_HEADER
);
}
static INVALID_ACCEPT_HEADER(msg = "Invalid Sec-WebSocket-Accept header") {
return new WebSocketError(
msg,
"INVALID_ACCEPT_HEADER",
status.PROTOCOL_ERROR,
WebSocketError.INVALID_ACCEPT_HEADER
);
}
static INVALID_OPCODE(msg = "Invalid opcode") {
return new WebSocketError(
msg,
"INVALID_OPCODE",
status.PROTOCOL_ERROR,
WebSocketError.INVALID_OPCODE
);
}
static INVALID_PAYLOAD_LENGTH(msg = "Invalid payload length") {
return new WebSocketError(
msg,
"INVALID_PAYLOAD_LENGTH",
status.MESSAGE_TOO_LARGE,
WebSocketError.INVALID_PAYLOAD_LENGTH
);
}
static INCOMPLETE_FRAME(msg = "Incomplete frame", length = -1) {
return new WebSocketError(msg, "INCOMPLETE_FRAME", length, WebSocketError.INCOMPLETE_FRAME);
}
};
}
});
// ../../node_modules/bare-ws/lib/frame.js
var require_frame = __commonJS({
"../../node_modules/bare-ws/lib/frame.js"(exports, module) {
var crypto = require_bare_crypto();
var errors = require_errors17();
var EMPTY = Buffer.alloc(0);
var FIN = 128;
var RSV1 = 64;
var RSV2 = 32;
var RSV3 = 16;
var OPCODE = 15;
var MASK = 128;
var LENGTH = 127;
module.exports = exports = class Frame2 {
constructor(opcode, payload = EMPTY, opts = {}) {
if (payload && !Buffer.isBuffer(payload)) {
opts = payload;
payload = EMPTY;
}
const { fin = true, rsv1 = false, rsv2 = false, rsv3 = false, mask = null } = opts;
this.fin = fin;
this.rsv1 = rsv1;
this.rsv2 = rsv2;
this.rsv3 = rsv3;
this.opcode = opcode;
this.mask = mask;
this.payload = payload;
}
toBuffer() {
const state = { start: 0, end: 0, buffer: null };
Frame2.preencode(state, this);
state.buffer = Buffer.allocUnsafe(state.end);
Frame2.encode(state, this);
return state.buffer;
}
};
var Frame = exports;
exports.preencode = function preencode(state, f) {
let i = state.end;
i++;
const length = f.payload.length;
if (length <= 125) i++;
else {
if (length <= 65535) i += 3;
else i += 9;
}
if (f.mask) i += 4;
i += length;
state.end = i;
};
exports.encode = function encode(state, f) {
const b = state.buffer;
let i = state.start;
const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
b[i] = f.opcode & OPCODE;
if (f.fin) b[i] |= FIN;
if (f.rsv1) b[i] |= RSV1;
if (f.rsv1) b[i] |= RSV2;
if (f.rsv1) b[i] |= RSV3;
i++;
b[i] = f.mask ? MASK : 0;
const length = f.payload.length;
if (length <= 125) b[i++] |= length;
else {
if (length <= 65535) {
b[i++] |= 126;
v.setUint16(i, length, false);
i += 2;
} else {
b[i++] |= 127;
const high = Math.floor(length / 4294967296);
v.setUint32(i, high, false);
i += 4;
const low = length & 4294967295;
v.setUint32(i, low, false);
i += 4;
}
}
if (f.mask) {
crypto.randomFill(f.mask, 0, 4);
b.set(f.mask, i);
i += 4;
for (let j = 0; j < length; j++) {
b[i + j] = f.payload[j] ^ f.mask[j & 3];
}
} else {
b.set(f.payload, i);
}
i += length;
state.start = i;
};
exports.decode = function decode(state) {
const s = state.start;
const b = state.buffer;
let i = s;
let n = b.byteLength;
if (n < 2) throw errors.INCOMPLETE_FRAME();
const view = new DataView(b.buffer, b.byteOffset, b.byteLength);
const fin = !!(b[i] & FIN);
const rsv1 = !!(b[i] & RSV1);
const rsv2 = !!(b[i] & RSV2);
const rsv3 = !!(b[i] & RSV3);
const opcode = b[i] & OPCODE;
i++;
n--;
const masked = !!(b[i] & MASK);
let length = b[i] & LENGTH;
i++;
n--;
if (length === 126) {
if (n < 2) throw errors.INCOMPLETE_FRAME();
length = view.getUint16(i, false);
i += 2;
n -= 2;
} else if (length === 127) {
if (n < 8) throw errors.INCOMPLETE_FRAME();
const high = view.getUint32(i, false);
if (high >= 2097152) throw errors.INVALID_PAYLOAD_LENGTH();
i += 4;
n -= 4;
const low = view.getUint32(i, false);
i += 4;
n -= 4;
length = high * 4294967296 + low;
}
let mask = null;
if (masked) {
if (n < 4) throw errors.INCOMPLETE_FRAME();
mask = b.subarray(i, i + 4);
i += 4;
n -= 4;
}
if (n < length) {
throw errors.INCOMPLETE_FRAME("Incomplete frame", i - s + length);
}
const payload = b.subarray(i, i + length);
i += length;
n -= length;
if (mask) {
for (let i2 = 0; i2 < length; i2++) {
payload[i2] ^= mask[i2 & 3];
}
}
state.start = i;
return new Frame(opcode, payload, { fin, rsv1, rsv2, rsv3, mask });
};
}
});
// ../../node_modules/bare-ws/lib/socket.js
var require_socket2 = __commonJS({
"../../node_modules/bare-ws/lib/socket.js"(exports, module) {
var { Duplex } = require_bare_stream();
var http = require_bare_http1();
var https = require_bare_https();
var crypto = require_bare_crypto();
var { GUID, opcode } = require_constants14();
var errors = require_errors17();
var Frame = require_frame();
var CLOSE = new Frame(opcode.CLOSE).toBuffer();
module.exports = exports = class WebSocket extends Duplex {
constructor(url, opts = {}) {
if (typeof url === "string") url = new URL(url);
if (isURL(url)) {
opts = opts ? { ...opts } : {};
opts.host = url.hostname;
opts.path = url.pathname + url.search;
opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url);
opts.secure = url.protocol === "https:" || url.protocol === "wss:";
} else {
opts = url ? { ...url } : {};
opts.host = opts.hostname || opts.host;
opts.port = typeof opts.port === "string" ? parseInt(opts.port, 10) : opts.port;
}
const { isServer = false, socket = null } = opts;
super({ eagerOpen: true });
this._socket = null;
this._isServer = isServer;
this._mask = isServer ? null : Buffer.allocUnsafe(4);
this._fragments = [];
this._pendingOpen = null;
this._pendingWrite = null;
this._buffer = [];
this._buffered = 0;
this._frame = -1;
if (socket !== null) this._attach(socket);
else this._connect(opts);
}
ping(data) {
if (this._socket === null) throw errors.NOT_CONNECTED();
if (typeof data === "string") data = Buffer.from(data);
this._socket.write(new Frame(opcode.PING, data, { mask: this._mask }).toBuffer());
}
pong(data) {
if (this._socket === null) throw errors.NOT_CONNECTED();
if (typeof data === "string") data = Buffer.from(data);
this._socket.write(new Frame(opcode.PONG, data, { mask: this._mask }).toBuffer());
}
_attach(socket) {
this._socket = socket;
this._socket.on("error", this._onerror.bind(this)).on("close", this._onclose.bind(this)).on("data", this._ondata.bind(this)).on("drain", this._ondrain.bind(this));
}
_connect(opts) {
const request = opts.secure ? https.request : http.request;
const req = request(opts);
exports.handshake(req, (err) => {
const cb = this._pendingOpen;
this._pendingOpen = null;
if (err) req.socket.destroy();
else this._attach(req.socket);
cb(err);
});
}
_onerror(err) {
this.destroy(err);
}
_onclose() {
this.destroy();
}
_ondata(data) {
this._buffer.push(data);
this._buffered += data.byteLength;
while (this._frame === -1 || this._frame <= this._buffered) {
const buffer = this._buffer.length === 1 ? this._buffer[0] : Buffer.concat(this._buffer);
this._buffer = [buffer];
const state = { start: 0, end: buffer.length, buffer };
try {
this._onframe(Frame.decode(state));
} catch (err) {
if (err.code === "INCOMPLETE_FRAME") this._frame = err.status;
else this.destroy(err);
return;
}
this._buffered -= state.start;
this._buffer = this._buffered > 0 ? [buffer.subarray(state.start)] : [];
this._frame = -1;
}
}
_onframe(frame) {
if (frame.rsv1) throw errors.UNEXPECTED_RSV1();
if (frame.rsv2) throw errors.UNEXPECTED_RSV2();
if (frame.rsv3) throw errors.UNEXPECTED_RSV3();
if (frame.payload.length > 0 && !frame.mask === this._isServer) {
throw this._isServer ? errors.EXPECTED_MASK() : errors.UNEXPECTED_MASK();
}
if (frame.fin === false) {
if (this._fragments.push(frame) === 1) {
if (frame.opcode === opcode.CONTINUATION) {
throw errors.UNEXPECTED_CONTINUATION();
}
if (frame.opcode >= opcode.CLOSE) {
throw errors.UNEXPECTED_CONTROL();
}
return;
}
if (frame.opcode !== opcode.CONTINUATION) {
throw errors.EXPECTED_CONTINUATION();
}
return;
}
switch (frame.opcode) {
case opcode.CLOSE:
this.push(null);
this.end();
return;
case opcode.PING:
this.pong(frame.payload);
this.emit("ping", frame.payload);
return;
case opcode.PONG:
this.emit("pong", frame.payload);
return;
case opcode.CONTINUATION: {
if (this._fragments.length === 0) throw errors.UNEXPECTED_CONTINUATION();
frame.opcode = this._fragments[0].opcode;
const payloads = this._fragments.map((frame2) => frame2.payload);
payloads.push(frame.payload);
frame.payload = Buffer.concat(payloads);
this._fragments = [];
break;
}
default:
if (this._fragments.length > 0) throw errors.EXPECTED_CONTINUATION();
}
switch (frame.opcode) {
case opcode.TEXT:
case opcode.BINARY:
this.push(frame.payload);
break;
default:
throw errors.INVALID_OPCODE();
}
}
_ondrain() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_open(cb) {
if (this._socket === null) this._pendingOpen = cb;
else cb(null);
}
_write(data, encoding, cb) {
if (encoding !== "buffer" && encoding !== "utf8") {
return cb(errors.INVALID_ENCODING());
}
const frame = new Frame(encoding === "buffer" ? opcode.BINARY : opcode.TEXT, data, {
mask: this._mask
});
if (this._socket.write(frame.toBuffer())) cb(null);
else this._pendingWrite = cb;
}
_final(cb) {
this._socket.end(CLOSE);
cb(null);
}
_predestroy() {
if (!this._socket) return;
this._socket.destroy();
}
};
exports.handshake = function handshake(req, cb) {
const key = crypto.randomBytes(16).toString("base64");
req.headers = {
...req.headers,
Connection: "Upgrade",
Upgrade: "websocket",
"Sec-WebSocket-Version": 13,
"Sec-WebSocket-Key": key
};
req.on("upgrade", (res, socket, head) => {
if (res.headers.upgrade.toLowerCase() !== "websocket") {
return cb(errors.INVALID_UPGRADE_HEADER());
}
const digest = crypto.createHash("sha1").update(key).update(GUID).digest("base64");
if (res.headers["sec-websocket-accept"] !== digest) {
return cb(errors.INVALID_ACCEPT_HEADER());
}
if (head.byteLength) socket.unshift(head);
cb(null);
});
req.on("error", (err) => {
cb(errors.NETWORK_ERROR("Network error", err));
});
req.end();
};
function defaultPort(url) {
switch (url.protocol) {
case "ftp:":
return 21;
case "http:":
case "ws:":
return 80;
case "https:":
case "wss:":
return 443;
}
return null;
}
function isURL(url) {
return url !== null && typeof url === "object" && typeof url.protocol === "string" && typeof url.hostname === "string" && typeof url.pathname === "string" && typeof url.search === "string";
}
}
});
// ../../node_modules/bare-ws/lib/server.js
var require_server3 = __commonJS({
"../../node_modules/bare-ws/lib/server.js"(exports, module) {
var EventEmitter = require_bare_events();
var http = require_bare_http1();
var https = require_bare_https();
var crypto = require_bare_crypto();
var { GUID, EOL, EOF } = require_constants14();
var errors = require_errors17();
var WebSocket = require_socket2();
var EMPTY = Buffer.alloc(0);
var KEY = /^[+/0-9A-Za-z]{22}==$/;
module.exports = exports = class WebSocketServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const createServer = opts.secure ? https.createServer : http.createServer;
const {
server = createServer(opts, this._onrequest.bind(this)).listen(
opts,
this._onlistening.bind(this)
)
} = opts;
this._server = server;
this._server.on("upgrade", this._onupgrade.bind(this));
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return this._server.listening;
}
address() {
return this._server.address();
}
close(cb) {
this._server.close(cb);
return this;
}
ref() {
this._server.ref();
return this;
}
unref() {
this._server.unref();
return this;
}
_onlistening() {
this.emit("listening");
}
_onrequest(req, res) {
const body = http.constants.status[426];
res.writeHead(426, {
"Content-Type": "text/plain",
"Content-Length": body.length
});
res.end(body);
}
_onupgrade(req, socket, head) {
exports.handshake(req, socket, head, (err) => {
if (err) return socket.destroy(err);
this.emit("connection", new WebSocket({ socket, isServer: true }), req);
});
}
};
exports.handshake = function handshake(req, socket = req.socket, head = EMPTY, cb) {
if (typeof socket === "function") {
cb = socket;
socket = req.socket;
head = EMPTY;
} else if (typeof head === "function") {
cb = head;
head = EMPTY;
}
if (req.headers.upgrade.toLowerCase() !== "websocket") {
return cb(errors.INVALID_UPGRADE_HEADER());
}
const version = +req.headers["sec-websocket-version"];
if (version !== 8 && version !== 13) {
return cb(errors.INVALID_VERSION_HEADER());
}
const key = req.headers["sec-websocket-key"];
if (!key || !KEY.test(key)) {
return cb(errors.INVALID_KEY_HEADER());
}
const digest = crypto.createHash("sha1").update(key).update(GUID).digest("base64");
socket.write(
"HTTP/1.1 101 Web Socket Protocol Handshake" + EOL + "Upgrade: WebSocket" + EOL + "Connection: Upgrade" + EOL + `Sec-WebSocket-Accept: ${digest}` + EOF
);
if (head.byteLength) socket.unshift(head);
cb(null);
};
}
});
// ../../node_modules/bare-ws/index.js
var require_bare_ws = __commonJS({
"../../node_modules/bare-ws/index.js"(exports) {
exports.Server = require_server3();
exports.Socket = require_socket2();
}
});
// ../../node_modules/bare-ws/global.js
var require_global9 = __commonJS({
"../../node_modules/bare-ws/global.js"() {
var ws = require_bare_ws();
global.WebSocket = ws.Socket;
}
});
// ../../bare-lib-entry-bareNodeRuntime.js
var bare_lib_entry_bareNodeRuntime_exports = {};
__export(bare_lib_entry_bareNodeRuntime_exports, {
default: () => bare_lib_entry_bareNodeRuntime_default
});
// ../../node_modules/bare-node-runtime/global.js
require_global();
require_global2();
require_global3();
require_global4();
require_global5();
require_global6();
require_global7();
require_global8();
require_global9();
// ../../bare-lib-entry-bareNodeRuntime.js
var bare_lib_entry_bareNodeRuntime_default = true;
return __toCommonJS(bare_lib_entry_bareNodeRuntime_exports);
})();
;(function(){var g=globalThis;var s="__bare_os_stdlib__";g[s]=g[s]||{};var e=typeof __bare_os_bundle_exports__!=="undefined"?__bare_os_bundle_exports__:void 0;var v=e!=null&&typeof e==="object"&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;g[s]["bareNodeRuntime"]=v;})();