var __bare_os_bundle_exports__ = (() => { var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __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 __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // ../../node_modules/get-mime-type/index.js var require_get_mime_type = __commonJS({ "../../node_modules/get-mime-type/index.js"(exports, module) { var m = { ez: { type: "application/andrew-inset", charset: null }, appinstaller: { type: "application/appinstaller", charset: null }, aw: { type: "application/applixware", charset: null }, appx: { type: "application/appx", charset: null }, appxbundle: { type: "application/appxbundle", charset: null }, atom: { type: "application/atom+xml", charset: null }, atomcat: { type: "application/atomcat+xml", charset: null }, atomdeleted: { type: "application/atomdeleted+xml", charset: null }, atomsvc: { type: "application/atomsvc+xml", charset: null }, dwd: { type: "application/atsc-dwd+xml", charset: null }, held: { type: "application/atsc-held+xml", charset: null }, rsat: { type: "application/atsc-rsat+xml", charset: null }, aml: { type: "application/automationml-aml+xml", charset: null }, amlx: { type: "application/automationml-amlx+zip", charset: null }, bdoc: { type: "application/bdoc", charset: null }, xcs: { type: "application/calendar+xml", charset: null }, ccxml: { type: "application/ccxml+xml", charset: null }, cdfx: { type: "application/cdfx+xml", charset: null }, cdmia: { type: "application/cdmi-capability", charset: null }, cdmic: { type: "application/cdmi-container", charset: null }, cdmid: { type: "application/cdmi-domain", charset: null }, cdmio: { type: "application/cdmi-object", charset: null }, cdmiq: { type: "application/cdmi-queue", charset: null }, cpl: { type: "application/cpl+xml", charset: null }, cu: { type: "application/cu-seeme", charset: null }, cwl: { type: "application/cwl", charset: null }, mpd: { type: "application/dash+xml", charset: null }, mpp: { type: "application/dash-patch+xml", charset: null }, davmount: { type: "application/davmount+xml", charset: null }, dcm: { type: "application/dicom", charset: null }, dbk: { type: "application/docbook+xml", charset: null }, dssc: { type: "application/dssc+der", charset: null }, xdssc: { type: "application/dssc+xml", charset: null }, ecma: { type: "application/ecmascript", charset: null }, emma: { type: "application/emma+xml", charset: null }, emotionml: { type: "application/emotionml+xml", charset: null }, epub: { type: "application/epub+zip", charset: null }, exi: { type: "application/exi", charset: null }, exp: { type: "application/express", charset: null }, fdf: { type: "application/fdf", charset: null }, fdt: { type: "application/fdt+xml", charset: null }, pfr: { type: "application/font-tdpfr", charset: null }, geojson: { type: "application/geo+json", charset: null }, gml: { type: "application/gml+xml", charset: null }, gpx: { type: "application/gpx+xml", charset: null }, gxf: { type: "application/gxf", charset: null }, gz: { type: "application/gzip", charset: null }, hjson: { type: "application/hjson", charset: null }, stk: { type: "application/hyperstudio", charset: null }, ink: { type: "application/inkml+xml", charset: null }, inkml: null, ipfix: { type: "application/ipfix", charset: null }, its: { type: "application/its+xml", charset: null }, jar: { type: "application/java-archive", charset: null }, war: null, ear: null, ser: { type: "application/java-serialized-object", charset: null }, class: { type: "application/java-vm", charset: null }, js: { type: "application/javascript", charset: "utf-8" }, json: { type: "application/json", charset: "utf-8" }, map: null, json5: { type: "application/json5", charset: null }, jsonml: { type: "application/jsonml+json", charset: null }, jsonld: { type: "application/ld+json", charset: null }, lgr: { type: "application/lgr+xml", charset: null }, lostxml: { type: "application/lost+xml", charset: null }, hqx: { type: "application/mac-binhex40", charset: null }, cpt: { type: "application/mac-compactpro", charset: null }, mads: { type: "application/mads+xml", charset: null }, webmanifest: { type: "application/manifest+json", charset: "utf-8" }, mrc: { type: "application/marc", charset: null }, mrcx: { type: "application/marcxml+xml", charset: null }, ma: { type: "application/mathematica", charset: null }, nb: null, mb: null, mathml: { type: "application/mathml+xml", charset: null }, mbox: { type: "application/mbox", charset: null }, mpf: { type: "application/media-policy-dataset+xml", charset: null }, mscml: { type: "application/mediaservercontrol+xml", charset: null }, metalink: { type: "application/metalink+xml", charset: null }, meta4: { type: "application/metalink4+xml", charset: null }, mets: { type: "application/mets+xml", charset: null }, maei: { type: "application/mmt-aei+xml", charset: null }, musd: { type: "application/mmt-usd+xml", charset: null }, mods: { type: "application/mods+xml", charset: null }, m21: { type: "application/mp21", charset: null }, mp21: null, mp4: { type: "video/mp4", charset: null }, mpg4: null, mp4s: null, m4p: null, msix: { type: "application/msix", charset: null }, msixbundle: { type: "application/msixbundle", charset: null }, doc: { type: "application/msword", charset: null }, dot: null, mxf: { type: "application/mxf", charset: null }, nq: { type: "application/n-quads", charset: null }, nt: { type: "application/n-triples", charset: null }, cjs: { type: "application/javascript", charset: "utf-8" }, bin: { type: "application/octet-stream", charset: null }, dms: null, lrf: null, mar: null, so: null, dist: null, distz: null, pkg: null, bpk: null, dump: null, elc: null, deploy: null, exe: null, dll: null, deb: null, dmg: null, iso: null, img: null, msi: null, msp: null, msm: null, buffer: null, oda: { type: "application/oda", charset: null }, opf: { type: "application/oebps-package+xml", charset: null }, ogx: { type: "application/ogg", charset: null }, omdoc: { type: "application/omdoc+xml", charset: null }, onetoc: { type: "application/onenote", charset: null }, onetoc2: null, onetmp: null, onepkg: null, one: null, onea: null, oxps: { type: "application/oxps", charset: null }, relo: { type: "application/p2p-overlay+xml", charset: null }, xer: { type: "application/patch-ops-error+xml", charset: null }, pdf: { type: "application/pdf", charset: null }, pgp: { type: "application/pgp-encrypted", charset: null }, asc: { type: "application/pgp-keys", charset: null }, sig: { type: "application/pgp-signature", charset: null }, prf: { type: "application/pics-rules", charset: null }, p10: { type: "application/pkcs10", charset: null }, p7m: { type: "application/pkcs7-mime", charset: null }, p7c: null, p7s: { type: "application/pkcs7-signature", charset: null }, p8: { type: "application/pkcs8", charset: null }, ac: { type: "application/pkix-attr-cert", charset: null }, cer: { type: "application/pkix-cert", charset: null }, crl: { type: "application/pkix-crl", charset: null }, pkipath: { type: "application/pkix-pkipath", charset: null }, pki: { type: "application/pkixcmp", charset: null }, pls: { type: "application/pls+xml", charset: null }, ai: { type: "application/postscript", charset: null }, eps: null, ps: null, provx: { type: "application/provenance+xml", charset: null }, cww: { type: "application/prs.cww", charset: null }, xsf: { type: "application/prs.xsf+xml", charset: null }, pskcxml: { type: "application/pskc+xml", charset: null }, raml: { type: "application/raml+yaml", charset: null }, rdf: { type: "application/rdf+xml", charset: null }, owl: null, rif: { type: "application/reginfo+xml", charset: null }, rnc: { type: "application/relax-ng-compact-syntax", charset: null }, rl: { type: "application/resource-lists+xml", charset: null }, rld: { type: "application/resource-lists-diff+xml", charset: null }, rs: { type: "application/rls-services+xml", charset: null }, rapd: { type: "application/route-apd+xml", charset: null }, sls: { type: "application/route-s-tsid+xml", charset: null }, rusd: { type: "application/route-usd+xml", charset: null }, gbr: { type: "application/rpki-ghostbusters", charset: null }, mft: { type: "application/rpki-manifest", charset: null }, roa: { type: "application/rpki-roa", charset: null }, rsd: { type: "application/rsd+xml", charset: null }, rss: { type: "application/rss+xml", charset: null }, rtf: { type: "application/rtf", charset: null }, sbml: { type: "application/sbml+xml", charset: null }, scq: { type: "application/scvp-cv-request", charset: null }, scs: { type: "application/scvp-cv-response", charset: null }, spq: { type: "application/scvp-vp-request", charset: null }, spp: { type: "application/scvp-vp-response", charset: null }, sdp: { type: "application/sdp", charset: null }, senmlx: { type: "application/senml+xml", charset: null }, sensmlx: { type: "application/sensml+xml", charset: null }, setpay: { type: "application/set-payment-initiation", charset: null }, setreg: { type: "application/set-registration-initiation", charset: null }, shf: { type: "application/shf+xml", charset: null }, siv: { type: "application/sieve", charset: null }, sieve: null, smi: { type: "application/smil+xml", charset: null }, smil: null, rq: { type: "application/sparql-query", charset: null }, srx: { type: "application/sparql-results+xml", charset: null }, sql: { type: "application/sql", charset: null }, gram: { type: "application/srgs", charset: null }, grxml: { type: "application/srgs+xml", charset: null }, sru: { type: "application/sru+xml", charset: null }, ssdl: { type: "application/ssdl+xml", charset: null }, ssml: { type: "application/ssml+xml", charset: null }, swidtag: { type: "application/swid+xml", charset: null }, tei: { type: "application/tei+xml", charset: null }, teicorpus: null, tfi: { type: "application/thraud+xml", charset: null }, tsd: { type: "application/timestamped-data", charset: null }, toml: { type: "application/toml", charset: null }, trig: { type: "application/trig", charset: null }, ttml: { type: "application/ttml+xml", charset: null }, ubj: { type: "application/ubjson", charset: null }, rsheet: { type: "application/urc-ressheet+xml", charset: null }, td: { type: "application/urc-targetdesc+xml", charset: null }, "1km": { type: "application/vnd.1000minds.decision-model+xml", charset: null }, plb: { type: "application/vnd.3gpp.pic-bw-large", charset: null }, psb: { type: "application/vnd.3gpp.pic-bw-small", charset: null }, pvb: { type: "application/vnd.3gpp.pic-bw-var", charset: null }, tcap: { type: "application/vnd.3gpp2.tcap", charset: null }, pwn: { type: "application/vnd.3m.post-it-notes", charset: null }, aso: { type: "application/vnd.accpac.simply.aso", charset: null }, imp: { type: "application/vnd.accpac.simply.imp", charset: null }, acu: { type: "application/vnd.acucobol", charset: null }, atc: { type: "application/vnd.acucorp", charset: null }, acutc: null, air: { type: "application/vnd.adobe.air-application-installer-package+zip", charset: null }, fcdt: { type: "application/vnd.adobe.formscentral.fcdt", charset: null }, fxp: { type: "application/vnd.adobe.fxp", charset: null }, fxpl: null, xdp: { type: "application/vnd.adobe.xdp+xml", charset: null }, xfdf: { type: "application/vnd.adobe.xfdf", charset: null }, age: { type: "application/vnd.age", charset: null }, ahead: { type: "application/vnd.ahead.space", charset: null }, azf: { type: "application/vnd.airzip.filesecure.azf", charset: null }, azs: { type: "application/vnd.airzip.filesecure.azs", charset: null }, azw: { type: "application/vnd.amazon.ebook", charset: null }, acc: { type: "application/vnd.americandynamics.acc", charset: null }, ami: { type: "application/vnd.amiga.ami", charset: null }, apk: { type: "application/vnd.android.package-archive", charset: null }, cii: { type: "application/vnd.anser-web-certificate-issue-initiation", charset: null }, fti: { type: "application/vnd.anser-web-funds-transfer-initiation", charset: null }, atx: { type: "application/vnd.antix.game-component", charset: null }, mpkg: { type: "application/vnd.apple.installer+xml", charset: null }, key: { type: "application/vnd.apple.keynote", charset: null }, m3u8: { type: "application/vnd.apple.mpegurl", charset: null }, numbers: { type: "application/vnd.apple.numbers", charset: null }, pages: { type: "application/vnd.apple.pages", charset: null }, pkpass: { type: "application/vnd.apple.pkpass", charset: null }, swi: { type: "application/vnd.aristanetworks.swi", charset: null }, iota: { type: "application/vnd.astraea-software.iota", charset: null }, aep: { type: "application/vnd.audiograph", charset: null }, fbx: { type: "application/vnd.autodesk.fbx", charset: null }, bmml: { type: "application/vnd.balsamiq.bmml+xml", charset: null }, mpm: { type: "application/vnd.blueice.multipass", charset: null }, bmi: { type: "application/vnd.bmi", charset: null }, rep: { type: "application/vnd.businessobjects", charset: null }, cdxml: { type: "application/vnd.chemdraw+xml", charset: null }, mmd: { type: "application/vnd.chipnuts.karaoke-mmd", charset: null }, cdy: { type: "application/vnd.cinderella", charset: null }, csl: { type: "application/vnd.citationstyles.style+xml", charset: null }, cla: { type: "application/vnd.claymore", charset: null }, rp9: { type: "application/vnd.cloanto.rp9", charset: null }, c4g: { type: "application/vnd.clonk.c4group", charset: null }, c4d: null, c4f: null, c4p: null, c4u: null, c11amc: { type: "application/vnd.cluetrust.cartomobile-config", charset: null }, c11amz: { type: "application/vnd.cluetrust.cartomobile-config-pkg", charset: null }, csp: { type: "application/vnd.commonspace", charset: null }, cdbcmsg: { type: "application/vnd.contact.cmsg", charset: null }, cmc: { type: "application/vnd.cosmocaller", charset: null }, clkx: { type: "application/vnd.crick.clicker", charset: null }, clkk: { type: "application/vnd.crick.clicker.keyboard", charset: null }, clkp: { type: "application/vnd.crick.clicker.palette", charset: null }, clkt: { type: "application/vnd.crick.clicker.template", charset: null }, clkw: { type: "application/vnd.crick.clicker.wordbank", charset: null }, wbs: { type: "application/vnd.criticaltools.wbs+xml", charset: null }, pml: { type: "application/vnd.ctc-posml", charset: null }, ppd: { type: "application/vnd.cups-ppd", charset: null }, car: { type: "application/vnd.curl.car", charset: null }, pcurl: { type: "application/vnd.curl.pcurl", charset: null }, dart: { type: "application/vnd.dart", charset: null }, rdz: { type: "application/vnd.data-vision.rdz", charset: null }, dbf: { type: "application/vnd.dbf", charset: null }, dcmp: { type: "application/vnd.dcmp+xml", charset: null }, uvf: { type: "application/vnd.dece.data", charset: null }, uvvf: null, uvd: null, uvvd: null, uvt: { type: "application/vnd.dece.ttml+xml", charset: null }, uvvt: null, uvx: { type: "application/vnd.dece.unspecified", charset: null }, uvvx: null, uvz: { type: "application/vnd.dece.zip", charset: null }, uvvz: null, fe_launch: { type: "application/vnd.denovo.fcselayout-link", charset: null }, dna: { type: "application/vnd.dna", charset: null }, mlp: { type: "application/vnd.dolby.mlp", charset: null }, dpg: { type: "application/vnd.dpgraph", charset: null }, dfac: { type: "application/vnd.dreamfactory", charset: null }, kpxx: { type: "application/vnd.ds-keypoint", charset: null }, ait: { type: "application/vnd.dvb.ait", charset: null }, svc: { type: "application/vnd.dvb.service", charset: null }, geo: { type: "application/vnd.dynageo", charset: null }, mag: { type: "application/vnd.ecowin.chart", charset: null }, nml: { type: "application/vnd.enliven", charset: null }, esf: { type: "application/vnd.epson.esf", charset: null }, msf: { type: "application/vnd.epson.msf", charset: null }, qam: { type: "application/vnd.epson.quickanime", charset: null }, slt: { type: "application/vnd.epson.salt", charset: null }, ssf: { type: "application/vnd.epson.ssf", charset: null }, es3: { type: "application/vnd.eszigno3+xml", charset: null }, et3: null, ez2: { type: "application/vnd.ezpix-album", charset: null }, ez3: { type: "application/vnd.ezpix-package", charset: null }, mseed: { type: "application/vnd.fdsn.mseed", charset: null }, seed: { type: "application/vnd.fdsn.seed", charset: null }, dataless: null, gph: { type: "application/vnd.flographit", charset: null }, ftc: { type: "application/vnd.fluxtime.clip", charset: null }, fm: { type: "application/vnd.framemaker", charset: null }, frame: null, maker: null, book: null, fnc: { type: "application/vnd.frogans.fnc", charset: null }, ltf: { type: "application/vnd.frogans.ltf", charset: null }, fsc: { type: "application/vnd.fsc.weblaunch", charset: null }, oas: { type: "application/vnd.fujitsu.oasys", charset: null }, oa2: { type: "application/vnd.fujitsu.oasys2", charset: null }, oa3: { type: "application/vnd.fujitsu.oasys3", charset: null }, fg5: { type: "application/vnd.fujitsu.oasysgp", charset: null }, bh2: { type: "application/vnd.fujitsu.oasysprs", charset: null }, ddd: { type: "application/vnd.fujixerox.ddd", charset: null }, xdw: { type: "application/vnd.fujixerox.docuworks", charset: null }, xbd: { type: "application/vnd.fujixerox.docuworks.binder", charset: null }, fzs: { type: "application/vnd.fuzzysheet", charset: null }, txd: { type: "application/vnd.genomatix.tuxedo", charset: null }, ggb: { type: "application/vnd.geogebra.file", charset: null }, ggs: { type: "application/vnd.geogebra.slides", charset: null }, ggt: { type: "application/vnd.geogebra.tool", charset: null }, gex: { type: "application/vnd.geometry-explorer", charset: null }, gre: null, gxt: { type: "application/vnd.geonext", charset: null }, g2w: { type: "application/vnd.geoplan", charset: null }, g3w: { type: "application/vnd.geospace", charset: null }, gmx: { type: "application/vnd.gmx", charset: null }, gdoc: { type: "application/vnd.google-apps.document", charset: null }, gdraw: { type: "application/vnd.google-apps.drawing", charset: null }, gform: { type: "application/vnd.google-apps.form", charset: null }, gjam: { type: "application/vnd.google-apps.jam", charset: null }, gmap: { type: "application/vnd.google-apps.map", charset: null }, gslides: { type: "application/vnd.google-apps.presentation", charset: null }, gscript: { type: "application/vnd.google-apps.script", charset: null }, gsite: { type: "application/vnd.google-apps.site", charset: null }, gsheet: { type: "application/vnd.google-apps.spreadsheet", charset: null }, kml: { type: "application/vnd.google-earth.kml+xml", charset: null }, kmz: { type: "application/vnd.google-earth.kmz", charset: null }, xdcf: { type: "application/vnd.gov.sk.xmldatacontainer+xml", charset: null }, gqf: { type: "application/vnd.grafeq", charset: null }, gqs: null, gac: { type: "application/vnd.groove-account", charset: null }, ghf: { type: "application/vnd.groove-help", charset: null }, gim: { type: "application/vnd.groove-identity-message", charset: null }, grv: { type: "application/vnd.groove-injector", charset: null }, gtm: { type: "application/vnd.groove-tool-message", charset: null }, tpl: { type: "application/vnd.groove-tool-template", charset: null }, vcg: { type: "application/vnd.groove-vcard", charset: null }, hal: { type: "application/vnd.hal+xml", charset: null }, zmm: { type: "application/vnd.handheld-entertainment+xml", charset: null }, hbci: { type: "application/vnd.hbci", charset: null }, les: { type: "application/vnd.hhe.lesson-player", charset: null }, hpgl: { type: "application/vnd.hp-hpgl", charset: null }, hpid: { type: "application/vnd.hp-hpid", charset: null }, hps: { type: "application/vnd.hp-hps", charset: null }, jlt: { type: "application/vnd.hp-jlyt", charset: null }, pcl: { type: "application/vnd.hp-pcl", charset: null }, pclxl: { type: "application/vnd.hp-pclxl", charset: null }, "sfd-hdstx": { type: "application/vnd.hydrostatix.sof-data", charset: null }, mpy: { type: "application/vnd.ibm.minipay", charset: null }, afp: { type: "application/vnd.ibm.modcap", charset: null }, listafp: null, list3820: null, irm: { type: "application/vnd.ibm.rights-management", charset: null }, sc: { type: "application/vnd.ibm.secure-container", charset: null }, icc: { type: "application/vnd.iccprofile", charset: null }, icm: null, igl: { type: "application/vnd.igloader", charset: null }, ivp: { type: "application/vnd.immervision-ivp", charset: null }, ivu: { type: "application/vnd.immervision-ivu", charset: null }, igm: { type: "application/vnd.insors.igm", charset: null }, xpw: { type: "application/vnd.intercon.formnet", charset: null }, xpx: null, i2g: { type: "application/vnd.intergeo", charset: null }, qbo: { type: "application/vnd.intu.qbo", charset: null }, qfx: { type: "application/vnd.intu.qfx", charset: null }, rcprofile: { type: "application/vnd.ipunplugged.rcprofile", charset: null }, irp: { type: "application/vnd.irepository.package+xml", charset: null }, xpr: { type: "application/vnd.is-xpr", charset: null }, fcs: { type: "application/vnd.isac.fcs", charset: null }, jam: { type: "application/vnd.jam", charset: null }, rms: { type: "application/vnd.jcp.javame.midlet-rms", charset: null }, jisp: { type: "application/vnd.jisp", charset: null }, joda: { type: "application/vnd.joost.joda-archive", charset: null }, ktz: { type: "application/vnd.kahootz", charset: null }, ktr: null, karbon: { type: "application/vnd.kde.karbon", charset: null }, chrt: { type: "application/vnd.kde.kchart", charset: null }, kfo: { type: "application/vnd.kde.kformula", charset: null }, flw: { type: "application/vnd.kde.kivio", charset: null }, kon: { type: "application/vnd.kde.kontour", charset: null }, kpr: { type: "application/vnd.kde.kpresenter", charset: null }, kpt: null, ksp: { type: "application/vnd.kde.kspread", charset: null }, kwd: { type: "application/vnd.kde.kword", charset: null }, kwt: null, htke: { type: "application/vnd.kenameaapp", charset: null }, kia: { type: "application/vnd.kidspiration", charset: null }, kne: { type: "application/vnd.kinar", charset: null }, knp: null, skp: { type: "application/vnd.koan", charset: null }, skd: null, skt: null, skm: null, sse: { type: "application/vnd.kodak-descriptor", charset: null }, lasxml: { type: "application/vnd.las.las+xml", charset: null }, lbd: { type: "application/vnd.llamagraphics.life-balance.desktop", charset: null }, lbe: { type: "application/vnd.llamagraphics.life-balance.exchange+xml", charset: null }, "123": { type: "application/vnd.lotus-1-2-3", charset: null }, apr: { type: "application/vnd.lotus-approach", charset: null }, pre: { type: "application/vnd.lotus-freelance", charset: null }, nsf: { type: "application/vnd.lotus-notes", charset: null }, org: { type: "application/vnd.lotus-organizer", charset: null }, scm: { type: "application/vnd.lotus-screencam", charset: null }, lwp: { type: "application/vnd.lotus-wordpro", charset: null }, portpkg: { type: "application/vnd.macports.portpkg", charset: null }, mvt: { type: "application/vnd.mapbox-vector-tile", charset: null }, mcd: { type: "application/vnd.mcd", charset: null }, mc1: { type: "application/vnd.medcalcdata", charset: null }, cdkey: { type: "application/vnd.mediastation.cdkey", charset: null }, mwf: { type: "application/vnd.mfer", charset: null }, mfm: { type: "application/vnd.mfmp", charset: null }, flo: { type: "application/vnd.micrografx.flo", charset: null }, igx: { type: "application/vnd.micrografx.igx", charset: null }, mif: { type: "application/vnd.mif", charset: null }, daf: { type: "application/vnd.mobius.daf", charset: null }, dis: { type: "application/vnd.mobius.dis", charset: null }, mbk: { type: "application/vnd.mobius.mbk", charset: null }, mqy: { type: "application/vnd.mobius.mqy", charset: null }, msl: { type: "application/vnd.mobius.msl", charset: null }, plc: { type: "application/vnd.mobius.plc", charset: null }, txf: { type: "application/vnd.mobius.txf", charset: null }, mpn: { type: "application/vnd.mophun.application", charset: null }, mpc: { type: "application/vnd.mophun.certificate", charset: null }, xul: { type: "application/vnd.mozilla.xul+xml", charset: null }, cil: { type: "application/vnd.ms-artgalry", charset: null }, cab: { type: "application/vnd.ms-cab-compressed", charset: null }, xls: { type: "application/vnd.ms-excel", charset: null }, xlm: null, xla: null, xlc: null, xlt: null, xlw: null, xlam: { type: "application/vnd.ms-excel.addin.macroenabled.12", charset: null }, xlsb: { type: "application/vnd.ms-excel.sheet.binary.macroenabled.12", charset: null }, xlsm: { type: "application/vnd.ms-excel.sheet.macroenabled.12", charset: null }, xltm: { type: "application/vnd.ms-excel.template.macroenabled.12", charset: null }, eot: { type: "application/vnd.ms-fontobject", charset: null }, chm: { type: "application/vnd.ms-htmlhelp", charset: null }, ims: { type: "application/vnd.ms-ims", charset: null }, lrm: { type: "application/vnd.ms-lrm", charset: null }, thmx: { type: "application/vnd.ms-officetheme", charset: null }, msg: { type: "application/vnd.ms-outlook", charset: null }, cat: { type: "application/vnd.ms-pki.seccat", charset: null }, stl: { type: "application/vnd.ms-pki.stl", charset: null }, ppt: { type: "application/vnd.ms-powerpoint", charset: null }, pps: null, pot: null, ppam: { type: "application/vnd.ms-powerpoint.addin.macroenabled.12", charset: null }, pptm: { type: "application/vnd.ms-powerpoint.presentation.macroenabled.12", charset: null }, sldm: { type: "application/vnd.ms-powerpoint.slide.macroenabled.12", charset: null }, ppsm: { type: "application/vnd.ms-powerpoint.slideshow.macroenabled.12", charset: null }, potm: { type: "application/vnd.ms-powerpoint.template.macroenabled.12", charset: null }, mpt: null, vdx: { type: "application/vnd.ms-visio.viewer", charset: null }, docm: { type: "application/vnd.ms-word.document.macroenabled.12", charset: null }, dotm: { type: "application/vnd.ms-word.template.macroenabled.12", charset: null }, wps: { type: "application/vnd.ms-works", charset: null }, wks: null, wcm: null, wdb: null, wpl: { type: "application/vnd.ms-wpl", charset: null }, xps: { type: "application/vnd.ms-xpsdocument", charset: null }, mseq: { type: "application/vnd.mseq", charset: null }, mus: { type: "application/vnd.musician", charset: null }, msty: { type: "application/vnd.muvee.style", charset: null }, taglet: { type: "application/vnd.mynfc", charset: null }, bdo: { type: "application/vnd.nato.bindingdataobject+xml", charset: null }, nlu: { type: "application/vnd.neurolanguage.nlu", charset: null }, ntf: { type: "application/vnd.nitf", charset: null }, nitf: null, nnd: { type: "application/vnd.noblenet-directory", charset: null }, nns: { type: "application/vnd.noblenet-sealer", charset: null }, nnw: { type: "application/vnd.noblenet-web", charset: null }, ngdat: { type: "application/vnd.nokia.n-gage.data", charset: null }, "n-gage": { type: "application/vnd.nokia.n-gage.symbian.install", charset: null }, rpst: { type: "application/vnd.nokia.radio-preset", charset: null }, rpss: { type: "application/vnd.nokia.radio-presets", charset: null }, edm: { type: "application/vnd.novadigm.edm", charset: null }, edx: { type: "application/vnd.novadigm.edx", charset: null }, ext: { type: "application/vnd.novadigm.ext", charset: null }, odc: { type: "application/vnd.oasis.opendocument.chart", charset: null }, otc: { type: "application/vnd.oasis.opendocument.chart-template", charset: null }, odb: { type: "application/vnd.oasis.opendocument.database", charset: null }, odf: { type: "application/vnd.oasis.opendocument.formula", charset: null }, odft: { type: "application/vnd.oasis.opendocument.formula-template", charset: null }, odg: { type: "application/vnd.oasis.opendocument.graphics", charset: null }, otg: { type: "application/vnd.oasis.opendocument.graphics-template", charset: null }, odi: { type: "application/vnd.oasis.opendocument.image", charset: null }, oti: { type: "application/vnd.oasis.opendocument.image-template", charset: null }, odp: { type: "application/vnd.oasis.opendocument.presentation", charset: null }, otp: { type: "application/vnd.oasis.opendocument.presentation-template", charset: null }, ods: { type: "application/vnd.oasis.opendocument.spreadsheet", charset: null }, ots: { type: "application/vnd.oasis.opendocument.spreadsheet-template", charset: null }, odt: { type: "application/vnd.oasis.opendocument.text", charset: null }, odm: { type: "application/vnd.oasis.opendocument.text-master", charset: null }, ott: { type: "application/vnd.oasis.opendocument.text-template", charset: null }, oth: { type: "application/vnd.oasis.opendocument.text-web", charset: null }, xo: { type: "application/vnd.olpc-sugar", charset: null }, dd2: { type: "application/vnd.oma.dd2+xml", charset: null }, obgx: { type: "application/vnd.openblox.game+xml", charset: null }, oxt: { type: "application/vnd.openofficeorg.extension", charset: null }, osm: { type: "application/vnd.openstreetmap.data+xml", charset: null }, pptx: { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation", charset: null }, sldx: { type: "application/vnd.openxmlformats-officedocument.presentationml.slide", charset: null }, ppsx: { type: "application/vnd.openxmlformats-officedocument.presentationml.slideshow", charset: null }, potx: { type: "application/vnd.openxmlformats-officedocument.presentationml.template", charset: null }, xlsx: { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", charset: null }, xltx: { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.template", charset: null }, docx: { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", charset: null }, dotx: { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.template", charset: null }, mgp: { type: "application/vnd.osgeo.mapguide.package", charset: null }, dp: { type: "application/vnd.osgi.dp", charset: null }, esa: { type: "application/vnd.osgi.subsystem", charset: null }, pdb: { type: "application/vnd.palm", charset: null }, pqa: null, oprc: null, paw: { type: "application/vnd.pawaafile", charset: null }, str: { type: "application/vnd.pg.format", charset: null }, ei6: { type: "application/vnd.pg.osasli", charset: null }, efif: { type: "application/vnd.picsel", charset: null }, wg: { type: "application/vnd.pmi.widget", charset: null }, plf: { type: "application/vnd.pocketlearn", charset: null }, pbd: { type: "application/vnd.powerbuilder6", charset: null }, box: { type: "application/vnd.previewsystems.box", charset: null }, brushset: { type: "application/vnd.procrate.brushset", charset: null }, brush: { type: "application/vnd.procreate.brush", charset: null }, drm: { type: "application/vnd.procreate.dream", charset: null }, mgz: { type: "application/vnd.proteus.magazine", charset: null }, qps: { type: "application/vnd.publishare-delta-tree", charset: null }, ptid: { type: "application/vnd.pvi.ptid1", charset: null }, xhtm: { type: "application/vnd.pwg-xhtml-print+xml", charset: null }, qxd: { type: "application/vnd.quark.quarkxpress", charset: null }, qxt: null, qwd: null, qwt: null, qxl: null, qxb: null, rar: { type: "application/vnd.rar", charset: null }, bed: { type: "application/vnd.realvnc.bed", charset: null }, mxl: { type: "application/vnd.recordare.musicxml", charset: null }, musicxml: { type: "application/vnd.recordare.musicxml+xml", charset: null }, cryptonote: { type: "application/vnd.rig.cryptonote", charset: null }, cod: { type: "application/vnd.rim.cod", charset: null }, rm: { type: "application/vnd.rn-realmedia", charset: null }, rmvb: { type: "application/vnd.rn-realmedia-vbr", charset: null }, link66: { type: "application/vnd.route66.link66+xml", charset: null }, st: { type: "application/vnd.sailingtracker.track", charset: null }, see: { type: "application/vnd.seemail", charset: null }, sema: { type: "application/vnd.sema", charset: null }, semd: { type: "application/vnd.semd", charset: null }, semf: { type: "application/vnd.semf", charset: null }, ifm: { type: "application/vnd.shana.informed.formdata", charset: null }, itp: { type: "application/vnd.shana.informed.formtemplate", charset: null }, iif: { type: "application/vnd.shana.informed.interchange", charset: null }, ipk: { type: "application/vnd.shana.informed.package", charset: null }, twd: { type: "application/vnd.simtech-mindmapper", charset: null }, twds: null, mmf: { type: "application/vnd.smaf", charset: null }, teacher: { type: "application/vnd.smart.teacher", charset: null }, fo: { type: "application/vnd.software602.filler.form+xml", charset: null }, sdkm: { type: "application/vnd.solent.sdkm+xml", charset: null }, sdkd: null, dxp: { type: "application/vnd.spotfire.dxp", charset: null }, sfs: { type: "application/vnd.spotfire.sfs", charset: null }, sdc: { type: "application/vnd.stardivision.calc", charset: null }, sda: { type: "application/vnd.stardivision.draw", charset: null }, sdd: { type: "application/vnd.stardivision.impress", charset: null }, smf: { type: "application/vnd.stardivision.math", charset: null }, sdw: { type: "application/vnd.stardivision.writer", charset: null }, vor: null, sgl: { type: "application/vnd.stardivision.writer-global", charset: null }, smzip: { type: "application/vnd.stepmania.package", charset: null }, sm: { type: "application/vnd.stepmania.stepchart", charset: null }, wadl: { type: "application/vnd.sun.wadl+xml", charset: null }, sxc: { type: "application/vnd.sun.xml.calc", charset: null }, stc: { type: "application/vnd.sun.xml.calc.template", charset: null }, sxd: { type: "application/vnd.sun.xml.draw", charset: null }, std: { type: "application/vnd.sun.xml.draw.template", charset: null }, sxi: { type: "application/vnd.sun.xml.impress", charset: null }, sti: { type: "application/vnd.sun.xml.impress.template", charset: null }, sxm: { type: "application/vnd.sun.xml.math", charset: null }, sxw: { type: "application/vnd.sun.xml.writer", charset: null }, sxg: { type: "application/vnd.sun.xml.writer.global", charset: null }, stw: { type: "application/vnd.sun.xml.writer.template", charset: null }, sus: { type: "application/vnd.sus-calendar", charset: null }, susp: null, svd: { type: "application/vnd.svd", charset: null }, sis: { type: "application/vnd.symbian.install", charset: null }, sisx: null, xsm: { type: "application/vnd.syncml+xml", charset: "utf-8" }, bdm: { type: "application/vnd.syncml.dm+wbxml", charset: "utf-8" }, xdm: { type: "application/vnd.syncml.dm+xml", charset: "utf-8" }, ddf: { type: "application/vnd.syncml.dmddf+xml", charset: "utf-8" }, tao: { type: "application/vnd.tao.intent-module-archive", charset: null }, pcap: { type: "application/vnd.tcpdump.pcap", charset: null }, cap: null, dmp: null, tmo: { type: "application/vnd.tmobile-livetv", charset: null }, tpt: { type: "application/vnd.trid.tpt", charset: null }, mxs: { type: "application/vnd.triscape.mxs", charset: null }, tra: { type: "application/vnd.trueapp", charset: null }, ufd: { type: "application/vnd.ufdl", charset: null }, ufdl: null, utz: { type: "application/vnd.uiq.theme", charset: null }, umj: { type: "application/vnd.umajin", charset: null }, unityweb: { type: "application/vnd.unity", charset: null }, uoml: { type: "application/vnd.uoml+xml", charset: null }, uo: null, vcx: { type: "application/vnd.vcx", charset: null }, vsd: { type: "application/vnd.visio", charset: null }, vst: null, vss: null, vsw: null, vsdx: null, vtx: null, vis: { type: "application/vnd.visionary", charset: null }, vsf: { type: "application/vnd.vsf", charset: null }, wbxml: { type: "application/vnd.wap.wbxml", charset: "utf-8" }, wmlc: { type: "application/vnd.wap.wmlc", charset: null }, wmlsc: { type: "application/vnd.wap.wmlscriptc", charset: null }, wtb: { type: "application/vnd.webturbo", charset: null }, nbp: { type: "application/vnd.wolfram.player", charset: null }, wpd: { type: "application/vnd.wordperfect", charset: null }, wqd: { type: "application/vnd.wqd", charset: null }, stf: { type: "application/vnd.wt.stf", charset: null }, xar: { type: "application/vnd.xara", charset: null }, xfdl: { type: "application/vnd.xfdl", charset: null }, hvd: { type: "application/vnd.yamaha.hv-dic", charset: null }, hvs: { type: "application/vnd.yamaha.hv-script", charset: null }, hvp: { type: "application/vnd.yamaha.hv-voice", charset: null }, osf: { type: "application/vnd.yamaha.openscoreformat", charset: null }, osfpvg: { type: "application/vnd.yamaha.openscoreformat.osfpvg+xml", charset: null }, saf: { type: "application/vnd.yamaha.smaf-audio", charset: null }, spf: { type: "application/vnd.yamaha.smaf-phrase", charset: null }, cmp: { type: "application/vnd.yellowriver-custom-menu", charset: null }, zir: { type: "application/vnd.zul", charset: null }, zirz: null, zaz: { type: "application/vnd.zzazz.deck+xml", charset: null }, vxml: { type: "application/voicexml+xml", charset: null }, wasm: { type: "application/wasm", charset: null }, wif: { type: "application/watcherinfo+xml", charset: null }, wgt: { type: "application/widget", charset: null }, hlp: { type: "application/winhlp", charset: null }, wsdl: { type: "application/wsdl+xml", charset: null }, wspolicy: { type: "application/wspolicy+xml", charset: null }, "7z": { type: "application/x-7z-compressed", charset: null }, abw: { type: "application/x-abiword", charset: null }, ace: { type: "application/x-ace-compressed", charset: null }, arj: { type: "application/x-arj", charset: null }, aab: { type: "application/x-authorware-bin", charset: null }, x32: null, u32: null, vox: null, aam: { type: "application/x-authorware-map", charset: null }, aas: { type: "application/x-authorware-seg", charset: null }, bcpio: { type: "application/x-bcpio", charset: null }, torrent: { type: "application/x-bittorrent", charset: null }, blend: { type: "application/x-blender", charset: null }, blb: { type: "application/x-blorb", charset: null }, blorb: null, bz: { type: "application/x-bzip", charset: null }, bz2: { type: "application/x-bzip2", charset: null }, boz: null, cbr: { type: "application/x-cbr", charset: null }, cba: null, cbt: null, cbz: null, cb7: null, vcd: { type: "application/x-cdlink", charset: null }, cfs: { type: "application/x-cfs-compressed", charset: null }, chat: { type: "application/x-chat", charset: null }, pgn: { type: "application/x-chess-pgn", charset: null }, crx: { type: "application/x-chrome-extension", charset: null }, cco: { type: "application/x-cocoa", charset: null }, nsc: { type: "application/x-conference", charset: null }, cpio: { type: "application/x-cpio", charset: null }, csh: { type: "application/x-csh", charset: null }, udeb: null, dgc: { type: "application/x-dgc-compressed", charset: null }, dir: { type: "application/x-director", charset: null }, dcr: null, dxr: null, cst: null, cct: null, cxt: null, w3d: null, fgd: null, swa: null, wad: { type: "application/x-doom", charset: null }, ncx: { type: "application/x-dtbncx+xml", charset: null }, dtb: { type: "application/x-dtbook+xml", charset: null }, res: { type: "application/x-dtbresource+xml", charset: null }, dvi: { type: "application/x-dvi", charset: null }, evy: { type: "application/x-envoy", charset: null }, eva: { type: "application/x-eva", charset: null }, bdf: { type: "application/x-font-bdf", charset: null }, gsf: { type: "application/x-font-ghostscript", charset: null }, psf: { type: "application/x-font-linux-psf", charset: null }, pcf: { type: "application/x-font-pcf", charset: null }, snf: { type: "application/x-font-snf", charset: null }, pfa: { type: "application/x-font-type1", charset: null }, pfb: null, pfm: null, afm: null, arc: { type: "application/x-freearc", charset: null }, spl: { type: "application/x-futuresplash", charset: null }, gca: { type: "application/x-gca-compressed", charset: null }, ulx: { type: "application/x-glulx", charset: null }, gnumeric: { type: "application/x-gnumeric", charset: null }, gramps: { type: "application/x-gramps-xml", charset: null }, gtar: { type: "application/x-gtar", charset: null }, hdf: { type: "application/x-hdf", charset: null }, php: { type: "application/x-httpd-php", charset: null }, install: { type: "application/x-install-instructions", charset: null }, ipynb: { type: "application/x-ipynb+json", charset: null }, jardiff: { type: "application/x-java-archive-diff", charset: null }, jnlp: { type: "application/x-java-jnlp-file", charset: null }, kdbx: { type: "application/x-keepass2", charset: null }, latex: { type: "application/x-latex", charset: null }, luac: { type: "application/x-lua-bytecode", charset: null }, lzh: { type: "application/x-lzh-compressed", charset: null }, lha: null, run: { type: "application/x-makeself", charset: null }, mie: { type: "application/x-mie", charset: null }, prc: { type: "application/x-mobipocket-ebook", charset: null }, mobi: null, application: { type: "application/x-ms-application", charset: null }, lnk: { type: "application/x-ms-shortcut", charset: null }, wmd: { type: "application/x-ms-wmd", charset: null }, wmz: { type: "application/x-ms-wmz", charset: null }, xbap: { type: "application/x-ms-xbap", charset: null }, mdb: { type: "application/x-msaccess", charset: null }, obd: { type: "application/x-msbinder", charset: null }, crd: { type: "application/x-mscardfile", charset: null }, clp: { type: "application/x-msclip", charset: null }, com: null, bat: null, mvb: { type: "application/x-msmediaview", charset: null }, m13: null, m14: null, wmf: { type: "application/x-msmetafile", charset: null }, emf: null, emz: null, mny: { type: "application/x-msmoney", charset: null }, pub: { type: "application/x-mspublisher", charset: null }, scd: { type: "application/x-msschedule", charset: null }, trm: { type: "application/x-msterminal", charset: null }, wri: { type: "application/x-mswrite", charset: null }, nc: { type: "application/x-netcdf", charset: null }, cdf: null, pac: { type: "application/x-ns-proxy-autoconfig", charset: null }, nzb: { type: "application/x-nzb", charset: null }, pl: { type: "application/x-perl", charset: null }, pm: null, p12: { type: "application/x-pkcs12", charset: null }, pfx: null, p7b: { type: "application/x-pkcs7-certificates", charset: null }, spc: null, p7r: { type: "application/x-pkcs7-certreqresp", charset: null }, rpm: { type: "application/x-redhat-package-manager", charset: null }, ris: { type: "application/x-research-info-systems", charset: null }, sea: { type: "application/x-sea", charset: null }, sh: { type: "application/x-sh", charset: null }, shar: { type: "application/x-shar", charset: null }, swf: { type: "application/x-shockwave-flash", charset: null }, xap: { type: "application/x-silverlight-app", charset: null }, sit: { type: "application/x-stuffit", charset: null }, sitx: { type: "application/x-stuffitx", charset: null }, srt: { type: "application/x-subrip", charset: null }, sv4cpio: { type: "application/x-sv4cpio", charset: null }, sv4crc: { type: "application/x-sv4crc", charset: null }, t3: { type: "application/x-t3vm-image", charset: null }, gam: { type: "application/x-tads", charset: null }, tar: { type: "application/x-tar", charset: null }, tcl: { type: "application/x-tcl", charset: null }, tk: null, tex: { type: "application/x-tex", charset: null }, tfm: { type: "application/x-tex-tfm", charset: null }, texinfo: { type: "application/x-texinfo", charset: null }, texi: null, obj: { type: "application/x-tgif", charset: null }, ustar: { type: "application/x-ustar", charset: null }, hdd: { type: "application/x-virtualbox-hdd", charset: null }, ova: { type: "application/x-virtualbox-ova", charset: null }, ovf: { type: "application/x-virtualbox-ovf", charset: null }, vbox: { type: "application/x-virtualbox-vbox", charset: null }, "vbox-extpack": { type: "application/x-virtualbox-vbox-extpack", charset: null }, vdi: { type: "application/x-virtualbox-vdi", charset: null }, vhd: { type: "application/x-virtualbox-vhd", charset: null }, vmdk: { type: "application/x-virtualbox-vmdk", charset: null }, src: { type: "application/x-wais-source", charset: null }, webapp: { type: "application/x-web-app-manifest+json", charset: null }, der: { type: "application/x-x509-ca-cert", charset: null }, crt: null, pem: null, fig: { type: "application/x-xfig", charset: null }, xlf: { type: "application/x-xliff+xml", charset: null }, xpi: { type: "application/x-xpinstall", charset: null }, xz: { type: "application/x-xz", charset: null }, zip: { type: "application/x-zip-compressed", charset: null }, z1: { type: "application/x-zmachine", charset: null }, z2: null, z3: null, z4: null, z5: null, z6: null, z7: null, z8: null, xaml: { type: "application/xaml+xml", charset: null }, xav: { type: "application/xcap-att+xml", charset: null }, xca: { type: "application/xcap-caps+xml", charset: null }, xdf: { type: "application/xcap-diff+xml", charset: null }, xel: { type: "application/xcap-el+xml", charset: null }, xns: { type: "application/xcap-ns+xml", charset: null }, xenc: { type: "application/xenc+xml", charset: null }, xhtml: { type: "application/xhtml+xml", charset: null }, xht: null, xml: { type: "application/xml", charset: null }, xsl: null, xsd: null, rng: null, dtd: { type: "application/xml-dtd", charset: null }, xop: { type: "application/xop+xml", charset: null }, xpl: { type: "application/xproc+xml", charset: null }, xslt: null, xspf: { type: "application/xspf+xml", charset: null }, mxml: { type: "application/xv+xml", charset: null }, xhvml: null, xvml: null, xvm: null, yang: { type: "application/yang", charset: null }, yin: { type: "application/yin+xml", charset: null }, lottie: { type: "application/zip+dotlottie", charset: null }, "3gpp": { type: "audio/3gpp", charset: null }, adts: { type: "audio/aac", charset: null }, aac: null, adp: { type: "audio/adpcm", charset: null }, amr: { type: "audio/amr", charset: null }, au: { type: "audio/basic", charset: null }, snd: null, mid: { type: "audio/midi", charset: null }, midi: null, kar: null, rmi: null, mxmf: { type: "audio/mobile-xmf", charset: null }, mp3: { type: "audio/mp3", charset: null }, m4a: { type: "audio/mp4", charset: null }, mp4a: null, m4b: null, mpga: { type: "audio/mpeg", charset: null }, mp2: null, mp2a: null, m2a: null, m3a: null, oga: { type: "audio/ogg", charset: null }, ogg: null, spx: null, opus: null, s3m: { type: "audio/s3m", charset: null }, sil: { type: "audio/silk", charset: null }, uva: { type: "audio/vnd.dece.audio", charset: null }, uvva: null, eol: { type: "audio/vnd.digital-winds", charset: null }, dra: { type: "audio/vnd.dra", charset: null }, dts: { type: "audio/vnd.dts", charset: null }, dtshd: { type: "audio/vnd.dts.hd", charset: null }, lvp: { type: "audio/vnd.lucent.voice", charset: null }, pya: { type: "audio/vnd.ms-playready.media.pya", charset: null }, ecelp4800: { type: "audio/vnd.nuera.ecelp4800", charset: null }, ecelp7470: { type: "audio/vnd.nuera.ecelp7470", charset: null }, ecelp9600: { type: "audio/vnd.nuera.ecelp9600", charset: null }, rip: { type: "audio/vnd.rip", charset: null }, wav: { type: "audio/wav", charset: null }, weba: { type: "audio/webm", charset: null }, aif: { type: "audio/x-aiff", charset: null }, aiff: null, aifc: null, caf: { type: "audio/x-caf", charset: null }, flac: { type: "audio/x-flac", charset: null }, mka: { type: "audio/x-matroska", charset: null }, m3u: { type: "audio/x-mpegurl", charset: null }, wax: { type: "audio/x-ms-wax", charset: null }, wma: { type: "audio/x-ms-wma", charset: null }, ram: { type: "audio/x-pn-realaudio", charset: null }, ra: null, rmp: { type: "audio/x-pn-realaudio-plugin", charset: null }, xm: { type: "audio/xm", charset: null }, cdx: { type: "chemical/x-cdx", charset: null }, cif: { type: "chemical/x-cif", charset: null }, cmdf: { type: "chemical/x-cmdf", charset: null }, cml: { type: "chemical/x-cml", charset: null }, csml: { type: "chemical/x-csml", charset: null }, xyz: { type: "chemical/x-xyz", charset: null }, ttc: { type: "font/collection", charset: null }, otf: { type: "font/otf", charset: null }, ttf: { type: "font/ttf", charset: null }, woff: { type: "font/woff", charset: null }, woff2: { type: "font/woff2", charset: null }, exr: { type: "image/aces", charset: null }, apng: { type: "image/apng", charset: null }, avci: { type: "image/avci", charset: null }, avcs: { type: "image/avcs", charset: null }, avif: { type: "image/avif", charset: null }, bmp: { type: "image/bmp", charset: null }, dib: null, cgm: { type: "image/cgm", charset: null }, drle: { type: "image/dicom-rle", charset: null }, dpx: { type: "image/dpx", charset: null }, fits: { type: "image/fits", charset: null }, g3: { type: "image/g3fax", charset: null }, gif: { type: "image/gif", charset: null }, heic: { type: "image/heic", charset: null }, heics: { type: "image/heic-sequence", charset: null }, heif: { type: "image/heif", charset: null }, heifs: { type: "image/heif-sequence", charset: null }, hej2: { type: "image/hej2k", charset: null }, ief: { type: "image/ief", charset: null }, jaii: { type: "image/jaii", charset: null }, jais: { type: "image/jais", charset: null }, jls: { type: "image/jls", charset: null }, jp2: { type: "image/jp2", charset: null }, jpg2: null, jpg: { type: "image/jpeg", charset: null }, jpeg: null, jpe: null, jph: { type: "image/jph", charset: null }, jhc: { type: "image/jphc", charset: null }, jpm: { type: "image/jpm", charset: null }, jpgm: null, jpx: { type: "image/jpx", charset: null }, jpf: null, jxl: { type: "image/jxl", charset: null }, jxr: { type: "image/jxr", charset: null }, jxra: { type: "image/jxra", charset: null }, jxrs: { type: "image/jxrs", charset: null }, jxs: { type: "image/jxs", charset: null }, jxsc: { type: "image/jxsc", charset: null }, jxsi: { type: "image/jxsi", charset: null }, jxss: { type: "image/jxss", charset: null }, ktx: { type: "image/ktx", charset: null }, ktx2: { type: "image/ktx2", charset: null }, jfif: { type: "image/pjpeg", charset: null }, png: { type: "image/png", charset: null }, btif: { type: "image/prs.btif", charset: null }, btf: null, pti: { type: "image/prs.pti", charset: null }, sgi: { type: "image/sgi", charset: null }, svg: { type: "image/svg+xml", charset: null }, svgz: null, t38: { type: "image/t38", charset: null }, tif: { type: "image/tiff", charset: null }, tiff: null, tfx: { type: "image/tiff-fx", charset: null }, psd: { type: "image/vnd.adobe.photoshop", charset: null }, azv: { type: "image/vnd.airzip.accelerator.azv", charset: null }, uvi: { type: "image/vnd.dece.graphic", charset: null }, uvvi: null, uvg: null, uvvg: null, djvu: { type: "image/vnd.djvu", charset: null }, djv: null, sub: { type: "image/vnd.dvb.subtitle", charset: null }, dwg: { type: "image/vnd.dwg", charset: null }, dxf: { type: "image/vnd.dxf", charset: null }, fbs: { type: "image/vnd.fastbidsheet", charset: null }, fpx: { type: "image/vnd.fpx", charset: null }, fst: { type: "image/vnd.fst", charset: null }, mmr: { type: "image/vnd.fujixerox.edmics-mmr", charset: null }, rlc: { type: "image/vnd.fujixerox.edmics-rlc", charset: null }, ico: { type: "image/vnd.microsoft.icon", charset: null }, dds: { type: "image/vnd.ms-dds", charset: null }, mdi: { type: "image/vnd.ms-modi", charset: null }, wdp: { type: "image/vnd.ms-photo", charset: null }, npx: { type: "image/vnd.net-fpx", charset: null }, b16: { type: "image/vnd.pco.b16", charset: null }, tap: { type: "image/vnd.tencent.tap", charset: null }, vtf: { type: "image/vnd.valve.source.texture", charset: null }, wbmp: { type: "image/vnd.wap.wbmp", charset: null }, xif: { type: "image/vnd.xiff", charset: null }, pcx: { type: "image/vnd.zbrush.pcx", charset: null }, webp: { type: "image/webp", charset: null }, "3ds": { type: "image/x-3ds", charset: null }, dng: { type: "image/x-adobe-dng", charset: null }, ras: { type: "image/x-cmu-raster", charset: null }, cmx: { type: "image/x-cmx", charset: null }, fh: { type: "image/x-freehand", charset: null }, fhc: null, fh4: null, fh5: null, fh7: null, jng: { type: "image/x-jng", charset: null }, sid: { type: "image/x-mrsid-image", charset: null }, pic: { type: "image/x-pict", charset: null }, pct: null, pnm: { type: "image/x-portable-anymap", charset: null }, pbm: { type: "image/x-portable-bitmap", charset: null }, pgm: { type: "image/x-portable-graymap", charset: null }, ppm: { type: "image/x-portable-pixmap", charset: null }, rgb: { type: "image/x-rgb", charset: null }, tga: { type: "image/x-tga", charset: null }, xbm: { type: "image/x-xbitmap", charset: null }, xpm: { type: "image/x-xpixmap", charset: null }, xwd: { type: "image/x-xwindowdump", charset: null }, "disposition-notification": { type: "message/disposition-notification", charset: null }, u8msg: { type: "message/global", charset: null }, u8dsn: { type: "message/global-delivery-status", charset: null }, u8mdn: { type: "message/global-disposition-notification", charset: null }, u8hdr: { type: "message/global-headers", charset: null }, eml: { type: "message/rfc822", charset: null }, mime: null, mht: null, mhtml: null, wsc: { type: "message/vnd.wfa.wsc", charset: null }, "3mf": { type: "model/3mf", charset: null }, gltf: { type: "model/gltf+json", charset: null }, glb: { type: "model/gltf-binary", charset: null }, igs: { type: "model/iges", charset: null }, iges: null, jt: { type: "model/jt", charset: null }, msh: { type: "model/mesh", charset: null }, mesh: null, silo: null, mtl: { type: "model/mtl", charset: null }, step: { type: "model/step", charset: null }, stp: null, stpnc: null, p21: null, "210": null, stpx: { type: "model/step+xml", charset: null }, stpz: { type: "model/step+zip", charset: null }, stpxz: { type: "model/step-xml+zip", charset: null }, u3d: { type: "model/u3d", charset: null }, bary: { type: "model/vnd.bary", charset: null }, cld: { type: "model/vnd.cld", charset: null }, dae: { type: "model/vnd.collada+xml", charset: null }, dwf: { type: "model/vnd.dwf", charset: null }, gdl: { type: "model/vnd.gdl", charset: null }, gtw: { type: "model/vnd.gtw", charset: null }, mts: { type: "model/vnd.mts", charset: null }, ogex: { type: "model/vnd.opengex", charset: null }, x_b: { type: "model/vnd.parasolid.transmit.binary", charset: null }, x_t: { type: "model/vnd.parasolid.transmit.text", charset: null }, pyo: { type: "model/vnd.pytha.pyox", charset: null }, pyox: null, vds: { type: "model/vnd.sap.vds", charset: null }, usda: { type: "model/vnd.usda", charset: null }, usdz: { type: "model/vnd.usdz+zip", charset: null }, bsp: { type: "model/vnd.valve.source.compiled-map", charset: null }, vtu: { type: "model/vnd.vtu", charset: null }, wrl: { type: "model/vrml", charset: null }, vrml: null, x3db: { type: "model/x3d+binary", charset: null }, x3dbz: null, x3dv: { type: "model/x3d+vrml", charset: null }, x3dvz: null, x3d: { type: "model/x3d+xml", charset: null }, x3dz: null, appcache: { type: "text/cache-manifest", charset: null }, manifest: null, ics: { type: "text/calendar", charset: null }, ifb: null, coffee: { type: "text/coffeescript", charset: null }, litcoffee: null, css: { type: "text/css", charset: "utf-8" }, csv: { type: "text/csv", charset: null }, html: { type: "text/html", charset: null }, htm: null, shtml: null, jade: { type: "text/jade", charset: null }, mjs: null, jsx: { type: "text/jsx", charset: null }, less: { type: "text/less", charset: null }, md: { type: "text/markdown", charset: null }, markdown: null, mml: { type: "text/mathml", charset: null }, mdx: { type: "text/mdx", charset: null }, n3: { type: "text/n3", charset: "utf-8" }, txt: { type: "text/plain", charset: null }, text: null, conf: null, def: null, list: null, log: null, in: null, ini: null, dsc: { type: "text/prs.lines.tag", charset: null }, rtx: { type: "text/richtext", charset: null }, sgml: { type: "text/sgml", charset: null }, sgm: null, shex: { type: "text/shex", charset: null }, slim: { type: "text/slim", charset: null }, slm: null, spdx: { type: "text/spdx", charset: null }, stylus: { type: "text/stylus", charset: null }, styl: null, tsv: { type: "text/tab-separated-values", charset: null }, t: { type: "text/troff", charset: null }, tr: null, roff: null, man: null, me: null, ms: null, ttl: { type: "text/turtle", charset: "utf-8" }, uri: { type: "text/uri-list", charset: null }, uris: null, urls: null, vcard: { type: "text/vcard", charset: null }, curl: { type: "text/vnd.curl", charset: null }, dcurl: { type: "text/vnd.curl.dcurl", charset: null }, mcurl: { type: "text/vnd.curl.mcurl", charset: null }, scurl: { type: "text/vnd.curl.scurl", charset: null }, ged: { type: "text/vnd.familysearch.gedcom", charset: null }, fly: { type: "text/vnd.fly", charset: null }, flx: { type: "text/vnd.fmi.flexstor", charset: null }, gv: { type: "text/vnd.graphviz", charset: null }, "3dml": { type: "text/vnd.in3d.3dml", charset: null }, spot: { type: "text/vnd.in3d.spot", charset: null }, jad: { type: "text/vnd.sun.j2me.app-descriptor", charset: "utf-8" }, wml: { type: "text/vnd.wap.wml", charset: null }, wmls: { type: "text/vnd.wap.wmlscript", charset: null }, vtt: { type: "text/vtt", charset: "utf-8" }, wgsl: { type: "text/wgsl", charset: null }, s: { type: "text/x-asm", charset: null }, asm: null, c: { type: "text/x-c", charset: null }, cc: null, cxx: null, cpp: null, h: null, hh: null, dic: null, htc: { type: "text/x-component", charset: null }, f: { type: "text/x-fortran", charset: null }, for: null, f77: null, f90: null, hbs: { type: "text/x-handlebars-template", charset: null }, java: { type: "text/x-java-source", charset: null }, lua: { type: "text/x-lua", charset: null }, mkd: { type: "text/x-markdown", charset: null }, nfo: { type: "text/x-nfo", charset: null }, opml: { type: "text/x-opml", charset: null }, p: { type: "text/x-pascal", charset: null }, pas: null, pde: { type: "text/x-processing", charset: null }, sass: { type: "text/x-sass", charset: null }, scss: { type: "text/x-scss", charset: null }, etx: { type: "text/x-setext", charset: null }, sfv: { type: "text/x-sfv", charset: null }, ymp: { type: "text/x-suse-ymp", charset: null }, uu: { type: "text/x-uuencode", charset: null }, vcs: { type: "text/x-vcalendar", charset: null }, vcf: { type: "text/x-vcard", charset: null }, yaml: { type: "text/yaml", charset: null }, yml: null, "3gp": { type: "video/3gpp", charset: null }, "3g2": { type: "video/3gpp2", charset: null }, h261: { type: "video/h261", charset: null }, h263: { type: "video/h263", charset: null }, h264: { type: "video/h264", charset: null }, m4s: { type: "video/iso.segment", charset: null }, jpgv: { type: "video/jpeg", charset: null }, mj2: { type: "video/mj2", charset: null }, mjp2: null, ts: { type: "video/mp2t", charset: null }, m2t: null, m2ts: null, mp4v: null, mpeg: { type: "video/mpeg", charset: null }, mpg: null, mpe: null, m1v: null, m2v: null, ogv: { type: "video/ogg", charset: null }, qt: { type: "video/quicktime", charset: null }, mov: null, uvh: { type: "video/vnd.dece.hd", charset: null }, uvvh: null, uvm: { type: "video/vnd.dece.mobile", charset: null }, uvvm: null, uvp: { type: "video/vnd.dece.pd", charset: null }, uvvp: null, uvs: { type: "video/vnd.dece.sd", charset: null }, uvvs: null, uvv: { type: "video/vnd.dece.video", charset: null }, uvvv: null, dvb: { type: "video/vnd.dvb.file", charset: null }, fvt: { type: "video/vnd.fvt", charset: null }, mxu: { type: "video/vnd.mpegurl", charset: null }, m4u: null, pyv: { type: "video/vnd.ms-playready.media.pyv", charset: null }, uvu: { type: "video/vnd.uvvu.mp4", charset: null }, uvvu: null, viv: { type: "video/vnd.vivo", charset: null }, webm: { type: "video/webm", charset: null }, f4v: { type: "video/x-f4v", charset: null }, fli: { type: "video/x-fli", charset: null }, flv: { type: "video/x-flv", charset: null }, m4v: { type: "video/x-m4v", charset: null }, mkv: { type: "video/x-matroska", charset: null }, mk3d: null, mks: null, mng: { type: "video/x-mng", charset: null }, asf: { type: "video/x-ms-asf", charset: null }, asx: null, vob: { type: "video/x-ms-vob", charset: null }, wm: { type: "video/x-ms-wm", charset: null }, wmv: { type: "video/x-ms-wmv", charset: null }, wmx: { type: "video/x-ms-wmx", charset: null }, wvx: { type: "video/x-ms-wvx", charset: null }, avi: { type: "video/x-msvideo", charset: null }, movie: { type: "video/x-sgi-movie", charset: null }, smv: { type: "video/x-smv", charset: null }, ice: { type: "x-conference/x-cooltalk", charset: null } }; m.inkml = m.ink; m.war = m.jar; m.ear = m.jar; m.map = m.json; m.nb = m.ma; m.mb = m.ma; m.mp21 = m.m21; m.mpg4 = m.mp4; m.mp4s = m.mp4; m.m4p = m.mp4; m.dot = m.doc; m.dms = m.bin; m.lrf = m.bin; m.mar = m.bin; m.so = m.bin; m.dist = m.bin; m.distz = m.bin; m.pkg = m.bin; m.bpk = m.bin; m.dump = m.bin; m.elc = m.bin; m.deploy = m.bin; m.exe = m.bin; m.dll = m.bin; m.deb = m.bin; m.dmg = m.bin; m.iso = m.bin; m.img = m.bin; m.msi = m.bin; m.msp = m.bin; m.msm = m.bin; m.buffer = m.bin; m.onetoc2 = m.onetoc; m.onetmp = m.onetoc; m.onepkg = m.onetoc; m.one = m.onetoc; m.onea = m.onetoc; m.p7c = m.p7m; m.eps = m.ai; m.ps = m.ai; m.owl = m.rdf; m.sieve = m.siv; m.smil = m.smi; m.teicorpus = m.tei; m.acutc = m.atc; m.fxpl = m.fxp; m.c4d = m.c4g; m.c4f = m.c4g; m.c4p = m.c4g; m.c4u = m.c4g; m.uvvf = m.uvf; m.uvd = m.uvf; m.uvvd = m.uvf; m.uvvt = m.uvt; m.uvvx = m.uvx; m.uvvz = m.uvz; m.et3 = m.es3; m.dataless = m.seed; m.frame = m.fm; m.maker = m.fm; m.book = m.fm; m.gre = m.gex; m.gqs = m.gqf; m.listafp = m.afp; m.list3820 = m.afp; m.icm = m.icc; m.xpx = m.xpw; m.ktr = m.ktz; m.kpt = m.kpr; m.kwt = m.kwd; m.knp = m.kne; m.skd = m.skp; m.skt = m.skp; m.skm = m.skp; m.xlm = m.xls; m.xla = m.xls; m.xlc = m.xls; m.xlt = m.xls; m.xlw = m.xls; m.pps = m.ppt; m.pot = m.ppt; m.mpt = m.mpp; m.wks = m.wps; m.wcm = m.wps; m.wdb = m.wps; m.nitf = m.ntf; m.pqa = m.pdb; m.oprc = m.pdb; m.qxt = m.qxd; m.qwd = m.qxd; m.qwt = m.qxd; m.qxl = m.qxd; m.qxb = m.qxd; m.twds = m.twd; m.sdkd = m.sdkm; m.vor = m.sdw; m.susp = m.sus; m.sisx = m.sis; m.cap = m.pcap; m.dmp = m.pcap; m.ufdl = m.ufd; m.uo = m.uoml; m.vst = m.vsd; m.vss = m.vsd; m.vsw = m.vsd; m.vsdx = m.vsd; m.vtx = m.vsd; m.zirz = m.zir; m.x32 = m.aab; m.u32 = m.aab; m.vox = m.aab; m.blorb = m.blb; m.boz = m.bz2; m.cba = m.cbr; m.cbt = m.cbr; m.cbz = m.cbr; m.cb7 = m.cbr; m.udeb = m.deb; m.dcr = m.dir; m.dxr = m.dir; m.cst = m.dir; m.cct = m.dir; m.cxt = m.dir; m.w3d = m.dir; m.fgd = m.dir; m.swa = m.dir; m.pfb = m.pfa; m.pfm = m.pfa; m.afm = m.pfa; m.lha = m.lzh; m.mobi = m.prc; m.com = m.exe; m.bat = m.exe; m.m13 = m.mvb; m.m14 = m.mvb; m.emf = m.wmf; m.emz = m.wmf; m.cdf = m.nc; m.pm = m.pl; m.pfx = m.p12; m.spc = m.p7b; m.tk = m.tcl; m.texi = m.texinfo; m.crt = m.der; m.pem = m.der; m.z2 = m.z1; m.z3 = m.z1; m.z4 = m.z1; m.z5 = m.z1; m.z6 = m.z1; m.z7 = m.z1; m.z8 = m.z1; m.xht = m.xhtml; m.xsl = m.xml; m.xsd = m.xml; m.rng = m.xml; m.xslt = m.xsl; m.xhvml = m.mxml; m.xvml = m.mxml; m.xvm = m.mxml; m.aac = m.adts; m.snd = m.au; m.midi = m.mid; m.kar = m.mid; m.rmi = m.mid; m.mp4a = m.m4a; m.m4b = m.m4a; m.mp2 = m.mpga; m.mp2a = m.mpga; m.m2a = m.mpga; m.m3a = m.mpga; m.ogg = m.oga; m.spx = m.oga; m.opus = m.oga; m.uvva = m.uva; m.aiff = m.aif; m.aifc = m.aif; m.ra = m.ram; m.dib = m.bmp; m.jpg2 = m.jp2; m.jpeg = m.jpg; m.jpe = m.jpg; m.jpgm = m.jpm; m.jpf = m.jpx; m.btf = m.btif; m.svgz = m.svg; m.tiff = m.tif; m.uvvi = m.uvi; m.uvg = m.uvi; m.uvvg = m.uvi; m.djv = m.djvu; m.fhc = m.fh; m.fh4 = m.fh; m.fh5 = m.fh; m.fh7 = m.fh; m.pct = m.pic; m.mime = m.eml; m.mht = m.eml; m.mhtml = m.eml; m.iges = m.igs; m.mesh = m.msh; m.silo = m.msh; m.stp = m.step; m.stpnc = m.step; m.p21 = m.step; m["210"] = m.step; m.pyox = m.pyo; m.vrml = m.wrl; m.x3dbz = m.x3db; m.x3dvz = m.x3dv; m.x3dz = m.x3d; m.manifest = m.appcache; m.ifb = m.ics; m.litcoffee = m.coffee; m.htm = m.html; m.shtml = m.html; m.mjs = m.js; m.markdown = m.md; m.text = m.txt; m.conf = m.txt; m.def = m.txt; m.list = m.txt; m.log = m.txt; m.in = m.txt; m.ini = m.txt; m.sgm = m.sgml; m.slm = m.slim; m.styl = m.stylus; m.tr = m.t; m.roff = m.t; m.man = m.t; m.me = m.t; m.ms = m.t; m.uris = m.uri; m.urls = m.uri; m.asm = m.s; m.cc = m.c; m.cxx = m.c; m.cpp = m.c; m.h = m.c; m.hh = m.c; m.dic = m.c; m.for = m.f; m.f77 = m.f; m.f90 = m.f; m.pas = m.p; m.yml = m.yaml; m.mjp2 = m.mj2; m.m2t = m.ts; m.m2ts = m.ts; m.mp4v = m.mp4; m.mpg = m.mpeg; m.mpe = m.mpeg; m.m1v = m.mpeg; m.m2v = m.mpeg; m.mov = m.qt; m.uvvh = m.uvh; m.uvvm = m.uvm; m.uvvp = m.uvp; m.uvvs = m.uvs; m.uvvv = m.uvv; m.m4u = m.mxu; m.uvvu = m.uvu; m.mk3d = m.mkv; m.mks = m.mkv; m.asx = m.asf; module.exports = function getMimeType2(name, charset = true) { if (!name) return null; let e = m[name.slice(name.lastIndexOf(".") + 1).toLowerCase()]; if (!e) e = m.bin; return e.type + (charset && e.charset ? "; charset=" + e.charset : ""); }; } }); // ../../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/get-file-format/index.js var require_get_file_format = __commonJS({ "../../node_modules/get-file-format/index.js"(exports, module) { var b4a2 = require_b4a(); var ftyp = { "3g2": [ { sequence: [51, 103, 50] } // 3g2 ], "3gp": [ { sequence: [51, 103, 112] } // 3gp ], avif: [ { sequence: [97, 118, 105, 102] }, // avif { sequence: [97, 118, 105, 115] }, // avis { sequence: [97, 118, 105, 102, 115] } // avifs ], cr3: [ { sequence: [99, 114, 120] } // crx ], f4v: [ { sequence: [70, 52, 86] }, // F4V { sequence: [102, 52, 118] } // f4v ], heic: [ { sequence: [104, 101, 105, 99] }, // heic { sequence: [104, 101, 105, 120] }, // heix { sequence: [104, 101, 118, 99] }, // hevc { sequence: [109, 105, 102, 49] } // mif1 ], heics: [ { sequence: [104, 101, 118, 120] }, // hevx { sequence: [104, 101, 105, 115] }, // heis { sequence: [104, 101, 118, 115] } // hevs ], heifs: [ { sequence: [109, 115, 102, 49] } // msf1 ], m4a: [{ sequence: [77, 52, 65] }], // M4A m4b: [{ sequence: [77, 52, 66] }], // M4B m4p: [{ sequence: [77, 52, 80] }], // M4P m4v: [{ sequence: [77, 52, 86] }], // M4V mov: [{ sequence: [113, 116] }], // qt mp4: [ { sequence: [105, 115, 111, 109] }, // isom { sequence: [105, 115, 111, 50] }, // iso2 { sequence: [105, 115, 111, 51] }, // iso3 { sequence: [109, 112, 52, 49] }, // mp41 { sequence: [109, 112, 52, 50] } // mp42 ] }; var matroska = { mkv: [ { search: [66, 130], offset: 1, sequence: [109, 97, 116, 114, 111, 115, 107, 97] } ], webm: [ { search: [66, 130], offset: 1, sequence: [119, 101, 98, 109] } ] }; var riff = { avi: [{ sequence: [65, 86, 73, 32], offset: 8 }], webp: [{ sequence: [87, 69, 66, 80], offset: 8 }], wav: [{ sequence: [87, 65, 86, 69], offset: 8 }] }; var signature = { // containers ftyp: [{ sequence: [102, 116, 121, 112], offset: 4 }], matroska: [{ sequence: [26, 69, 223, 163] }], riff: [{ sequence: [82, 73, 70, 70] }], // standalone formats bmp: [{ sequence: [66, 77] }], ico: [{ sequence: [0, 0, 1, 0] }], jpg: [{ sequence: [255, 216, 255] }], gif: [{ sequence: [71, 73, 70, 56] }], pdf: [{ sequence: [37, 80, 68, 70, 45] }], png: [{ sequence: [137, 80, 78, 71, 13, 10, 26, 10] }], svg: [{ sequence: [60, 115, 118, 103] }], tiff: [ { sequence: [77, 77, 0, 42] }, { sequence: [73, 73, 42, 0] } ], xml: [ { sequence: [60, 63, 120, 109, 108] }, { sequence: [239, 187, 191, 60, 63, 120, 109, 108] }, { sequence: [254, 255, 0, 60, 0, 63] }, { sequence: [255, 254, 60, 0, 63, 0] } ] }; function head(buffer, end = 4096) { if (Buffer.isBuffer(buffer) || ArrayBuffer.isView(buffer)) { return buffer.subarray(0, end); } if (buffer instanceof ArrayBuffer) { return b4a2.from(buffer.slice(0, end)); } } function startsWith(buffer, sequence, offset = 0) { for (let i = 0; i < sequence.length; i++) { if (buffer[i + offset] !== sequence[i]) { return false; } } return true; } function endIndexOf(buffer, search) { let last = []; for (let i = 0; i < buffer.length; i++) { if (buffer[i] === search[last.length]) { last.push(buffer[i]); } else { last = []; } if (last.length === search.length) { return i + 1; } } return -1; } function lookup(types, buffer) { for (const type in types) { for (const { search, sequence, offset = 0 } of types[type]) { let searchIndex = 0; if (search) { searchIndex = endIndexOf(buffer, search); if (searchIndex === -1) return null; } if (startsWith(buffer, sequence, searchIndex + offset)) { return type; } } } return null; } var TAG_SVG_OPEN = b4a2.from(" 10, // \n 9, // \t 13, // \r CHAR_SLASH ]; function isLikelySvg(buffer) { const openIndex = b4a2.indexOf(buffer, TAG_SVG_OPEN); if (openIndex === -1) return false; const nextByte = buffer[openIndex + 4]; if (nextByte && !TAG_BOUNDARIES.includes(nextByte)) return false; const tagEnd = b4a2.indexOf(buffer, CHAR_GT, openIndex); if (tagEnd === -1) return false; return true; } function isobmff(buffer) { const size = buffer.subarray(0, 4).readUInt32BE(); const majorBrand = buffer.subarray(8, 12); const format = lookup(ftyp, majorBrand); if (format) { return format; } const compatibleCount = Math.max(0, (size - 16) / 4); for (let i = 0; i < compatibleCount; i++) { const index = 16 + i * 4; const compatible = buffer.subarray(index, index + 4); const format2 = lookup(ftyp, compatible); if (format2) { return format2; } } return null; } module.exports = function getFileFormat2(bytes) { const buffer = head(bytes); const format = lookup(signature, buffer); if (format === "ftyp") { return isobmff(buffer); } if (format === "matroska") { return lookup(matroska, buffer); } if (format === "riff") { return lookup(riff, buffer); } if (format === "xml") { if (isLikelySvg(bytes)) return "svg"; return "xml"; } return format || null; }; } }); // ../../node_modules/bare-media/types.js var IMAGE, supportedImageMimetypes, EXIF; var init_types = __esm({ "../../node_modules/bare-media/types.js"() { IMAGE = { AVIF: "image/avif", BMP: "image/bmp", GIF: "image/gif", HEIC: "image/heic", HEIF: "image/heif", JPEG: "image/jpeg", JPG: "image/jpg", PNG: "image/png", SVG_XML: "image/svg+xml", TIF: "image/tif", TIFF: "image/tiff", VND_MS_ICON: "image/vnd.microsoft.icon", WEBP: "image/webp", X_ICON: "image/x-icon", X_MS_BMP: "image/x-ms-bmp" }; supportedImageMimetypes = Object.values(IMAGE); EXIF = { ORIENTATION: { NORMAL: 1, MIRROR_HORIZONTAL: 2, ROTATE_180: 3, MIRROR_VERTICAL: 4, TRANSPOSE: 5, ROTATE_90: 6, TRANSVERSE: 7, ROTATE_270: 8 } }; } }); // ../../node_modules/bare-heif/binding.js var require_binding = __commonJS({ "../../node_modules/bare-heif/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-heif/index.js var require_bare_heif = __commonJS({ "../../node_modules/bare-heif/index.js"(exports) { var binding = require_binding(); exports.decode = function decode2(image2) { const { width, height, data } = binding.decode(image2); return { width, height, data: Buffer.from(data) }; }; } }); // ../../node_modules/bare-bmp/binding.js var require_binding2 = __commonJS({ "../../node_modules/bare-bmp/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-bmp/index.js var require_bare_bmp = __commonJS({ "../../node_modules/bare-bmp/index.js"(exports) { var binding = require_binding2(); exports.decode = function decode2(buffer) { const { width, height, data } = binding.decode(buffer); return { width, height, data: Buffer.from(data) }; }; exports.encode = function encode2(image2, opts = {}) { const buffer = binding.encode(image2, opts); return Buffer.from(buffer); }; exports.encodeAnimated = function encodeAnimated() { return binding.encodeAnimated(); }; } }); // ../../node_modules/bare-gif/binding.js var require_binding3 = __commonJS({ "../../node_modules/bare-gif/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-gif/index.js var require_bare_gif = __commonJS({ "../../node_modules/bare-gif/index.js"(exports) { var binding = require_binding3(); exports.decode = function decode2(image2) { const { width, height, data } = binding.decode(image2); return { width, height, data: Buffer.from(data) }; }; exports.decodeAnimated = function decodeAnimated(image2) { const { width, height, frames } = binding.decodeAnimated(image2); return { width, height, frames: frames.map((frame) => { const { width: width2, height: height2, timestamp, data } = frame; return { width: width2, height: height2, timestamp, data: Buffer.from(data) }; }) }; }; } }); // ../../node_modules/bare-jpeg/binding.js var require_binding4 = __commonJS({ "../../node_modules/bare-jpeg/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-jpeg/index.js var require_bare_jpeg = __commonJS({ "../../node_modules/bare-jpeg/index.js"(exports) { var binding = require_binding4(); var MARKER_PREFIX = 255; var SOI = 216; var EOI = 217; var SOS = 218; var APP0 = 224; var APP15 = 239; var COM = 254; exports.decode = function decode2(image2) { const { width, height, data } = binding.decode(image2); return { width, height, data: Buffer.from(data) }; }; exports.encode = function encode2(image2, opts = {}) { const { quality = 90 } = opts; const buffer = binding.encode(image2.data, image2.width, image2.height, clamp(quality, 0, 100)); return Buffer.from(buffer); }; exports.readHeader = function readHeader(image2) { const header = binding.readHeader(image2); return { ...header, markers: header.markers.map(({ marker, data }) => ({ marker, data: Buffer.from(data) })) }; }; exports.replaceMarkers = function replaceMarkers(image2, markers = []) { if (image2.length < 2 || image2[0] !== MARKER_PREFIX || image2[1] !== SOI) { throw new Error("Invalid JPEG"); } const output = [image2.subarray(0, 2)]; let offset = 2; let next = 0; let insertAt = 1; while (offset < image2.length) { const start = offset; while (offset < image2.length && image2[offset] === MARKER_PREFIX) { offset++; } if (offset >= image2.length) { throw new Error("Invalid JPEG"); } const marker = image2[offset]; if (marker === SOS || marker === EOI) { const leftover = []; while (next < markers.length) { leftover.push(buildSegment(markers[next++])); } if (leftover.length > 0) { output.splice(insertAt, 0, ...leftover); } output.push(image2.subarray(start)); return Buffer.concat(output); } if (offset + 2 >= image2.length) { throw new Error("Invalid JPEG"); } const length = image2.readUInt16BE(offset + 1); const end = offset + 1 + length; if (length < 2 || end > image2.length) { throw new Error("Invalid JPEG"); } if (marker >= APP0 && marker <= APP15 || marker === COM) { if (next < markers.length) { output.push(buildSegment(markers[next++])); insertAt = output.length; } } else { output.push(image2.subarray(start, end)); } offset = end; } throw new Error("Invalid JPEG"); }; function buildSegment(marker) { const payload = Buffer.from(marker.data); const segment = Buffer.allocUnsafe(payload.length + 4); segment[0] = MARKER_PREFIX; segment[1] = marker.marker; segment.writeUInt16BE(payload.length + 2, 2); payload.copy(segment, 4); return segment; } function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } } }); // ../../node_modules/bare-png/binding.js var require_binding5 = __commonJS({ "../../node_modules/bare-png/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-png/index.js var require_bare_png = __commonJS({ "../../node_modules/bare-png/index.js"(exports) { var binding = require_binding5(); exports.decode = function decode2(image2) { const { width, height, data } = binding.decode(image2); return { width, height, data: Buffer.from(data) }; }; exports.encode = function encode2(image2) { const buffer = binding.encode(image2.data, image2.width, image2.height); return Buffer.from(buffer); }; } }); // ../../node_modules/bare-svg/binding.js var require_binding6 = __commonJS({ "../../node_modules/bare-svg/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-svg/index.js var require_bare_svg = __commonJS({ "../../node_modules/bare-svg/index.js"(exports) { var binding = require_binding6(); exports.decode = function decode2(svg, opts = {}) { const result = binding.decode(svg, opts); return { width: result.width, height: result.height, data: Buffer.from(result.data) }; }; exports.encode = function encode2(rgba, opts = {}) { throw new Error("SVG encoding not supported"); }; exports.encodeAnimated = function encodeAnimated(frames, opts = {}) { throw new Error("Animated SVG not supported"); }; } }); // ../../node_modules/bare-tiff/binding.js var require_binding7 = __commonJS({ "../../node_modules/bare-tiff/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-tiff/index.js var require_bare_tiff = __commonJS({ "../../node_modules/bare-tiff/index.js"(exports) { var binding = require_binding7(); exports.decode = function decode2(image2) { const { width, height, data } = binding.decode(image2); return { width, height, data: Buffer.from(data) }; }; exports.encode = function encode2(image2) { const buffer = binding.encode(image2.data, image2.width, image2.height); return Buffer.from(buffer); }; } }); // ../../node_modules/bare-ico/binding.js var require_binding8 = __commonJS({ "../../node_modules/bare-ico/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-ico/index.js var require_bare_ico = __commonJS({ "../../node_modules/bare-ico/index.js"(exports) { var binding = require_binding8(); exports.decode = function decode2(ico, opts = {}) { const result = binding.decode(ico, opts); return { width: result.width, height: result.height, data: Buffer.from(result.data), sizes: result.sizes }; }; exports.encode = function encode2(rgba, opts = {}) { throw new Error("ICO encoding unavailable in this bundle"); }; exports.encodeAnimated = function encodeAnimated(frames, opts = {}) { throw new Error("Animated ICO not supported"); }; } }); // ../../node_modules/bare-webp/binding.js var require_binding9 = __commonJS({ "../../node_modules/bare-webp/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-webp/index.js var require_bare_webp = __commonJS({ "../../node_modules/bare-webp/index.js"(exports) { var binding = require_binding9(); exports.decode = function decode2(image2) { const { width, height, data } = binding.decode(image2); return { width, height, data: Buffer.from(data) }; }; exports.decodeAnimated = function decodeAnimated(image2) { const decoder = binding.animatedDecoderInit(image2); const { width, height, loops } = binding.animatedDecoderGetInfo(decoder); const frames = { next() { const frame = binding.animatedDecoderGetNextFrame( decoder, image2 // Keep a reference for lifetime management ); if (frame === null) { return { done: true }; } const { data, timestamp } = frame; return { done: false, value: { width, height, timestamp, data: Buffer.from(data) } }; }, [Symbol.iterator]() { return frames; } }; return { width, height, loops, frames }; }; exports.encode = function encode2(image2, opts = {}) { const { quality = 90 } = opts; const buffer = binding.encode(image2.data, image2.width, image2.height, clamp(quality, 0, 100)); return Buffer.from(buffer); }; exports.encodeAnimated = function encodeAnimated(image2, opts = {}) { const { quality = 90 } = opts; const encoder = binding.animatedEncoderInit(image2.width, image2.height); for (const { data, timestamp } of image2.frames) { binding.animatedEncoderAddFrame( encoder, data, image2.width, image2.height, clamp(quality, 0, 100), timestamp ); } return Buffer.from(binding.animatedEncoderAssemble(encoder)); }; function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } } }); // ../../node_modules/bare-ffmpeg/binding.js var require_binding10 = __commonJS({ "../../node_modules/bare-ffmpeg/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-ffmpeg/lib/errors.js var require_errors = __commonJS({ "../../node_modules/bare-ffmpeg/lib/errors.js"(exports, module) { module.exports = class FFmpegError extends Error { constructor(msg, code, fn = FFmpegError) { super(`${code}: ${msg}`); this.code = code; if (Error.captureStackTrace) { Error.captureStackTrace(this, fn); } } get name() { return "FFmpegError"; } static UNKNOWN_PIXEL_FORMAT(msg) { return new FFmpegError(msg, "UNKNOWN_PIXEL_FORMAT", FFmpegError.UNKNOWN_PIXEL_FORMAT); } static UNKNOWN_SAMPLE_FORMAT(msg) { return new FFmpegError(msg, "UNKNOWN_SAMPLE_FORMAT", FFmpegError.UNKNOWN_SAMPLE_FORMAT); } static UNKNOWN_CHANNEL_LAYOUT(msg) { return new FFmpegError(msg, "UNKNOWN_CHANNEL_LAYOUT", FFmpegError.UNKNOWN_CHANNEL_LAYOUT); } }; } }); // ../../node_modules/bare-ffmpeg/lib/constants.js var require_constants = __commonJS({ "../../node_modules/bare-ffmpeg/lib/constants.js"(exports, module) { var binding = require_binding10(); var errors = require_errors(); function makeTag(a, b, c, d) { return a.charCodeAt(0) | b.charCodeAt(0) << 8 | c.charCodeAt(0) << 16 | d.charCodeAt(0) << 24; } module.exports = exports = { codecs: { MJPEG: binding.AV_CODEC_ID_MJPEG, H264: binding.AV_CODEC_ID_H264, AVC: binding.AV_CODEC_ID_H264, // Alias for H264 AAC: binding.AV_CODEC_ID_AAC, OPUS: binding.AV_CODEC_ID_OPUS, AV1: binding.AV_CODEC_ID_AV1, FLAC: binding.AV_CODEC_ID_FLAC, MP3: binding.AV_CODEC_ID_MP3, H265: binding.AV_CODEC_ID_HEVC, HEVC: binding.AV_CODEC_ID_HEVC, VP8: binding.AV_CODEC_ID_VP8, VP9: binding.AV_CODEC_ID_VP9, VORBIS: binding.AV_CODEC_ID_VORBIS, PCM_S16LE: binding.AV_CODEC_ID_PCM_S16LE, PCM_S16BE: binding.AV_CODEC_ID_PCM_S16BE, PCM_U8: binding.AV_CODEC_ID_PCM_U8, PCM_ALAW: binding.AV_CODEC_ID_PCM_ALAW, PCM_MULAW: binding.AV_CODEC_ID_PCM_MULAW }, tags: { MJPEG: makeTag("M", "J", "P", "G"), AV1: makeTag("A", "V", "0", "1"), H264: makeTag("H", "2", "6", "4"), AAC: 255, FLAC: 61868, MP3: 85 }, profiles: { H264_MAIN: binding.AV_PROFILE_H264_MAIN }, levels: { UNKNOWN: binding.AV_LEVEL_UNKNOWN }, pixelFormats: { NONE: binding.AV_PIX_FMT_NONE, RGBA: binding.AV_PIX_FMT_RGBA, RGB24: binding.AV_PIX_FMT_RGB24, YUVJ420P: binding.AV_PIX_FMT_YUVJ420P, UYVY422: binding.AV_PIX_FMT_UYVY422, YUV420P: binding.AV_PIX_FMT_YUV420P, NV12: binding.AV_PIX_FMT_NV12, NV21: binding.AV_PIX_FMT_NV21, NV24: binding.AV_PIX_FMT_NV24, VIDEOTOOLBOX: binding.AV_PIX_FMT_VIDEOTOOLBOX }, mediaTypes: { UNKNOWN: binding.AVMEDIA_TYPE_UNKNOWN, VIDEO: binding.AVMEDIA_TYPE_VIDEO, AUDIO: binding.AVMEDIA_TYPE_AUDIO, DATA: binding.AVMEDIA_TYPE_DATA, SUBTITLE: binding.AVMEDIA_TYPE_SUBTITLE, ATTACHEMENT: binding.AVMEDIA_TYPE_ATTACHMENT, NB: binding.AVMEDIA_TYPE_NB }, sampleFormats: { NONE: binding.AV_SAMPLE_FMT_NONE, U8: binding.AV_SAMPLE_FMT_U8, S16: binding.AV_SAMPLE_FMT_S16, S32: binding.AV_SAMPLE_FMT_S32, S64: binding.AV_SAMPLE_FMT_S64, FLT: binding.AV_SAMPLE_FMT_FLT, DBL: binding.AV_SAMPLE_FMT_DBL, U8P: binding.AV_SAMPLE_FMT_U8P, S16P: binding.AV_SAMPLE_FMT_S16P, S32P: binding.AV_SAMPLE_FMT_S32P, S64P: binding.AV_SAMPLE_FMT_S64P, FLTP: binding.AV_SAMPLE_FMT_FLTP, DBLP: binding.AV_SAMPLE_FMT_DBLP, NB: binding.AV_SAMPLE_FMT_NB }, channelLayouts: { MONO: binding.AV_CH_LAYOUT_MONO, STEREO: binding.AV_CH_LAYOUT_STEREO, QUAD: binding.AV_CH_LAYOUT_QUAD, SURROUND: binding.AV_CH_LAYOUT_SURROUND, 21: binding.AV_CH_LAYOUT_2POINT1, 50: binding.AV_CH_LAYOUT_5POINT0, 51: binding.AV_CH_LAYOUT_5POINT1, 71: binding.AV_CH_LAYOUT_7POINT1, // Aliases 2.1: binding.AV_CH_LAYOUT_2POINT1, "5.0": binding.AV_CH_LAYOUT_5POINT0, 5.1: binding.AV_CH_LAYOUT_5POINT1, 7.1: binding.AV_CH_LAYOUT_7POINT1 }, pictureTypes: { NONE: binding.AV_PICTURE_TYPE_NONE, I: binding.AV_PICTURE_TYPE_I, P: binding.AV_PICTURE_TYPE_P, B: binding.AV_PICTURE_TYPE_B, S: binding.AV_PICTURE_TYPE_S, SI: binding.AV_PICTURE_TYPE_SI, SP: binding.AV_PICTURE_TYPE_SP, BI: binding.AV_PICTURE_TYPE_BI }, logLevels: { QUIET: binding.AV_LOG_QUIET, PANIC: binding.AV_LOG_PANIC, FATAL: binding.AV_LOG_FATAL, ERROR: binding.AV_LOG_ERROR, WARNING: binding.AV_LOG_WARNING, INFO: binding.AV_LOG_INFO, VERBOSE: binding.AV_LOG_VERBOSE, DEBUG: binding.AV_LOG_DEBUG, TRACE: binding.AV_LOG_TRACE }, codecFlags: { COPY_OPAQUE: binding.AV_CODEC_FLAG_COPY_OPAQUE, FRAME_DURATION: binding.AV_CODEC_FLAG_FRAME_DURATION, PASS1: binding.AV_CODEC_FLAG_PASS1, PASS2: binding.AV_CODEC_FLAG_PASS2, LOOP_FILTER: binding.AV_CODEC_FLAG_LOOP_FILTER, GRAY: binding.AV_CODEC_FLAG_GRAY, PSNR: binding.AV_CODEC_FLAG_PSNR, INTERLACED_DCT: binding.AV_CODEC_FLAG_INTERLACED_DCT, LOW_DELAY: binding.AV_CODEC_FLAG_LOW_DELAY, GLOBAL_HEADER: binding.AV_CODEC_FLAG_GLOBAL_HEADER, BITEXACT: binding.AV_CODEC_FLAG_BITEXACT, AC_PRED: binding.AV_CODEC_FLAG_AC_PRED, INTERLACED_ME: binding.AV_CODEC_FLAG_INTERLACED_ME, CLOSED_GOP: binding.AV_CODEC_FLAG_CLOSED_GOP }, formatFlags: { SHOW_IDS: binding.AVFMT_SHOW_IDS, GENERIC_INDEX: binding.AVFMT_GENERIC_INDEX, TS_DISCONT: binding.AVFMT_TS_DISCONT, NOBINSEARCH: binding.AVFMT_NOBINSEARCH, NOGENSEARCH: binding.AVFMT_NOGENSEARCH, NO_BYTE_SEEK: binding.AVFMT_NO_BYTE_SEEK, SEEK_TO_PTS: binding.AVFMT_SEEK_TO_PTS, GLOBALHEADER: binding.AVFMT_GLOBALHEADER, VARIABLE_FPS: binding.AVFMT_VARIABLE_FPS, NODIMENSIONS: binding.AVFMT_NODIMENSIONS, NOSTREAMS: binding.AVFMT_NOSTREAMS, TS_NONSTRICT: binding.AVFMT_TS_NONSTRICT, TS_NEGATIVE: binding.AVFMT_TS_NEGATIVE, NOFILE: binding.AVFMT_NOFILE, NEEDNUMBER: binding.AVFMT_NEEDNUMBER, NOTIMESTAMPS: binding.AVFMT_NOTIMESTAMPS }, seek: { SIZE: binding.AVSEEK_SIZE, FORCE: binding.AVSEEK_FORCE, CUR: binding.SEEK_CUR, SET: binding.SEEK_SET, END: binding.SEEK_END }, packetSideDataType: { PALETTE: binding.AV_PKT_DATA_PALETTE, NEW_EXTRADATA: binding.AV_PKT_DATA_NEW_EXTRADATA, PARAM_CHANGE: binding.AV_PKT_DATA_PARAM_CHANGE, H263_MB_INFO: binding.AV_PKT_DATA_H263_MB_INFO, REPLAYGAIN: binding.AV_PKT_DATA_REPLAYGAIN, DISPLAYMATRIX: binding.AV_PKT_DATA_DISPLAYMATRIX, STEREO3D: binding.AV_PKT_DATA_STEREO3D, AUDIO_SERVICE_TYPE: binding.AV_PKT_DATA_AUDIO_SERVICE_TYPE, QUALITY_STATS: binding.AV_PKT_DATA_QUALITY_STATS, FALLBACK_TRACK: binding.AV_PKT_DATA_FALLBACK_TRACK, CPB_PROPERTIES: binding.AV_PKT_DATA_CPB_PROPERTIES, SKIP_SAMPLES: binding.AV_PKT_DATA_SKIP_SAMPLES, JP_DUALMONO: binding.AV_PKT_DATA_JP_DUALMONO, STRINGS_METADATA: binding.AV_PKT_DATA_STRINGS_METADATA, SUBTITLE_POSITION: binding.AV_PKT_DATA_SUBTITLE_POSITION, MATROSKA_BLOCKADDITIONAL: binding.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, WEBVTT_IDENTIFIER: binding.AV_PKT_DATA_WEBVTT_IDENTIFIER, WEBVTT_SETTINGS: binding.AV_PKT_DATA_WEBVTT_SETTINGS, METADATA_UPDATE: binding.AV_PKT_DATA_METADATA_UPDATE, MPEGTS_STREAM_ID: binding.AV_PKT_DATA_MPEGTS_STREAM_ID, MASTERING_DISPLAY_METADATA: binding.AV_PKT_DATA_MASTERING_DISPLAY_METADATA, SPHERICAL: binding.AV_PKT_DATA_SPHERICAL, CONTENT_LIGHT_LEVEL: binding.AV_PKT_DATA_CONTENT_LIGHT_LEVEL, A53_CC: binding.AV_PKT_DATA_A53_CC, ENCRYPTION_INIT_INFO: binding.AV_PKT_DATA_ENCRYPTION_INIT_INFO, ENCRYPTION_INFO: binding.AV_PKT_DATA_ENCRYPTION_INFO, AFD: binding.AV_PKT_DATA_AFD, PRFT: binding.AV_PKT_DATA_PRFT, ICC_PROFILE: binding.AV_PKT_DATA_ICC_PROFILE, DOVI_CONF: binding.AV_PKT_DATA_DOVI_CONF, S12M_TIMECODE: binding.AV_PKT_DATA_S12M_TIMECODE, DYNAMIC_HDR10_PLUS: binding.AV_PKT_DATA_DYNAMIC_HDR10_PLUS, IAMF_MIX_GAIN_PARAM: binding.AV_PKT_DATA_IAMF_MIX_GAIN_PARAM, IAMF_DEMIXING_INFO_PARAM: binding.AV_PKT_DATA_IAMF_DEMIXING_INFO_PARAM, IAMF_RECON_GAIN_INFO_PARAM: binding.AV_PKT_DATA_IAMF_RECON_GAIN_INFO_PARAM, AMBIENT_VIEWING_ENVIRONMENT: binding.AV_PKT_DATA_AMBIENT_VIEWING_ENVIRONMENT, FRAME_CROPPING: binding.AV_PKT_DATA_FRAME_CROPPING, LCEVC: binding.AV_PKT_DATA_LCEVC, "3D_REFERENCE_DISPLAYS": binding.AV_PKT_DATA_3D_REFERENCE_DISPLAYS, RTCP_SR: binding.AV_PKT_DATA_RTCP_SR, NB: binding.AV_PKT_DATA_NB }, frameSideDataType: { PANSCAN: binding.AV_FRAME_DATA_PANSCAN, A53_CC: binding.AV_FRAME_DATA_A53_CC, STEREO3D: binding.AV_FRAME_DATA_STEREO3D, MATRIXENCODING: binding.AV_FRAME_DATA_MATRIXENCODING, DOWNMIX_INFO: binding.AV_FRAME_DATA_DOWNMIX_INFO, REPLAYGAIN: binding.AV_FRAME_DATA_REPLAYGAIN, DISPLAYMATRIX: binding.AV_FRAME_DATA_DISPLAYMATRIX, AFD: binding.AV_FRAME_DATA_AFD, MOTION_VECTORS: binding.AV_FRAME_DATA_MOTION_VECTORS, SKIP_SAMPLES: binding.AV_FRAME_DATA_SKIP_SAMPLES, AUDIO_SERVICE_TYPE: binding.AV_FRAME_DATA_AUDIO_SERVICE_TYPE, MASTERING_DISPLAY_METADATA: binding.AV_FRAME_DATA_MASTERING_DISPLAY_METADATA, GOP_TIMECODE: binding.AV_FRAME_DATA_GOP_TIMECODE, SPHERICAL: binding.AV_FRAME_DATA_SPHERICAL, CONTENT_LIGHT_LEVEL: binding.AV_FRAME_DATA_CONTENT_LIGHT_LEVEL, ICC_PROFILE: binding.AV_FRAME_DATA_ICC_PROFILE, S12M_TIMECODE: binding.AV_FRAME_DATA_S12M_TIMECODE, DYNAMIC_HDR_PLUS: binding.AV_FRAME_DATA_DYNAMIC_HDR_PLUS, REGIONS_OF_INTEREST: binding.AV_FRAME_DATA_REGIONS_OF_INTEREST, VIDEO_ENC_PARAMS: binding.AV_FRAME_DATA_VIDEO_ENC_PARAMS, SEI_UNREGISTERED: binding.AV_FRAME_DATA_SEI_UNREGISTERED, FILM_GRAIN_PARAMS: binding.AV_FRAME_DATA_FILM_GRAIN_PARAMS, DETECTION_BBOXES: binding.AV_FRAME_DATA_DETECTION_BBOXES, DOVI_RPU_BUFFER: binding.AV_FRAME_DATA_DOVI_RPU_BUFFER, DOVI_METADATA: binding.AV_FRAME_DATA_DOVI_METADATA, DYNAMIC_HDR_VIVID: binding.AV_FRAME_DATA_DYNAMIC_HDR_VIVID, AMBIENT_VIEWING_ENVIRONMENT: binding.AV_FRAME_DATA_AMBIENT_VIEWING_ENVIRONMENT, VIDEO_HINT: binding.AV_FRAME_DATA_VIDEO_HINT, LCEVC: binding.AV_FRAME_DATA_LCEVC, VIEW_ID: binding.AV_FRAME_DATA_VIEW_ID, "3D_REFERENCE_DISPLAYS": binding.AV_FRAME_DATA_3D_REFERENCE_DISPLAYS }, codecConfig: { PIX_FORMAT: binding.AV_CODEC_CONFIG_PIX_FORMAT, FRAME_RATE: binding.AV_CODEC_CONFIG_FRAME_RATE, SAMPLE_RATE: binding.AV_CODEC_CONFIG_SAMPLE_RATE, SAMPLE_FORMAT: binding.AV_CODEC_CONFIG_SAMPLE_FORMAT, CHANNEL_LAYOUT: binding.AV_CODEC_CONFIG_CHANNEL_LAYOUT, COLOR_RANGE: binding.AV_CODEC_CONFIG_COLOR_RANGE, COLOR_SPACE: binding.AV_CODEC_CONFIG_COLOR_SPACE }, rounding: { AV_ROUND_ZERO: binding.AV_ROUND_ZERO, AV_ROUND_INF: binding.AV_ROUND_INF, AV_ROUND_DOWN: binding.AV_ROUND_DOWN, AV_ROUND_UP: binding.AV_ROUND_UP, AV_ROUND_NEAR_INF: binding.AV_ROUND_NEAR_INF, AV_ROUND_PASS_MINMAX: binding.AV_ROUND_PASS_MINMAX }, optionFlags: { SEARCH_CHILDREN: binding.AV_OPT_SEARCH_CHILDREN, SEARCH_FAKE_OBJ: binding.AV_OPT_SEARCH_FAKE_OBJ, ALLOW_NULL: binding.AV_OPT_ALLOW_NULL, ARRAY_REPLACE: binding.AV_OPT_ARRAY_REPLACE, MULTI_COMPONENT_RANGE: binding.AV_OPT_MULTI_COMPONENT_RANGE }, hwDeviceTypes: { VIDEOTOOLBOX: binding.AV_HWDEVICE_TYPE_VIDEOTOOLBOX, CUDA: binding.AV_HWDEVICE_TYPE_CUDA, VAAPI: binding.AV_HWDEVICE_TYPE_VAAPI, DXVA2: binding.AV_HWDEVICE_TYPE_DXVA2, QSV: binding.AV_HWDEVICE_TYPE_QSV, D3D11VA: binding.AV_HWDEVICE_TYPE_D3D11VA }, hwFrameMapFlags: { NONE: 0, READ: binding.AV_HWFRAME_MAP_READ, WRITE: binding.AV_HWFRAME_MAP_WRITE, OVERWRITE: binding.AV_HWFRAME_MAP_OVERWRITE, DIRECT: binding.AV_HWFRAME_MAP_DIRECT }, colorSpace: { RGB: binding.AVCOL_SPC_RGB, BT709: binding.AVCOL_SPC_BT709, UNSPECIFIED: binding.AVCOL_SPC_UNSPECIFIED, RESERVED: binding.AVCOL_SPC_RESERVED, FCC: binding.AVCOL_SPC_FCC, BT470BG: binding.AVCOL_SPC_BT470BG, SMPTE170M: binding.AVCOL_SPC_SMPTE170M, SMPTE240M: binding.AVCOL_SPC_SMPTE240M, YCGCO: binding.AVCOL_SPC_YCGCO, YCOCG: binding.AVCOL_SPC_YCOCG, BT2020_NCL: binding.AVCOL_SPC_BT2020_NCL, BT2020_CL: binding.AVCOL_SPC_BT2020_CL, SMPTE2085: binding.AVCOL_SPC_SMPTE2085, CHROMA_DERIVED_NCL: binding.AVCOL_SPC_CHROMA_DERIVED_NCL, CHROMA_DERIVED_CL: binding.AVCOL_SPC_CHROMA_DERIVED_CL, ICTCP: binding.AVCOL_SPC_ICTCP, IPT_C2: binding.AVCOL_SPC_IPT_C2, YCGCO_RE: binding.AVCOL_SPC_YCGCO_RE, YCGCO_RO: binding.AVCOL_SPC_YCGCO_RO }, colorRange: { UNSPECIFIED: binding.AVCOL_RANGE_UNSPECIFIED, MPEG: binding.AVCOL_RANGE_MPEG, JPEG: binding.AVCOL_RANGE_JPEG }, colorPrimaries: { BT709: binding.AVCOL_PRI_BT709, UNSPECIFIED: binding.AVCOL_PRI_UNSPECIFIED, RESERVED: binding.AVCOL_PRI_RESERVED, BT470M: binding.AVCOL_PRI_BT470M, BT470BG: binding.AVCOL_PRI_BT470BG, SMPTE170M: binding.AVCOL_PRI_SMPTE170M, SMPTE240M: binding.AVCOL_PRI_SMPTE240M, FILM: binding.AVCOL_PRI_FILM, BT2020: binding.AVCOL_PRI_BT2020, SMPTE428: binding.AVCOL_PRI_SMPTE428, SMPTEST428_1: binding.AVCOL_PRI_SMPTEST428_1, SMPTE431: binding.AVCOL_PRI_SMPTE431, SMPTE432: binding.AVCOL_PRI_SMPTE432, EBU3213: binding.AVCOL_PRI_EBU3213, JEDEC_P22: binding.AVCOL_PRI_JEDEC_P22 }, colorTRC: { BT709: binding.AVCOL_TRC_BT709, UNSPECIFIED: binding.AVCOL_TRC_UNSPECIFIED, RESERVED: binding.AVCOL_TRC_RESERVED, GAMMA22: binding.AVCOL_TRC_GAMMA22, GAMMA28: binding.AVCOL_TRC_GAMMA28, SMPTE170M: binding.AVCOL_TRC_SMPTE170M, SMPTE240M: binding.AVCOL_TRC_SMPTE240M, LINEAR: binding.AVCOL_TRC_LINEAR, LOG: binding.AVCOL_TRC_LOG, LOG_SQRT: binding.AVCOL_TRC_LOG_SQRT, IEC61966_2_4: binding.AVCOL_TRC_IEC61966_2_4, BT1361_ECG: binding.AVCOL_TRC_BT1361_ECG, IEC61966_2_1: binding.AVCOL_TRC_IEC61966_2_1, BT2020_10: binding.AVCOL_TRC_BT2020_10, BT2020_12: binding.AVCOL_TRC_BT2020_12, SMPTE2084: binding.AVCOL_TRC_SMPTE2084, SMPTEST2084: binding.AVCOL_TRC_SMPTEST2084, SMPTE428: binding.AVCOL_TRC_SMPTE428, SMPTEST428_1: binding.AVCOL_TRC_SMPTEST428_1, ARIB_STD_B67: binding.AVCOL_TRC_ARIB_STD_B67 } }; exports.toPixelFormat = function toPixelFormat(format) { if (typeof format === "number") return format; if (typeof format === "string") { if (format in exports.pixelFormats === false) { throw errors.UNKNOWN_PIXEL_FORMAT(`Unknown pixel format '${format}'`); } return exports.pixelFormats[format]; } throw new TypeError( `Pixel format must be a number or string. Received ${typeof format} (${format})` ); }; exports.toSampleFormat = function toSampleFormat(format) { if (typeof format === "number") return format; if (typeof format === "string") { if (format in exports.sampleFormats === false) { throw errors.UNKNOWN_SAMPLE_FORMAT(`Unknown sample format '${format}'`); } return exports.sampleFormats[format]; } throw new TypeError( `Sample format must be a number or string. Received ${typeof format} (${format})` ); }; exports.toChannelLayout = function toChannelLayout(layout) { if (typeof layout === "number") return layout; if (typeof layout === "string") { if (layout in exports.channelLayouts === false) { throw errors.UNKNOWN_CHANNEL_LAYOUT(`Unknown channel layout '${layout}'`); } return exports.channelLayouts[layout]; } throw new TypeError( `Channel layout must be a number or string. Received ${typeof layout} (${layout})` ); }; exports.getSampleFormatName = function(sampleFormat) { return binding.getSampleFormatNameByID(sampleFormat); }; exports.getPixelFormatName = function(pixelFormat) { return binding.getPixelFormatNameByID(pixelFormat); }; exports.getColorSpaceName = function(colorSpace) { return binding.getColorSpaceNameByID(colorSpace); }; exports.toColorSpace = function(name) { return binding.getColorSpaceFromName(name); }; exports.getColorPrimariesName = function(colorPrimaries) { return binding.getColorPrimariesNameByID(colorPrimaries); }; exports.toColorPrimaries = function(name) { return binding.getColorPrimariesFromName(name); }; exports.getColorTransferName = function(colorTransfer) { return binding.getColorTransferNameByID(colorTransfer); }; exports.toColorTransfer = function(name) { return binding.getColorTransferFromName(name); }; } }); // ../../node_modules/bare-ffmpeg/lib/audio-fifo.js var require_audio_fifo = __commonJS({ "../../node_modules/bare-ffmpeg/lib/audio-fifo.js"(exports, module) { var binding = require_binding10(); var constants = require_constants(); module.exports = class FFmpegAudioFIFO { constructor(sampleFormat, channels, nbSamples) { sampleFormat = constants.toSampleFormat(sampleFormat); this._handle = binding.initAudioFifo(sampleFormat, channels, nbSamples); } destroy() { binding.destroyAudioFifo(this._handle); this._handle = null; } write(frame) { return binding.writeAudioFifo(this._handle, frame._handle); } read(frame, nbSamples) { return binding.readAudioFifo(this._handle, frame._handle, nbSamples); } peek(frame, nbSamples) { return binding.peekAudioFifo(this._handle, frame._handle, nbSamples); } drain(nbSamples) { return binding.drainAudioFifo(this._handle, nbSamples); } reset() { binding.resetAudioFifo(this._handle); } get size() { return binding.getAudioFifoSize(this._handle); } get space() { return binding.getAudioFifoSpace(this._handle); } [Symbol.dispose]() { this.destroy(); } }; } }); // ../../node_modules/bare-ffmpeg/lib/channel-layout.js var require_channel_layout = __commonJS({ "../../node_modules/bare-ffmpeg/lib/channel-layout.js"(exports, module) { var binding = require_binding10(); var constants = require_constants(); module.exports = class FFmpegChannelLayout { constructor(handle) { this._handle = handle; } get nbChannels() { return binding.getChannelLayoutNbChannels(this._handle); } get mask() { return binding.getChannelLayoutMask(this._handle); } static from(value) { if (typeof value === "string") value = constants.toChannelLayout(value); if (typeof value === "number") { value = binding.channelLayoutFromMask(value); } else if (typeof value === "object" && value !== null) { value = binding.copyChannelLayout(value._handle); } return new this(value); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegChannelLayout }, nbChannels: this.nbChannels }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/decoder.js var require_decoder = __commonJS({ "../../node_modules/bare-ffmpeg/lib/decoder.js"(exports, module) { var binding = require_binding10(); module.exports = class FFmpegDecoder { constructor(codec) { if (typeof codec === "string") { this._handle = binding.findDecoderByName(codec); } else { this._handle = binding.findDecoderByID(codec._id); } } }; } }); // ../../node_modules/bare-ffmpeg/lib/encoder.js var require_encoder = __commonJS({ "../../node_modules/bare-ffmpeg/lib/encoder.js"(exports, module) { var binding = require_binding10(); module.exports = class FFmpegEncoder { constructor(codec) { if (typeof codec === "string") { this._handle = binding.findEncoderByName(codec); } else { this._handle = binding.findEncoderByID(codec._id); } } }; } }); // ../../node_modules/bare-ffmpeg/lib/codec.js var require_codec = __commonJS({ "../../node_modules/bare-ffmpeg/lib/codec.js"(exports, module) { var Decoder = require_decoder(); var Encoder = require_encoder(); var constants = require_constants(); var binding = require_binding10(); var codecs2 = /* @__PURE__ */ new Map(); module.exports = class FFmpegCodec { constructor(id) { this._id = id; this._decoder = null; this._encoder = null; } get id() { return this._id; } get decoder() { if (this._decoder === null) this._decoder = new Decoder(this); return this._decoder; } get encoder() { if (this._encoder === null) this._encoder = new Encoder(this); return this._encoder; } get name() { if (Number.isInteger(this._id)) { return binding.getCodecNameByID(this._id); } } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegCodec }, id: this.id, name: this.name }; } /** @return {FFmpegCodec} */ static for(id) { let codec = codecs2.get(id); if (codec === void 0) { codec = new FFmpegCodec(id); codecs2.set(id, codec); } return codec; } static MJPEG = this.for(constants.codecs.MJPEG); static H264 = this.for(constants.codecs.H264); static AAC = this.for(constants.codecs.AAC); static OPUS = this.for(constants.codecs.OPUS); static AV1 = this.for(constants.codecs.AV1); static VP8 = this.for(constants.codecs.VP8); static VP9 = this.for(constants.codecs.VP9); }; } }); // ../../node_modules/bare-ffmpeg/lib/rational.js var require_rational = __commonJS({ "../../node_modules/bare-ffmpeg/lib/rational.js"(exports, module) { var binding = require_binding10(); var { AV_ROUND_NEAR_INF } = require_constants().rounding; module.exports = class FFmpegRational { constructor(numerator = 0, denominator = 1) { this.numerator = numerator; this.denominator = denominator; } get valid() { if (this.denominator < 0) return false; const n = this.toNumber(); if (Number.isNaN(n) || n === 0) return false; return true; } get uninitialized() { return this.numerator === 0 && this.denominator === 1; } toNumber() { return this.numerator / this.denominator; } equals(other) { return this.numerator === other.numerator && this.denominator === other.denominator; } static from(num) { const view = new Int32Array(binding.rationalD2Q(num)); return new FFmpegRational(view[0], view[1]); } static rescaleQ(n, src, dst, round = AV_ROUND_NEAR_INF) { if (src.equals(dst)) return n; return binding.rationalRescaleQ( n, src.numerator, src.denominator, dst.numerator, dst.denominator, round ); } }; } }); // ../../node_modules/bare-ffmpeg/lib/hw-device-context.js var require_hw_device_context = __commonJS({ "../../node_modules/bare-ffmpeg/lib/hw-device-context.js"(exports, module) { var binding = require_binding10(); module.exports = class HWDeviceContext { constructor(type, device = void 0, handle = void 0) { if (handle) { this._handle = handle; } else { this._handle = binding.initHWDeviceContext(type, device); } } static from(handle = null) { if (handle === null) return null; return new HWDeviceContext(null, void 0, handle); } destroy() { binding.destroyHWDeviceContext(this._handle); this._handle = null; } [Symbol.dispose]() { this.destroy(); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: HWDeviceContext } }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/codec-context.js var require_codec_context = __commonJS({ "../../node_modules/bare-ffmpeg/lib/codec-context.js"(exports, module) { var binding = require_binding10(); var Rational = require_rational(); var ChannelLayout = require_channel_layout(); var HWDeviceContext = require_hw_device_context(); var { codecConfig, optionFlags } = require_constants(); module.exports = class FFmpegCodecContext { constructor(codec) { this._codec = codec; this._opened = false; this._handle = binding.initCodecContext(codec._handle); } destroy() { binding.destroyCodecContext(this._handle); this._handle = null; } get pixelFormat() { return binding.getCodecContextPixelFormat(this._handle); } set pixelFormat(value) { binding.setCodecContextPixelFormat(this._handle, value); } get width() { return binding.getCodecContextWidth(this._handle); } set width(value) { binding.setCodecContextWidth(this._handle, value); } get height() { return binding.getCodecContextHeight(this._handle); } set height(value) { binding.setCodecContextHeight(this._handle, value); } get sampleFormat() { return binding.getCodecContextSampleFormat(this._handle); } set sampleFormat(value) { return binding.setCodecContextSampleFormat(this._handle, value); } get sampleRate() { return binding.getCodecContextSampleRate(this._handle); } set sampleRate(value) { binding.setCodecContextSampleRate(this._handle, value); } get timeBase() { const view = new Int32Array(binding.getCodecContextTimeBase(this._handle)); return new Rational(view[0], view[1]); } set timeBase(value) { binding.setCodecContextTimeBase(this._handle, value.numerator, value.denominator); } get frameRate() { const view = new Int32Array(binding.getCodecContextFramerate(this._handle)); return new Rational(view[0], view[1]); } set frameRate(value) { binding.setCodecContextFramerate(this._handle, value.numerator, value.denominator); } get channelLayout() { return new ChannelLayout(binding.getCodecContextChannelLayout(this._handle)); } set channelLayout(value) { binding.setCodecContextChannelLayout(this._handle, ChannelLayout.from(value)._handle); } get gopSize() { return binding.getCodecContextGOPSize(this._handle); } set gopSize(value) { binding.setCodecContextGOPSize(this._handle, value); } get flags() { return binding.getCodecContextFlags(this._handle); } set flags(value) { binding.setCodecContextFlags(this._handle, value); } get extraData() { return Buffer.from(binding.getCodecContextExtraData(this._handle)); } set extraData(value) { binding.setCodecContextExtraData(this._handle, value.buffer, value.byteOffset, value.byteLength); } get frameSize() { return binding.getCodecContextFrameSize(this._handle); } get frameNum() { return binding.getCodecContextFrameNum(this._handle); } get requestSampleFormat() { return binding.getCodecContextRequestSampleFormat(this._handle); } set requestSampleFormat(sampleFormat) { binding.setCodecContextRequestSampleFormat(this._handle, sampleFormat); } get hwDeviceCtx() { return HWDeviceContext.from(binding.getCodecContextHWDeviceCtx(this._handle)); } set hwDeviceCtx(hwDeviceContext) { binding.setCodecContextHWDeviceCtx(this._handle, hwDeviceContext._handle); } set getFormat(callback) { const wrap = (pixelFormats) => { return callback(this, pixelFormats); }; binding.setCodecContextGetFormat(this._handle, wrap); } open(options) { if (this._opened) return; this._opened = true; if (options) { binding.openCodecContextWithOptions(this._handle, options._handle); } else { binding.openCodecContext(this._handle); } } sendPacket(packet) { return binding.sendCodecContextPacket(this._handle, packet._handle); } receivePacket(packet) { return binding.receiveCodecContextPacket(this._handle, packet._handle); } sendFrame(frame) { let frameHandle = void 0; if (frame) frameHandle = frame._handle; return binding.sendCodecContextFrame(this._handle, frameHandle); } receiveFrame(frame) { return binding.receiveCodecContextFrame(this._handle, frame._handle); } getSupportedConfig(config) { if (config === codecConfig.FRAME_RATE) { const data2 = binding.getSupportedFrameRates(this._handle, this._codec._handle); if (!data2 || data2.length === 0) return null; const view = new Int32Array(data2); const rates = []; for (let i = 0; i < view.length; i += 2) { rates.push(new Rational(view[i], view[i + 1])); } return rates; } if (config === codecConfig.CHANNEL_LAYOUT) { const handles = binding.getSupportedChannelLayouts(this._handle, this._codec._handle); if (!handles || handles.length === 0) return null; return handles.map((handle) => new ChannelLayout(handle)); } const data = binding.getSupportedConfig(this._handle, this._codec._handle, config); if (config === codecConfig.SAMPLE_RATE && !data) { return null; } return new Int32Array(data); } getOption(name, flags = optionFlags.SEARCH_CHILDREN) { return binding.getOption(this._handle, name, flags); } setOption(name, value, flags = optionFlags.SEARCH_CHILDREN) { return binding.setOption(this._handle, name, value, flags); } setOptionDictionary(dictionary, flags = optionFlags.SEARCH_CHILDREN) { return binding.setOptionDictionary(this._handle, dictionary._handle, flags); } setOptionDefaults() { return binding.setOptionDefaults(this._handle); } listOptionNames(flags = optionFlags.SEARCH_CHILDREN) { return binding.listOptionNames(this._handle, flags); } getOptions(flags) { const options = {}; for (const name of this.listOptionNames(flags)) { try { options[name] = this.getOption(name, flags); } catch (error) { } } return options; } copyOptionsFrom(codecContext) { binding.copyOptions(this._handle, codecContext._handle); } [Symbol.dispose]() { this.destroy(); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegCodecContext }, _codec: this._codec, _opened: this._opened, flags: this.flags, pixelFormat: this.pixelFormat, width: this.width, height: this.height, sampleFormat: this.sampleFormat, sampleRate: this.sampleRate, timeBase: this.timeBase, channelLayout: this.channelLayout, gopSize: this.gopSize, extraData: this.extraData, frameRate: this.frameRate, frameSize: this.frameSize, frameNum: this.frameNum }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/codec-parameters.js var require_codec_parameters = __commonJS({ "../../node_modules/bare-ffmpeg/lib/codec-parameters.js"(exports, module) { var binding = require_binding10(); var ChannelLayout = require_channel_layout(); var Rational = require_rational(); module.exports = class FFmpegCodecParameters { constructor(handle, owned = false) { this._handle = handle; this._owned = owned; } // Getters, Setters get bitRate() { return binding.getCodecParametersBitRate(this._handle); } set bitRate(rate) { binding.setCodecParametersBitRate(this._handle, rate); } get bitsPerCodedSample() { return binding.getCodecParametersBitsPerCodedSample(this._handle); } set bitsPerCodedSample(bits) { binding.setCodecParametersBitsPerCodedSample(this._handle, bits); } get bitsPerRawSample() { return binding.getCodecParametersBitsPerRawSample(this._handle); } set bitsPerRawSample(bits) { binding.setCodecParametersBitsPerRawSample(this._handle, bits); } get sampleRate() { return binding.getCodecParametersSampleRate(this._handle); } set sampleRate(rate) { binding.setCodecParametersSampleRate(this._handle, rate); } get sampleAspectRatio() { const view = new Int32Array(binding.getCodecParametersSampleAspectRatio(this._handle)); return new Rational(view[0], view[1]); } set sampleAspectRatio(ratio) { binding.setCodecParametersSampleAspectRatio(this._handle, ratio.numerator, ratio.denominator); } get frameRate() { const view = new Int32Array(binding.getCodecParametersFramerate(this._handle)); return new Rational(view[0], view[1]); } set frameRate(rate) { binding.setCodecParametersFramerate(this._handle, rate.numerator, rate.denominator); } get frameSize() { return binding.getCodecParametersFrameSize(this._handle); } set frameSize(size) { binding.setCodecParametersFrameSize(this._handle, size); } get videoDelay() { return binding.getCodecParametersVideoDelay(this._handle); } set videoDelay(delay) { binding.setCodecParametersVideoDelay(this._handle, delay); } get nbChannels() { return binding.getCodecParametersNbChannels(this._handle); } set nbChannels(numberOfChannels) { binding.setCodecParametersNbChannels(this._handle, numberOfChannels); } get type() { return binding.getCodecParametersType(this._handle); } set type(type) { binding.setCodecParametersType(this._handle, type); } get tag() { return binding.getCodecParametersTag(this._handle); } set tag(tag) { binding.setCodecParametersTag(this._handle, tag); } get id() { return binding.getCodecParametersId(this._handle); } set id(id) { binding.setCodecParametersId(this._handle, id); } get level() { return binding.getCodecParametersLevel(this._handle); } set level(level) { binding.setCodecParametersLevel(this._handle, level); } get profile() { return binding.getCodecParametersProfile(this._handle); } set profile(profile) { binding.setCodecParametersProfile(this._handle, profile); } get format() { return binding.getCodecParametersFormat(this._handle); } set format(format) { binding.setCodecParametersFormat(this._handle, format); } get channelLayout() { return new ChannelLayout(binding.getCodecParametersChannelLayout(this._handle)); } set channelLayout(value) { binding.setCodecParametersChannelLayout(this._handle, ChannelLayout.from(value)._handle); } get width() { return binding.getCodecParametersWidth(this._handle); } set width(value) { binding.setCodecParametersWidth(this._handle, value); } get height() { return binding.getCodecParametersHeight(this._handle); } set height(value) { binding.setCodecParametersHeight(this._handle, value); } get extraData() { return Buffer.from(binding.getCodecParametersExtraData(this._handle)); } set extraData(value) { binding.setCodecParametersExtraData( this._handle, value.buffer, value.byteOffset, value.byteLength ); } get blockAlign() { return binding.getCodecParametersBlockAlign(this._handle); } set blockAlign(value) { binding.setCodecParametersBlockAlign(this._handle, value); } get initialPadding() { return binding.getCodecParametersInitialPadding(this._handle); } set initialPadding(value) { binding.setCodecParametersInitialPadding(this._handle, value); } get trailingPadding() { return binding.getCodecParametersTrailingPadding(this._handle); } set trailingPadding(value) { binding.setCodecParametersTrailingPadding(this._handle, value); } get seekPreroll() { return binding.getCodecParametersSeekPreroll(this._handle); } set seekPreroll(value) { binding.setCodecParametersSeekPreroll(this._handle, value); } get colorSpace() { return binding.getCodecParametersColorSpace(this._handle); } set colorSpace(value) { binding.setCodecParametersColorSpace(this._handle, value); } get colorPrimaries() { return binding.getCodecParametersColorPrimaries(this._handle); } set colorPrimaries(value) { binding.setCodecParametersColorPrimaries(this._handle, value); } get colorTRC() { return binding.getCodecParametersColorTRC(this._handle); } set colorTRC(value) { binding.setCodecParametersColorTRC(this._handle, value); } get colorRange() { return binding.getCodecParametersColorRange(this._handle); } set colorRange(value) { binding.setCodecParametersColorRange(this._handle, value); } // Methods fromContext(context) { binding.codecParametersFromContext(this._handle, context._handle); } toContext(context) { binding.codecParametersToContext(context._handle, this._handle); } destroy() { if (this._owned) binding.destroyCodecParameters(this._handle); } [Symbol.dispose]() { this.destroy(); } /* optional codec parameters */ [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegCodecParameters }, type: this.type, id: this.id, format: this.format, tag: this.tag, frameRate: this.frameRate, videoDelay: this.videoDelay, profile: this.profile, level: this.level, width: this.width, height: this.height, sampleAsectRatio: this.sampleAspectRatio, bitRate: this.bitRate, bitsPerCodedSample: this.bitsPerCodedSample, bitsPerRawSample: this.bitsPerRawSample, sampleRate: this.sampleRate, nbChannels: this.nbChannels, channelLayout: this.channelLayout, extraData: this.extraData, blockAlign: this.blockAlign, initialPadding: this.initialPadding, trailingPadding: this.trailingPadding, seekPreroll: this.seekPreroll, frameSize: this.frameSize }; } static alloc() { return new FFmpegCodecParameters(binding.allocCodecParameters(), true); } }; } }); // ../../node_modules/bare-ffmpeg/lib/dictionary.js var require_dictionary = __commonJS({ "../../node_modules/bare-ffmpeg/lib/dictionary.js"(exports, module) { var binding = require_binding10(); module.exports = class FFmpegDictionary { static from(obj) { const dictionary = new FFmpegDictionary(); for (const [key, value] of Object.entries(obj)) { dictionary.set(key, value); } return dictionary; } constructor() { this._handle = binding.initDictionary(); } destroy() { binding.destroyDictionary(this._handle); this._handle = null; } get(key) { const value = binding.getDictionaryEntry(this._handle, key); if (value === void 0) return null; return value; } set(key, value) { if (typeof value !== "string") value = String(value); binding.setDictionaryEntry(this._handle, key, value); } entries() { return binding.getDictionaryEntries(this._handle); } *[Symbol.iterator]() { yield* this.entries(); } [Symbol.dispose]() { this.destroy(); } }; } }); // ../../node_modules/bare-ffmpeg/lib/side-data.js var require_side_data = __commonJS({ "../../node_modules/bare-ffmpeg/lib/side-data.js"(exports, module) { module.exports = class SideData { constructor(handle, opts = {}) { this._handle = handle; this._type = opts.type || null; this._data = opts.data || null; } static from(readType, readName, readBuffer) { return class extends this { _readType() { return readType(this._handle); } _readName() { return readName(this._handle); } _readBuffer() { return readBuffer(this._handle); } }; } static fromData(data, type) { return new this(null, { data, type }); } get type() { if (this._type) return this._type; return this._readType(); } get name() { if (!this._handle) return null; return this._readName(); } get data() { if (this._data) return this._data; return Buffer.from(this._readBuffer()); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: SideData }, type: this.type, name: this.name, data: this.data }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/packet-side-data.js var require_packet_side_data = __commonJS({ "../../node_modules/bare-ffmpeg/lib/packet-side-data.js"(exports, module) { var binding = require_binding10(); var SideData = require_side_data(); module.exports = SideData.from( binding.getSideDataType, binding.getSideDataName, binding.getSideDataBuffer ); } }); // ../../node_modules/bare-ffmpeg/lib/stream.js var require_stream = __commonJS({ "../../node_modules/bare-ffmpeg/lib/stream.js"(exports, module) { var binding = require_binding10(); var Codec = require_codec(); var CodecContext = require_codec_context(); var CodecParameters = require_codec_parameters(); var Rational = require_rational(); var PacketSideData = require_packet_side_data(); module.exports = class FFmpegStream { constructor(handle) { this._handle = handle; this._codecParameters = new CodecParameters(binding.getStreamCodecParameters(this._handle)); } get id() { return binding.getStreamId(this._handle); } set id(value) { binding.setStreamId(this._handle, value); } get index() { return binding.getStreamIndex(this._handle); } get codec() { return Codec.for(this.codecParameters.id); } get codecParameters() { return this._codecParameters; } get sideData() { const handles = binding.getStreamSideData(this._handle); return handles.map((handle) => new PacketSideData(handle)); } get timeBase() { const view = new Int32Array(binding.getStreamTimeBase(this._handle)); return new Rational(view[0], view[1]); } set timeBase(value) { binding.setStreamTimeBase(this._handle, value.numerator, value.denominator); } get avgFramerate() { const view = new Int32Array(binding.getStreamAverageFramerate(this._handle)); return new Rational(view[0], view[1]); } set avgFramerate(value) { binding.setStreamAverageFramerate(this._handle, value.numerator, value.denominator); } get duration() { return binding.getStreamDuration(this._handle); } set duration(value) { binding.setStreamDuration(this._handle, value); } decoder() { const context = new CodecContext(this.codec.decoder); this._codecParameters.toContext(context); return context; } encoder() { const context = new CodecContext(this.codec.encoder); this._codecParameters.toContext(context); return context; } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegStream }, id: this.id, index: this.index, sideData: this.sideData, timeBase: this.timeBase, avgFramerate: this.avgFramerate, codecParameters: this.codecParameters }; } }; module.exports.SideData = PacketSideData; } }); // ../../node_modules/bare-ffmpeg/lib/output-format.js var require_output_format = __commonJS({ "../../node_modules/bare-ffmpeg/lib/output-format.js"(exports, module) { var binding = require_binding10(); module.exports = class FFmpegOutputFormat { constructor(name, handle) { if (handle) this._handle = handle; else this._handle = binding.initOutputFormat(name); } static from(handle) { return new FFmpegOutputFormat(null, handle); } get flags() { return binding.getOutputFormatFlags(this._handle); } get extensions() { return binding.getOutputFormatExtensions(this._handle); } get mimeType() { return binding.getOutputFormatMimeType(this._handle); } get name() { return binding.getOutputFormatName(this._handle); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegOutputFormat }, name: this.name, flags: this.flags, extensions: this.extensions, mimeType: this.mimeType }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/io-context.js var require_io_context = __commonJS({ "../../node_modules/bare-ffmpeg/lib/io-context.js"(exports, module) { var binding = require_binding10(); module.exports = class FFmpegIOContext { constructor(buffer, opts = {}) { if (buffer === null && opts === null) { this._handle = null; return; } let offset = 0; let len = 0; if (typeof buffer === "number") { len = buffer; buffer = void 0; } else if (buffer) { offset = buffer.byteOffset; len = buffer.byteLength; buffer = buffer.buffer; } else { buffer = Buffer.alloc(0); } this._handle = binding.initIOContext( buffer, offset, len, opts.onwrite && onwriteWrapper.bind(null, opts.onwrite), opts.onread && onreadWrapper.bind(null, opts.onread), opts.onseek ); } destroy() { if (this._handle) { binding.destroyIOContext(this._handle); this._handle = null; } } transfer() { const to = new FFmpegIOContext(null, null); to._handle = this._handle; this._handle = null; return to; } [Symbol.dispose]() { this.destroy(); } }; function onwriteWrapper(target, arraybuffer) { return target(Buffer.from(arraybuffer)); } function onreadWrapper(target, arraybuffer, requestedLen) { return target(Buffer.from(arraybuffer), requestedLen); } } }); // ../../node_modules/bare-ffmpeg/lib/input-format.js var require_input_format = __commonJS({ "../../node_modules/bare-ffmpeg/lib/input-format.js"(exports, module) { var binding = require_binding10(); var defaultName = null; switch (Bare.platform) { case "android": defaultName = "android_camera"; break; case "darwin": case "ios": defaultName = "avfoundation"; break; case "linux": defaultName = "v4l2"; break; case "win32": defaultName = "dshow"; break; } module.exports = class FFmpegInputFormat { constructor(name = defaultName, handle) { if (handle) this._handle = handle; else this._handle = binding.initInputFormat(name); } static from(handle) { return new FFmpegInputFormat(null, handle); } get flags() { return binding.getInputFormatFlags(this._handle); } get extensions() { return binding.getInputFormatExtensions(this._handle); } get mimeType() { return binding.getInputFormatMimeType(this._handle); } get name() { return binding.getInputFormatName(this._handle); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegInputFormat }, name: this.name, flags: this.flags, extensions: this.extensions, mimeType: this.mimeType }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/format-context.js var require_format_context = __commonJS({ "../../node_modules/bare-ffmpeg/lib/format-context.js"(exports) { var binding = require_binding10(); var Stream = require_stream(); var OutputFormat = require_output_format(); var IOContext = require_io_context(); var InputFormat = require_input_format(); var Dictionary = require_dictionary(); var FFmpegFormatContext = class { constructor(io) { this._io = io ? io.transfer() : null; this._streams = []; } destroy() { if (this._io) { this._io.destroy(); this._io = null; } } get io() { return this._io; } get streams() { return this._streams; } get duration() { return binding.getFormatContextDuration(this._handle); } set duration(value) { binding.setFormatContextDuration(this._handle, value); } readFrame(packet) { return binding.readFormatContextFrame(this._handle, packet._handle); } getBestStreamIndex(type) { return binding.getFormatContextBestStreamIndex(this._handle, type); } getStream(index) { if (index < 0 || index >= this._streams.length) { return null; } return this._streams[index]; } /** @returns {Stream|null} */ getBestStream(type) { if (this._streams.length === 0) { return null; } const bestIndex = binding.getFormatContextBestStreamIndex(this._handle, type); if (bestIndex < 0 || bestIndex >= this._streams.length) { return null; } return this._streams[bestIndex]; } [Symbol.dispose]() { this.destroy(); } }; var defaultURL = null; switch (Bare.platform) { case "darwin": case "ios": defaultURL = "0:0"; break; case "linux": defaultURL = "/dev/video0"; break; case "win32": defaultURL = "video=Integrated Camera"; break; } exports.InputFormatContext = class FFmpegInputFormatContext extends FFmpegFormatContext { // eslint-disable-next-line constructor(io, options, url = defaultURL) { if (io instanceof IOContext) { super(io); try { this._handle = binding.openInputFormatContextWithIO(this._io._handle); } catch (err) { super.destroy(); throw err; } } else if (io instanceof InputFormat) { super(); options = options || new Dictionary(); try { this._handle = binding.openInputFormatContextWithFormat(io._handle, options._handle, url); } finally { options.destroy(); } } for (const handle of binding.getFormatContextStreams(this._handle)) { this._streams.push(new Stream(handle)); } } destroy() { super.destroy(); binding.closeInputFormatContext(this._handle); this._handle = null; } dump(printIdx = 0, printUrl = "") { binding.dumpFormatContext(this._handle, false, printIdx, printUrl); } get inputFormat() { const handle = binding.getFormatContextInputFormat(this._handle); if (handle) return InputFormat.from(handle); } }; exports.OutputFormatContext = class FFmpegOutputFormatContext extends FFmpegFormatContext { constructor(format, io) { super(io); if (typeof format === "string") format = new OutputFormat(format); this._handle = binding.openOutputFormatContext(format._handle, this._io._handle); this._isOutput = true; } destroy() { super.destroy(); binding.closeOutputFormatContext(this._handle); this._handle = null; } createStream() { const stream = new Stream(binding.createFormatContextStream(this._handle)); this._streams.push(stream); return stream; } /** @param {Dictionary} [options] format options */ writeHeader(options) { binding.writeFormatContextHeader(this._handle, options?._handle); } /** @param {Packet} packet */ writeFrame(packet) { binding.writeFormatContextFrame(this._handle, packet._handle); } writeTrailer() { binding.writeFormatContextTrailer(this._handle); } dump(printIdx = 0, printUrl = "") { binding.dumpFormatContext(this._handle, true, printIdx, printUrl); } get outputFormat() { const handle = binding.getFormatContextOutputFormat(this._handle); if (handle) return OutputFormat.from(handle); } }; } }); // ../../node_modules/bare-ffmpeg/lib/filter.js var require_filter = __commonJS({ "../../node_modules/bare-ffmpeg/lib/filter.js"(exports, module) { var binding = require_binding10(); module.exports = class Filter { constructor(name) { this._handle = binding.getFilterByName(name); } }; } }); // ../../node_modules/bare-ffmpeg/lib/filter-context.js var require_filter_context = __commonJS({ "../../node_modules/bare-ffmpeg/lib/filter-context.js"(exports, module) { var binding = require_binding10(); var { optionFlags } = require_constants(); module.exports = class FilterContext { constructor() { this._handle = binding.initFilterContext(); } getOption(name, flags = optionFlags.SEARCH_CHILDREN) { return binding.getOption(this._handle, name, flags); } setOption(name, value, flags = optionFlags.SEARCH_CHILDREN) { binding.setOption(this._handle, name, value, flags); } setOptionDictionary(dictionary, flags = optionFlags.SEARCH_CHILDREN) { binding.setOptionDictionary(this._handle, dictionary._handle, flags); } setOptionDefaults() { binding.setOptionDefaults(this._handle); } listOptionNames(flags = optionFlags.SEARCH_CHILDREN) { return binding.listOptionNames(this._handle, flags); } getOptions(flags = optionFlags.SEARCH_CHILDREN) { const options = {}; for (const name of this.listOptionNames(flags)) { try { options[name] = this.getOption(name, flags); } catch (error) { } } return options; } }; } }); // ../../node_modules/bare-ffmpeg/lib/filter-graph.js var require_filter_graph = __commonJS({ "../../node_modules/bare-ffmpeg/lib/filter-graph.js"(exports, module) { var binding = require_binding10(); module.exports = class FilterGraph { constructor() { this._handle = binding.initFilterGraph(); } destroy() { binding.destroyFilterGraph(this._handle); this._handle = null; } createFilter(context, filter, name, args) { return binding.createFilterGraphFilter( this._handle, context._handle, filter._handle, name, args ?? void 0 ); } parse(filterDescription, inputs, outputs) { binding.parseFilterGraph( this._handle, inputs?._handle || void 0, outputs?._handle || void 0, filterDescription ); } configure() { binding.configureFilterGraph(this._handle); } pushFrame(ctx, frame) { return binding.pushFilterGraphFrame(ctx._handle, frame._handle); } pullFrame(ctx, frame) { frame.unref(); return binding.pullFilterGraphFrame(ctx._handle, frame._handle); } [Symbol.dispose]() { this.destroy(); } }; } }); // ../../node_modules/bare-ffmpeg/lib/filter-inout.js var require_filter_inout = __commonJS({ "../../node_modules/bare-ffmpeg/lib/filter-inout.js"(exports, module) { var binding = require_binding10(); module.exports = class FilterInOut { constructor(handle = binding.initFilterInout()) { this._handle = handle; this._next = null; this._filterContext = null; } destroy() { binding.destroyFilterInOut(this._handle); this._handle = null; } get name() { return binding.getFilterInOutName(this._handle); } set name(value) { return binding.setFilterInOutName(this._handle, value); } get filterContext() { return this._filterContext; } set filterContext(value) { this._filterContext = value; return binding.setFilterInOutFilterContext(this._handle, this._filterContext._handle); } get padIdx() { return binding.getFilterInOutPadIdx(this._handle); } set padIdx(value) { return binding.setFilterInOutPadIdx(this._handle, value); } get next() { return this._next; } set next(value) { this._next = value; return binding.setFilterInOutNext(this._handle, this._next._handle); } [Symbol.dispose]() { this.destroy(); } }; } }); // ../../node_modules/bare-ffmpeg/lib/hw-frames-constraints.js var require_hw_frames_constraints = __commonJS({ "../../node_modules/bare-ffmpeg/lib/hw-frames-constraints.js"(exports, module) { var binding = require_binding10(); module.exports = class HWFramesConstraints { constructor(handle) { this._handle = handle; } get validSwFormats() { return binding.getHWFramesConstraintsValidSwFormats(this._handle); } get validHwFormats() { return binding.getHWFramesConstraintsValidHwFormats(this._handle); } get minWidth() { return binding.getHWFramesConstraintsMinWidth(this._handle); } get maxWidth() { return binding.getHWFramesConstraintsMaxWidth(this._handle); } get minHeight() { return binding.getHWFramesConstraintsMinHeight(this._handle); } get maxHeight() { return binding.getHWFramesConstraintsMaxHeight(this._handle); } // Note: HWFramesConstraints is independently allocated by FFmpeg and must be // explicitly freed. It is not owned by HWFramesContext. destroy() { binding.destroyHWFramesConstraints(this._handle); this._handle = null; } [Symbol.dispose]() { this.destroy(); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: HWFramesConstraints }, validSwFormats: this.validSwFormats, validHwFormats: this.validHwFormats, minWidth: this.minWidth, maxWidth: this.maxWidth, minHeight: this.minHeight, maxHeight: this.maxHeight }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/hw-frames-context.js var require_hw_frames_context = __commonJS({ "../../node_modules/bare-ffmpeg/lib/hw-frames-context.js"(exports, module) { var binding = require_binding10(); var HWFramesConstraints = require_hw_frames_constraints(); module.exports = class HWFramesContext { constructor(hwDeviceContext, format, swFormat, width, height, handle = void 0) { if (handle) { this._handle = handle; return; } this._handle = binding.initHWFramesContext( hwDeviceContext._handle, format, swFormat, width, height ); } static from(handle = null) { if (handle === null) return null; return new HWFramesContext(null, null, null, null, null, handle); } get format() { return binding.getHWFramesContextFormat(this._handle); } set format(value) { binding.setHWFramesContextFormat(this._handle, value); } get swFormat() { return binding.getHWFramesContextSWFormat(this._handle); } set swFormat(value) { binding.setHWFramesContextSWFormat(this._handle, value); } get width() { return binding.getHWFramesContextWidth(this._handle); } set width(value) { binding.setHWFramesContextWidth(this._handle, value); } get height() { return binding.getHWFramesContextHeight(this._handle); } set height(value) { binding.setHWFramesContextHeight(this._handle, value); } get initialPoolSize() { return binding.getHWFramesContextInitialPoolSize(this._handle); } set initialPoolSize(value) { binding.setHWFramesContextInitialPoolSize(this._handle, value); } getBuffer(frame) { binding.getHWFramesContextBuffer(this._handle, frame._handle); } getConstraints() { const handle = binding.getHWFramesContextConstraints(this._handle); return new HWFramesConstraints(handle); } destroy() { binding.destroyHWFramesContext(this._handle); this._handle = null; } [Symbol.dispose]() { this.destroy(); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: HWFramesContext }, format: this.format, swFormat: this.swFormat, width: this.width, height: this.height }; } }; } }); // ../../node_modules/bare-ffmpeg/lib/frame.js var require_frame = __commonJS({ "../../node_modules/bare-ffmpeg/lib/frame.js"(exports, module) { var binding = require_binding10(); var ChannelLayout = require_channel_layout(); var HWFramesContext = require_hw_frames_context(); var Rational = require_rational(); var SideData = require_side_data(); var constants = require_constants(); var FrameMetadata = class { constructor(frame) { this._frameHandle = frame._handle; } get(key) { if (!this._frameHandle) return null; const value = binding.getFrameMetadataEntry(this._frameHandle, key); if (value === void 0) return null; return value; } entries() { if (!this._frameHandle) return []; return binding.getFrameMetadataEntries(this._frameHandle); } *[Symbol.iterator]() { yield* this.entries(); } }; var FrameSideData = SideData.from( binding.getFrameSideDataType, binding.getFrameSideDataName, binding.getFrameSideDataBuffer ); module.exports = class FFmpegFrame { constructor() { this._handle = binding.initFrame(); this._metadata = null; } destroy() { binding.destroyFrame(this._handle); this._handle = null; this._metadata = null; } unref() { binding.unrefFrame(this._handle); } get width() { return binding.getFrameWidth(this._handle); } set width(value) { binding.setFrameWidth(this._handle, value); } get height() { return binding.getFrameHeight(this._handle); } set height(value) { binding.setFrameHeight(this._handle, value); } get format() { return binding.getFrameFormat(this._handle); } set format(value) { binding.setFrameFormat(this._handle, value); } get channelLayout() { return new ChannelLayout(binding.getFrameChannelLayout(this._handle)); } set channelLayout(value) { binding.setFrameChannelLayout(this._handle, ChannelLayout.from(value)._handle); } get nbSamples() { return binding.getFrameNbSamples(this._handle); } set nbSamples(value) { binding.setFrameNbSamples(this._handle, value); } get pictType() { return binding.getFramePictType(this._handle); } get pts() { return binding.getFramePTS(this._handle); } set pts(value) { return binding.setFramePTS(this._handle, value); } get packetDTS() { return binding.getFramePacketDTS(this._handle); } set packetDTS(value) { return binding.setFramePacketDTS(this._handle, value); } get timeBase() { const view = new Int32Array(binding.getFrameTimeBase(this._handle)); return new Rational(view[0], view[1]); } set timeBase(value) { binding.setFrameTimeBase(this._handle, value.numerator, value.denominator); } get sampleRate() { return binding.getFrameSampleRate(this._handle); } set sampleRate(value) { binding.setFrameSampleRate(this._handle, value); } get metadata() { if (!this._metadata) this._metadata = new FrameMetadata(this); return this._metadata; } get sideData() { const handles = binding.getFrameSideData(this._handle); return handles.map((handle) => new FrameSideData(handle)); } set sideData(values) { binding.setFrameSideData( this._handle, values.map((value) => ({ buffer: value.data.buffer, offset: value.data.byteOffset, length: value.data.byteLength, type: value.type })) ); } removeSideData(type) { binding.removeFrameSideData(this._handle, type); } get hwFramesCtx() { const handle = binding.getFrameHWFramesCtx(this._handle); return handle ? HWFramesContext.from(handle) : null; } set hwFramesCtx(hwFramesContext) { binding.setFrameHWFramesCtx(this._handle, hwFramesContext._handle); } copyProperties(source) { binding.copyFrameProperties(this._handle, source._handle); } transferData(destination) { binding.transferFrameData(destination._handle, this._handle); } hwMap(destination, flags = constants.hwFrameMapFlags.NONE) { binding.mapFrame(destination._handle, this._handle, flags); } alloc() { binding.allocFrame(this._handle, 32); } [Symbol.dispose]() { this.destroy(); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegFrame }, width: this.width, height: this.height, format: this.format, channelLayout: this.channelLayout, nbSamples: this.nbSamples, pictType: this.pictType, pts: this.pts, packetDTS: this.packetDTS, timeBase: this.timeBase }; } }; module.exports.SideData = FrameSideData; } }); // ../../node_modules/bare-ffmpeg/lib/image.js var require_image = __commonJS({ "../../node_modules/bare-ffmpeg/lib/image.js"(exports, module) { var binding = require_binding10(); var constants = require_constants(); module.exports = class FFmpegImage { constructor(pixelFormat, width, height, align = 1) { pixelFormat = constants.toPixelFormat(pixelFormat); this._pixelFormat = pixelFormat; this._width = width; this._height = height; this._align = align; this._data = Buffer.from(binding.initImage(pixelFormat, width, height, align)); } get pixelFormat() { return this._pixelFormat; } get width() { return this._width; } get height() { return this._height; } get align() { return this._align; } get data() { return this._data; } fill(frame) { binding.fillImage( this._pixelFormat, this._width, this._height, this._align, this._data.buffer, this._data.byteOffset, frame._handle ); } read(frame) { binding.readImage( this._pixelFormat, this._width, this._height, this._align, this._data.buffer, this._data.byteOffset, frame._handle ); } lineSize(plane = 0) { return binding.getImageLineSize(this._pixelFormat, this._width, plane); } static lineSize(pixelFormat, width, plane = 0) { return binding.getImageLineSize(pixelFormat, width, plane); } }; } }); // ../../node_modules/bare-ffmpeg/lib/packet.js var require_packet = __commonJS({ "../../node_modules/bare-ffmpeg/lib/packet.js"(exports, module) { var binding = require_binding10(); var Rational = require_rational(); var PacketSideData = require_packet_side_data(); module.exports = class FFmpegPacket { constructor(buffer) { if (buffer) { this._handle = binding.initPacketFromBuffer( buffer.buffer, buffer.byteOffset, buffer.byteLength ); } else { this._handle = binding.initPacket(); } } destroy() { binding.destroyPacket(this._handle); this._handle = null; } unref() { binding.unrefPacket(this._handle); } get streamIndex() { return binding.getPacketStreamIndex(this._handle); } set streamIndex(value) { return binding.setPacketStreamIndex(this._handle, value); } get data() { return Buffer.from(binding.getPacketData(this._handle)); } set data(value) { binding.setPacketData(this._handle, value.buffer, value.byteOffset, value.byteLength); } get sideData() { const handles = binding.getPacketSideData(this._handle); return handles.map((handle) => new PacketSideData(handle)); } set sideData(values) { binding.setPacketSideData( this._handle, values.map((value) => ({ buffer: value.data.buffer, offset: value.data.byteOffset, length: value.data.byteLength, type: value.type })) ); } get isKeyframe() { return binding.isPacketKeyframe(this._handle); } set isKeyframe(value) { binding.setPacketIsKeyFrame(this._handle, value); } get dts() { return binding.getPacketDTS(this._handle); } set dts(value) { return binding.setPacketDTS(this._handle, value); } get pts() { return binding.getPacketPTS(this._handle); } set pts(value) { return binding.setPacketPTS(this._handle, value); } get timeBase() { const view = new Int32Array(binding.getPacketTimeBase(this._handle)); return new Rational(view[0], view[1]); } set timeBase(value) { binding.setPacketTimeBase(this._handle, value.numerator, value.denominator); } rescaleTimestamps(srcTimeBase, dstTimeBase) { return binding.rescalePacketTimestamps( this._handle, srcTimeBase.numerator, srcTimeBase.denominator, dstTimeBase.numerator, dstTimeBase.denominator ); } copyPropsFrom(sourcePacket) { binding.copyPacketProps(this._handle, sourcePacket._handle); } get duration() { return binding.getPacketDuration(this._handle); } set duration(value) { return binding.setPacketDuration(this._handle, value); } get flags() { return binding.getPacketFlags(this._handle); } set flags(value) { return binding.setPacketFlags(this._handle, value); } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: FFmpegPacket }, streamIndex: this.streamIndex, flags: this.flags, isKeyframe: this.isKeyframe, timeBase: this.timeBase, dts: this.dts, pts: this.pts, duration: this.duration, data: this.data, sideData: this.sideData }; } [Symbol.dispose]() { this.destroy(); } }; module.exports.SideData = PacketSideData; } }); // ../../node_modules/bare-ffmpeg/lib/resampler.js var require_resampler = __commonJS({ "../../node_modules/bare-ffmpeg/lib/resampler.js"(exports, module) { var binding = require_binding10(); var ChannelLayout = require_channel_layout(); var FFmpegResampler = class { constructor(inputSampleRate, inputChannelLayout, inputFormat, outputSampleRate, outputChannelLayout, outputFormat) { inputChannelLayout = ChannelLayout.from(inputChannelLayout); outputChannelLayout = ChannelLayout.from(outputChannelLayout); this._inputSampleRate = inputSampleRate; this._outputSampleRate = outputSampleRate; this._handle = binding.initResampler( inputSampleRate, inputFormat, inputChannelLayout._handle, outputSampleRate, outputFormat, outputChannelLayout._handle ); } get inputSampleRate() { return this._inputSampleRate; } get outputSampleRate() { return this._outputSampleRate; } get delay() { return binding.getResamplerDelay(this._handle, this._inputSampleRate); } convert(inputFrame, outputFrame) { return binding.convertResampler(this._handle, inputFrame._handle, outputFrame._handle); } flush(outputFrame) { return binding.flushResampler(this._handle, outputFrame._handle); } destroy() { binding.destroyResampler(this._handle); this._handle = null; } [Symbol.dispose]() { this.destroy(); } }; module.exports = FFmpegResampler; } }); // ../../node_modules/bare-ffmpeg/lib/samples.js var require_samples = __commonJS({ "../../node_modules/bare-ffmpeg/lib/samples.js"(exports, module) { var binding = require_binding10(); module.exports = class FFmpegSamples { _data; _frame; constructor({ noAlignment = false } = {}) { this._noAlignment = noAlignment; } get data() { return this._data; } get format() { return this._frame.format; } get channelLayout() { return this._frame.channelLayout; } get nbSamples() { return this._frame.nbSamples; } get nbChannels() { return this.channelLayout && this.channelLayout.nbChannels; } get pts() { return this._frame.pts; } fill(frame) { const { format, channelLayout, nbSamples } = frame; const len = FFmpegSamples.bufferSize( format, channelLayout.nbChannels, nbSamples, this._noAlignment ); if (!this._data || len !== this._data.length) { this._data = Buffer.allocUnsafe(len); } const res = binding.fillSamples( frame._handle, this._data.buffer, this._data.byteOffset, this._noAlignment ); this._frame = frame; return res; } read(frame) { const { format, channelLayout, nbSamples } = frame; const len = FFmpegSamples.bufferSize( format, channelLayout.nbChannels, nbSamples, this._noAlignment ); if (!this._data || len !== this._data.length) { this._data = Buffer.allocUnsafe(len); } binding.readSamples(frame._handle, this._data.buffer, this._data.byteOffset, this._noAlignment); } copy(frame, dstOffset = 0, srcOffset = 0) { binding.copySamples(frame._handle, this._frame._handle, dstOffset, srcOffset, this.nbSamples); } static bufferSize(format, nbChannels, nbSamples, noAlignment = false) { return binding.samplesBufferSize(format, nbChannels, nbSamples, noAlignment); } }; } }); // ../../node_modules/bare-ffmpeg/lib/scaler.js var require_scaler = __commonJS({ "../../node_modules/bare-ffmpeg/lib/scaler.js"(exports, module) { var binding = require_binding10(); var constants = require_constants(); module.exports = class FFmpegScaler { constructor(sourcePixelFormat, sourceWidth, sourceHeight, targetPixelFormat, targetWidth, targetHeight) { sourcePixelFormat = constants.toPixelFormat(sourcePixelFormat); targetPixelFormat = constants.toPixelFormat(targetPixelFormat); this._sourcePixelFormat = sourcePixelFormat; this._sourceWidth = sourceWidth; this._sourceHeight = sourceHeight; this._targetPixelFormat = targetPixelFormat; this._targetWidth = targetWidth; this._targetHeight = targetHeight; this._handle = binding.initScaler( sourcePixelFormat, sourceWidth, sourceHeight, targetPixelFormat, targetWidth, targetHeight ); } destroy() { binding.destroyScaler(this._handle); this._handle = null; } scale(source, y, height, target) { if (typeof y !== "number") { target = y; y = 0; height = source.height; } else if (typeof height !== "number") { target = height; height = source.height; } return binding.scaleScaler(this._handle, source._handle, y, height, target._handle); } [Symbol.dispose]() { this.destroy(); } }; } }); // ../../node_modules/bare-ffmpeg/lib/log.js var require_log = __commonJS({ "../../node_modules/bare-ffmpeg/lib/log.js"(exports, module) { var binding = require_binding10(); var constants = require_constants(); module.exports = { ...constants.logLevels }; Object.defineProperty(module.exports, "level", { get() { return binding.getLogLevel(); }, set(level) { return binding.setLogLevel(level); } }); } }); // ../../node_modules/bare-ffmpeg/index.js var require_bare_ffmpeg = __commonJS({ "../../node_modules/bare-ffmpeg/index.js"(exports) { var AudioFIFO = require_audio_fifo(); var ChannelLayout = require_channel_layout(); var Codec = require_codec(); var CodecContext = require_codec_context(); var CodecParameters = require_codec_parameters(); var Decoder = require_decoder(); var Dictionary = require_dictionary(); var Encoder = require_encoder(); var { InputFormatContext, OutputFormatContext } = require_format_context(); var Filter = require_filter(); var FilterContext = require_filter_context(); var FilterGraph = require_filter_graph(); var FilterInOut = require_filter_inout(); var Frame = require_frame(); var HWDeviceContext = require_hw_device_context(); var HWFramesContext = require_hw_frames_context(); var HWFramesConstraints = require_hw_frames_constraints(); var IOContext = require_io_context(); var Image = require_image(); var InputFormat = require_input_format(); var OutputFormat = require_output_format(); var Packet = require_packet(); var Rational = require_rational(); var Resampler = require_resampler(); var Samples = require_samples(); var Scaler = require_scaler(); var Stream = require_stream(); var log = require_log(); exports.AudioFIFO = AudioFIFO; exports.ChannelLayout = ChannelLayout; exports.Codec = Codec; exports.CodecContext = CodecContext; exports.CodecParameters = CodecParameters; exports.Decoder = Decoder; exports.Dictionary = Dictionary; exports.Encoder = Encoder; exports.Filter = Filter; exports.FilterContext = FilterContext; exports.FilterGraph = FilterGraph; exports.FilterInOut = FilterInOut; exports.Frame = Frame; exports.HWDeviceContext = HWDeviceContext; exports.HWFramesContext = HWFramesContext; exports.HWFramesConstraints = HWFramesConstraints; exports.IOContext = IOContext; exports.Image = Image; exports.InputFormat = InputFormat; exports.InputFormatContext = InputFormatContext; exports.OutputFormat = OutputFormat; exports.OutputFormatContext = OutputFormatContext; exports.Packet = Packet; exports.Samples = Samples; exports.Scaler = Scaler; exports.Stream = Stream; exports.Rational = Rational; exports.Resampler = Resampler; exports.log = log; exports.constants = require_constants(); } }); // ../../node_modules/bare-media/src/codecs.js async function importCodec(mimetype) { const codecImport = codecs[mimetype]; if (!codecImport) throw new Error(`Unsupported file type: No codec available for ${mimetype}`); try { return await codecImport(); } catch (err) { void err; throw new Error(`Failed to import codec for ${mimetype}`, { cause: err }); } } async function importFFmpeg() { try { return await Promise.resolve().then(() => __toESM(require_bare_ffmpeg(), 1)); } catch (err) { void err; throw new Error("Failed to import bare-ffmpeg", { cause: err }); } } function supportsQuality(mimetype) { return { "image/webp": true, "image/jpeg": true }[mimetype] || false; } function detectMimeType(buffer) { return (0, import_get_mime_type.default)((0, import_get_file_format.default)(buffer)); } var import_get_mime_type, import_get_file_format, codecs; var init_codecs = __esm({ "../../node_modules/bare-media/src/codecs.js"() { import_get_mime_type = __toESM(require_get_mime_type(), 1); import_get_file_format = __toESM(require_get_file_format(), 1); init_types(); codecs = { [IMAGE.AVIF]: () => Promise.resolve().then(() => __toESM(require_bare_heif(), 1)), [IMAGE.BMP]: () => Promise.resolve().then(() => __toESM(require_bare_bmp(), 1)), [IMAGE.GIF]: () => Promise.resolve().then(() => __toESM(require_bare_gif(), 1)), [IMAGE.HEIC]: () => Promise.resolve().then(() => __toESM(require_bare_heif(), 1)), [IMAGE.HEIF]: () => Promise.resolve().then(() => __toESM(require_bare_heif(), 1)), [IMAGE.JPEG]: () => Promise.resolve().then(() => __toESM(require_bare_jpeg(), 1)), [IMAGE.JPG]: () => Promise.resolve().then(() => __toESM(require_bare_jpeg(), 1)), [IMAGE.PNG]: () => Promise.resolve().then(() => __toESM(require_bare_png(), 1)), [IMAGE.SVG_XML]: () => Promise.resolve().then(() => __toESM(require_bare_svg(), 1)), [IMAGE.TIF]: () => Promise.resolve().then(() => __toESM(require_bare_tiff(), 1)), [IMAGE.TIFF]: () => Promise.resolve().then(() => __toESM(require_bare_tiff(), 1)), [IMAGE.VND_MS_ICON]: () => Promise.resolve().then(() => __toESM(require_bare_ico(), 1)), [IMAGE.WEBP]: () => Promise.resolve().then(() => __toESM(require_bare_webp(), 1)), [IMAGE.X_ICON]: () => Promise.resolve().then(() => __toESM(require_bare_ico(), 1)), [IMAGE.X_MS_BMP]: () => Promise.resolve().then(() => __toESM(require_bare_bmp(), 1)) }; } }); // ../../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/bare-events/lib/errors.js var require_errors2 = __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_errors2(); 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]; } rawListeners(name) { if (this._events === void 0) return []; const e = this._events[name]; return e === void 0 ? [] : e.list.map((l) => l[0]); } eventNames() { if (this._events === void 0) return []; return Reflect.ownKeys(this._events); } 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-path/binding.js var require_binding11 = __commonJS({ "../../node_modules/bare-path/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-path/lib/constants.js var require_constants2 = __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_constants2(); exports.validateString = function validateString(value, name) { if (typeof value !== "string") { throw new TypeError( `The "${name}" argument must be of type string. Received type ${typeof value}` ); } }; 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 binding = require_binding11(); var { normalizeString, validateString } = require_shared(); var { CHAR_DOT, CHAR_FORWARD_SLASH } = require_constants2(); 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] : binding.cwd(); if (i >= 0) validateString(path, `paths[${i}]`); 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) { validateString(path, "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) { validateString(path, "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]; validateString(arg, "path"); 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) { validateString(from, "from"); validateString(to, "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) { validateString(path, "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) { if (suffix !== void 0) validateString(suffix, "suffix"); validateString(path, "path"); 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) { validateString(path, "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 binding = require_binding11(); var { normalizeString, validateString } = 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_constants2(); 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]; validateString(path, `paths[${i}]`); if (path.length === 0) continue; } else if (resolvedDevice.length === 0) { path = binding.cwd(); } else { path = binding.cwd(resolvedDevice); 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) { validateString(path, "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) { validateString(path, "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]; validateString(arg, "path"); 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) { validateString(from, "from"); validateString(to, "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 (typeof path !== "string" || 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) { validateString(path, "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) { if (suffix !== void 0) validateString(suffix, "suffix"); validateString(path, "path"); 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) { validateString(path, "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_binding12 = __commonJS({ "../../node_modules/bare-url/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-url/lib/errors.js var require_errors3 = __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 URLSearchParams2 = 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 = null; if (url) _URLSearchParams._urls.set(this, url); if (typeof init === "string") { this._parse(init); } else { this._params = /* @__PURE__ */ new Map(); 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() { let size = 0; for (const values of this._params.values()) size += values.length; return size; } // 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) { const params = /* @__PURE__ */ new Map(); this._params = params; const len = input.length; let start = input.charCodeAt(0) === 63 ? 1 : 0; while (start < len) { let end = input.indexOf("&", start); if (end === -1) end = len; if (end !== start) { let split = input.indexOf("=", start); if (split === -1 || split > end) split = end; const name = decode2(input.slice(start, split)); const value = split === end ? "" : decode2(input.slice(split + 1, end)); const list = params.get(name); if (list === void 0) params.set(name, [value]); else list.push(value); } start = end + 1; } } // https://url.spec.whatwg.org/#concept-urlencoded-serializer _serialize() { let result = ""; let separator = ""; for (const [name, values] of this._params) { const encoded = encode2(String(name)); for (const value of values) { result += separator + encoded + "=" + encode2(String(value)); separator = "&"; } } return result; } }; module.exports = exports = URLSearchParams2; exports.isURLSearchParams = function isURLSearchParams(value) { if (value instanceof URLSearchParams2) return true; return typeof value === "object" && value !== null && value[kind] === URLSearchParams2[kind]; }; var unencoded = /^[\w*.-]*$/; var spaced = /^[\w*. -]*$/; var extra = /[!'()~]/; var extraAll = /[!'()~]/g; var escapes = { "!": "%21", "'": "%27", "(": "%28", ")": "%29", "~": "%7E" }; var lone = /[\ud800-\udbff](?![\udc00-\udfff])|(? escapes[match]); return encoded; } function decode2(component) { if (component.indexOf("+") !== -1) component = component.replaceAll("+", " "); if (component.indexOf("%") === -1) return component; return decodeURIComponent(component); } } }); // ../../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_binding12(); var errors = require_errors3(); var URLSearchParams2 = require_url_search_params(); var kind = Symbol.for("bare.url.kind"); var isWindows = Bare.platform === "win32"; var components = new Uint32Array(8); var unset = 4294967295; var reserved = isWindows ? /[%#?\n\r\t]/ : /[%#?\n\r\t\\]/; 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._href = void 0; this._schemeEnd = 0; this._usernameEnd = 0; this._hostStart = 0; this._hostEnd = 0; this._pathStart = 0; this._queryStart = 0; this._fragmentStart = 0; this._params = null; this._parse(input, base, opts.throw !== false); } get [kind]() { return _URL[kind]; } // https://url.spec.whatwg.org/#dom-url-href get href() { return this._href; } set href(value) { this._update(value); if (this._params) this._params._parse(this.search); } // https://url.spec.whatwg.org/#dom-url-protocol get protocol() { return this._slice(0, this._schemeEnd) + ":"; } set protocol(value) { this._update(this._replace(value.replace(/:+$/, ""), 0, this._schemeEnd)); } // https://url.spec.whatwg.org/#dom-url-username get username() { return this._slice(this._schemeEnd + 3, this._usernameEnd); } set username(value) { if (cannotHaveCredentialsOrPort(this)) { return; } if (this.username === "") value += "@"; this._update(this._replace(value, this._schemeEnd + 3, this._usernameEnd)); } // https://url.spec.whatwg.org/#dom-url-password get password() { return this._href.slice( this._usernameEnd + 1, this._hostStart - 1 /* @ */ ); } set password(value) { if (cannotHaveCredentialsOrPort(this)) { return; } let start = this._usernameEnd + 1; let end = this._hostStart - 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._hostStart, this._pathStart); } set host(value) { if (hasOpaquePath(this)) { return; } this._update( this._replace(value, this._hostStart, value.includes(":") ? this._pathStart : this._hostEnd) ); } // https://url.spec.whatwg.org/#dom-url-hostname get hostname() { return this._slice(this._hostStart, this._hostEnd); } set hostname(value) { if (hasOpaquePath(this)) { return; } this._update(this._replace(value, this._hostStart, this._hostEnd)); } // https://url.spec.whatwg.org/#dom-url-port get port() { return this._slice(this._hostEnd + 1, this._pathStart); } set port(value) { if (cannotHaveCredentialsOrPort(this)) { return; } let start = this._hostEnd + 1; if (this.port === "") { value = ":" + value; start--; } this._update(this._replace(value, start, this._pathStart)); } // https://url.spec.whatwg.org/#dom-url-pathname get pathname() { return this._slice( this._pathStart, this._queryStart - 1 /* ? */ ); } set pathname(value) { if (hasOpaquePath(this)) { return; } if (value[0] !== "/" && value[0] !== "\\") { value = "/" + value; } this._update(this._replace( value, this._pathStart, this._queryStart - 1 /* ? */ )); } // https://url.spec.whatwg.org/#dom-url-search get search() { return this._slice( this._queryStart - 1, this._fragmentStart - 1 /* # */ ); } set search(value) { if (value && value[0] !== "?") value = "?" + value; this._update( this._replace( value, this._queryStart - 1, this._fragmentStart - 1 /* # */ ) ); if (this._params) this._params._parse(this.search); } // https://url.spec.whatwg.org/#dom-url-searchparams get searchParams() { if (this._params === null) { this._params = new URLSearchParams2(this.search, this); } return this._params; } // https://url.spec.whatwg.org/#dom-url-hash get hash() { return this._slice( this._fragmentStart - 1 /* # */ ); } set hash(value) { if (value && value[0] !== "#") value = "#" + value; this._update(this._replace( value, this._fragmentStart - 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) { let href; try { href = binding.parse(input, base || null, components, shouldThrow); } catch (err) { if (err instanceof TypeError) throw err; throw errors.INVALID_URL(`Invalid URL '${input}'`, input); } if (href === void 0) return; this._href = href; this._schemeEnd = components[0]; this._usernameEnd = components[1]; this._hostStart = components[2]; this._hostEnd = components[3]; this._pathStart = components[5]; const queryStart = components[6]; const fragmentStart = components[7]; const end = href.length + 1; this._queryStart = queryStart === unset ? end : queryStart; this._fragmentStart = fragmentStart === unset ? end : fragmentStart; } _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 = URLSearchParams2; 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 = URLSearchParams2.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 && url.hostname) { throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty"); } const encoded = url.pathname; const hasEncoded = encoded.includes("%"); if (hasEncoded) { if (isWindows) { if (/%2f|%5c/i.test(encoded)) { throw errors.INVALID_FILE_URL_PATH( "The file: URL path must not include encoded \\ or / characters" ); } } else if (/%2f/i.test(encoded)) { throw errors.INVALID_FILE_URL_PATH("The file: URL path must not include encoded / characters"); } if (/%00/i.test(encoded)) { throw errors.INVALID_FILE_URL_PATH( "The file: URL path must not include encoded NUL characters" ); } } const pathname = path.normalize(hasEncoded ? decodeURIComponent(encoded) : encoded); 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 += "\\"; } if (reserved.test(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 URLSearchParams2(query); } if (typeof hash === "string") { if (hash[0] !== "#") result += "#"; result += hash; } return result; }; } }); // ../bare-os-openssh/vendor/bare-node-shims/bare-node-events/index.js var require_bare_node_events = __commonJS({ "../bare-os-openssh/vendor/bare-node-shims/bare-node-events/index.js"(exports, module) { module.exports = require_bare_events(); } }); // ../../node_modules/events-universal/default.js var require_default = __commonJS({ "../../node_modules/events-universal/default.js"(exports, module) { module.exports = require_bare_node_events(); } }); // ../../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 b4a2 = require_b4a(); module.exports = class PassThroughDecoder { constructor(encoding) { this.encoding = encoding; } get remaining() { return 0; } decode(data) { return b4a2.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 b4a2 = 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 b4a2.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 += b4a2.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/lib/errors.js var require_errors4 = __commonJS({ "../../node_modules/streamx/lib/errors.js"(exports, module) { module.exports = class StreamError extends Error { constructor(msg, code, fn = StreamError) { super(msg); this.code = code; if (Error.captureStackTrace) { Error.captureStackTrace(this, fn); } } static isStreamDestroyed(err) { return err && err.code === "STREAM_DESTROYED"; } static isPrematureClose(err) { return err && err.code === "PREMATURE_CLOSE"; } static isAborted(err) { return err && err.code === "ABORTED"; } static isBadArgument(err) { return err && err.code === "BAD_ARGUMENT"; } get name() { return "StreamError"; } static STREAM_DESTROYED() { return new StreamError("Stream was destroyed", "STREAM_DESTROYED", StreamError.STREAM_DESTROYED); } static PREMATURE_CLOSE(msg = "Premature close") { return new StreamError(msg, "PREMATURE_CLOSE", StreamError.PREMATURE_CLOSE); } static ABORTED() { return new StreamError("Stream aborted", "ABORTED", StreamError.ABORTED); } static BAD_ARGUMENT(msg = "Bad argument") { return new StreamError(msg, "BAD_ARGUMENT", StreamError.BAD_ARGUMENT); } }; } }); // ../../node_modules/streamx/index.js var require_streamx = __commonJS({ "../../node_modules/streamx/index.js"(exports, module) { var { EventEmitter } = require_default(); var FIFO = require_fast_fifo(); var TextDecoder = require_text_decoder(); var StreamError = require_errors4(); 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 StreamError.BAD_ARGUMENT("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 || StreamError.PREMATURE_CLOSE("Writable stream closed")); } return; } } if (stream === this.from) { this.from = null; if (this.to !== null) { if ((stream._duplexState & READ_DONE) === 0) { this.to.destroy(this.error || StreamError.PREMATURE_CLOSE("Readable stream closed")); } 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 && !StreamError.isStreamDestroyed(this.error)) 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 = StreamError.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); } } static deferred(fn, opts) { const out = new PassThrough(opts); fn().then((src) => { if (src === null) return out.end(); if (out.destroying) return; pipeline(src, out, noop); }).catch((err) => out.destroy(err)); return out; } 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(StreamError.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 StreamError.BAD_ARGUMENT("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 : StreamError.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(StreamError.PREMATURE_CLOSE()); } if (wr && s._writableState && !s._writableState.ended) { return onerror2(StreamError.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 && StreamError.isStreamDestroyed(err) ? 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(StreamError.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_web = __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); try { let starting = Promise.resolve(); if (start) starting = forwardError(start.call(this, controller), controller); if (pull) { this._stream._read = this._read.bind(this, starting, pull.bind(this, controller)); } if (cancel) { this._stream.once("error", cancel.bind(this)); } } catch (err) { controller.error(err); } } 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 _read(starting, pull, cb) { await starting; 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 }); const controller = new exports.WritableStreamDefaultController(this); this._controller = controller; try { let starting = Promise.resolve(); if (start) starting = forwardError(start.call(this, controller), controller); if (write) { this._stream._write = this._write.bind(this, starting, write.bind(this)); } if (close) { this._stream._destroy = this._destroy.bind(this, close.call(this)); } if (abort) { this._stream.once("error", abort.bind(this)); } } catch (err) { controller.error(err); } } 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 _write(starting, write, data, cb) { await starting; 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 = {}) { if (isStreamx(transformer)) { this._stream = transformer; } else { const { start, transform, flush } = transformer; this._stream = new Transform({ ...writableStrategy, ...readableStrategy }); const controller = new exports.TransformStreamDefaultController(this); this._controller = controller; try { let starting = Promise.resolve(); if (start) starting = forwardError(start.call(this, controller), controller); if (transform) { this._stream._transform = this._transform.bind(this, starting, transform.bind(this)); } if (flush) { this._stream._flush = this._flush.bind(this, flush.call(this, this._controller)); } } catch (err) { controller.error(err); } } this._writable = new WritableStream(this._stream); this._readable = new ReadableStream(this._stream); } get [transformKind]() { return _TransformStream[transformKind]; } get writable() { return this._writable; } get readable() { return this._readable; } async _transform(starting, transform, data, cb) { await starting; 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]; }; async function forwardError(promise, controller) { try { await promise; } catch (err) { controller.error(err); } } function noop() { } } }); // ../../node_modules/bare-stream/index.js var require_bare_stream = __commonJS({ "../../node_modules/bare-stream/index.js"(exports, module) { var b4a2 = require_b4a(); var stream = require_streamx(); var { ReadableStream, WritableStream } = require_web(); 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 = read2.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 = b4a2.from(chunk, encoding || defaultEncoding); } return super.push(chunk); } unshift(chunk, encoding) { if (typeof chunk === "string") { chunk = b4a2.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 = b4a2.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 = b4a2.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 = read2.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 = b4a2.from(chunk, encoding || defaultEncoding); } return super.push(chunk); } unshift(chunk, encoding) { if (typeof chunk === "string") { chunk = b4a2.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 = b4a2.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 = b4a2.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.Writable.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 = b4a2.from(chunk, encoding || defaultEncoding); } return super.push(chunk); } unshift(chunk, encoding) { if (typeof chunk === "string") { chunk = b4a2.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 = b4a2.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 = b4a2.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 read2(read3, cb) { read3.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-fs/binding.js var require_binding13 = __commonJS({ "../../node_modules/bare-fs/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-fs/lib/constants.js var require_constants3 = __commonJS({ "../../node_modules/bare-fs/lib/constants.js"(exports, module) { var binding = require_binding13(); 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_errors5 = __commonJS({ "../../node_modules/bare-fs/lib/errors.js"(exports, module) { var binding = require_binding13(); 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 binding.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 fs5 = require_bare_fs(); var FileHandle = class extends EventEmitter { constructor(fd) { super(); this.fd = fd; } async close() { await fs5.close(this.fd); this.fd = -1; this.emit("close"); } async read(buffer, ...args) { return { bytesRead: await fs5.read(this.fd, buffer, ...args), buffer }; } async readv(buffers, ...args) { return { bytesRead: await fs5.readv(this.fd, buffers, ...args), buffers }; } async write(buffer, ...args) { return { bytesWritten: await fs5.write(this.fd, buffer, ...args), buffer }; } async writev(buffers, ...args) { return { bytesWritten: await fs5.writev(this.fd, buffers, ...args), buffers }; } async stat() { return fs5.fstat(this.fd); } async chmod(mode) { await fs5.fchmod(this.fd, mode); } async chown(uid, gid) { await fs5.fchown(this.fd, uid, gid); } async datasync() { return fs5.fdatasync(this.fd); } async sync() { return fs5.fsync(this.fd); } async truncate(len) { await fs5.ftruncate(this.fd, len); } async utimes(atime, mtime) { await fs5.futimes(this.fd, atime, mtime); } createReadStream(opts) { return fs5.createReadStream(null, { ...opts, fd: this.fd }); } createWriteStream(opts) { return fs5.createWriteStream(null, { ...opts, fd: this.fd }); } async [Symbol.asyncDispose]() { await this.close(); } }; exports.open = async function open(filepath, flags, mode) { return new FileHandle(await fs5.open(filepath, flags, mode)); }; exports.access = fs5.access; exports.appendFile = fs5.appendFile; exports.chmod = fs5.chmod; exports.chown = fs5.chown; exports.constants = fs5.constants; exports.copyFile = fs5.copyFile; exports.cp = fs5.cp; exports.lchown = fs5.lchown; exports.lutimes = fs5.lutimes; exports.link = fs5.link; exports.lstat = fs5.lstat; exports.mkdir = fs5.mkdir; exports.mkdtemp = fs5.mkdtemp; exports.opendir = fs5.opendir; exports.readFile = fs5.readFile; exports.readdir = fs5.readdir; exports.readlink = fs5.readlink; exports.realpath = fs5.realpath; exports.rename = fs5.rename; exports.rm = fs5.rm; exports.rmdir = fs5.rmdir; exports.stat = fs5.stat; exports.statfs = fs5.statfs; exports.truncate = fs5.truncate; exports.symlink = fs5.symlink; exports.unlink = fs5.unlink; exports.utimes = fs5.utimes; exports.watch = fs5.watch; exports.writeFile = fs5.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_binding13(); var constants = require_constants3(); var FileError = require_errors5(); 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 read2(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); req.retain(buffer); 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); req.retain(buffers); 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); req.retain(data); 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); req.retain(buffers); 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 statfs(filepath, cb) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let st; let err = null; try { binding.statfs(req.handle, filepath); await req; st = new StatFs(...binding.requestResultStatfs(req.handle)); } catch (e) { err = new FileError(e.message, { operation: "statfs", code: e.code, path: filepath }); } finally { req.return(); } return done(err, st, cb); } function statfsSync(filepath) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.statfsSync(req.handle, filepath); return new StatFs(...binding.requestResultStatfs(req.handle)); } catch (e) { throw new FileError(e.message, { operation: "statfs", code: e.code, path: filepath }); } 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 truncate(filepath, len, cb) { let fd = -1; let err; try { fd = await open(filepath, "r+"); await ftruncate(fd, len); } catch (e) { err = e; } finally { if (fd !== -1) await close(fd); } return done(err, cb); } function truncateSync(filepath, len) { let fd = -1; let err; try { fd = openSync(filepath, "r+"); ftruncateSync(fd, len); } catch (e) { err = e; } finally { if (fd !== -1) closeSync(fd); } } 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 chown(filepath, uid, gid, cb) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let err = null; try { binding.chown(req.handle, filepath, uid, gid); await req; } catch (e) { err = new FileError(e.message, { operation: "chown", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function chownSync(filepath, uid, gid) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.chownSync(req.handle, filepath, uid, gid); } catch (e) { throw new FileError(e.message, { operation: "chownSync", code: e.code, path: filepath }); } finally { req.return(); } } async function lchown(filepath, uid, gid, cb) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let err = null; try { binding.lchown(req.handle, filepath, uid, gid); await req; } catch (e) { err = new FileError(e.message, { operation: "lchown", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function lchownSync(filepath, uid, gid) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.lchownSync(req.handle, filepath, uid, gid); } catch (e) { throw new FileError(e.message, { operation: "lchownSync", code: e.code, path: filepath }); } finally { req.return(); } } async function fchown(fd, uid, gid, cb) { const req = FileRequest.borrow(); let err = null; try { binding.fchown(req.handle, fd, uid, gid); await req; } catch (e) { err = new FileError(e.message, { operation: "fchown", code: e.code, fd }); } finally { req.return(); } return done(err, cb); } function fchownSync(fd, uid, gid) { const req = FileRequest.borrow(); try { binding.fchownSync(req.handle, fd, uid, gid); } catch (e) { throw new FileError(e.message, { operation: "fchownSync", 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 lutimes(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.lutimes(req.handle, filepath, atime, mtime); await req; } catch (e) { err = new FileError(e.message, { operation: "lutimes", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function lutimesSync(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.lutimesSync(req.handle, filepath, atime, mtime); } catch (e) { throw new FileError(e.message, { operation: "lutimes", code: e.code, path: filepath }); } finally { req.return(); } } async function futimes(fd, atime, mtime, cb) { if (typeof atime !== "number") atime = atime.getTime() / 1e3; if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3; const req = FileRequest.borrow(); let err = null; try { binding.futimes(req.handle, fd, atime, mtime); await req; } catch (e) { err = new FileError(e.message, { operation: "futimes", code: e.code, fd }); } finally { req.return(); } return done(err, cb); } function futimesSync(fd, atime, mtime) { if (typeof atime !== "number") atime = atime.getTime() / 1e3; if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3; const req = FileRequest.borrow(); try { binding.futimesSync(req.handle, fd, atime, mtime); } catch (e) { throw new FileError(e.message, { operation: "futimesSync", code: e.code, fd }); } finally { req.return(); } } async function link(src, dst, cb) { src = toNamespacedPath(src); dst = toNamespacedPath(dst); const req = FileRequest.borrow(); let err = null; try { binding.link(req.handle, src, dst); await req; } catch (e) { err = new FileError(e.message, { operation: "link", code: e.code, path: src, destination: dst }); } finally { req.return(); } return done(err, cb); } function linkSync(src, dst) { src = toNamespacedPath(src); dst = toNamespacedPath(dst); const req = FileRequest.borrow(); try { binding.linkSync(req.handle, src, dst); } catch (e) { throw new FileError(e.message, { operation: "linkSync", code: e.code, path: src, destination: dst }); } 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 mkdtemp(prefix, cb) { prefix = toNamespacedPath(prefix); const req = FileRequest.borrow(); let res; let err = null; try { binding.mkdtemp(req.handle, prefix + "XXXXXX"); await req; res = binding.requestResultPath(req.handle); } catch (e) { err = new FileError(e.message, { operation: "mkdtemp", code: e.code, path: prefix }); } finally { req.return(); } return done(err, res, cb); } function mkdtempSync(prefix) { prefix = toNamespacedPath(prefix); const req = FileRequest.borrow(); try { binding.mkdtempSync(req.handle, prefix + "XXXXXX"); return binding.requestResultPath(req.handle); } catch (e) { throw new FileError(e.message, { operation: "mkdtempSync", code: e.code, path: prefix }); } 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(); } } async function fsync(fd, cb) { const req = FileRequest.borrow(); let err = null; try { binding.fsync(req.handle, fd); await req; } catch (e) { err = new FileError(e.message, { operation: "fsync", code: e.code, fd }); } finally { req.return(); } return done(err, cb); } function fsyncSync(fd) { const req = FileRequest.borrow(); try { binding.fsyncSync(req.handle, fd); } catch (e) { throw new FileError(e.message, { operation: "fsyncSync", code: e.code, fd }); } finally { req.return(); } } async function fdatasync(fd, cb) { const req = FileRequest.borrow(); let err = null; try { binding.fdatasync(req.handle, fd); await req; } catch (e) { err = new FileError(e.message, { operation: "fdatasync", code: e.code, fd }); } finally { req.return(); } return done(err, cb); } function fdatasyncSync(fd) { const req = FileRequest.borrow(); try { binding.fdatasyncSync(req.handle, fd); } catch (e) { throw new FileError(e.message, { operation: "fdatasyncSync", code: e.code, fd }); } 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, recursive = false } = opts; filepath = toNamespacedPath(filepath); const queue = [filepath]; let result = []; let err = null; try { while (queue.length !== 0) { const dir = await opendir(queue.pop()); for await (const entry of dir) { const entryPath = path.join(entry.parentPath, entry.name); if (withFileTypes) { result.push(entry); } else { result.push(path.relative(filepath, entryPath)); } if (recursive && entry.isDirectory()) queue.push(entryPath); } } } 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, recursive = false } = opts; filepath = toNamespacedPath(filepath); const queue = [filepath]; const result = []; while (queue.length !== 0) { const dir = opendirSync(queue.pop(), opts); for (const entry of dir) { const entryPath = path.join(entry.parentPath, entry.name); if (withFileTypes) { result.push(entry); } else { result.push(path.relative(filepath, entryPath)); } if (recursive && entry.isDirectory()) queue.push(entryPath); } } 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 read2(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 read2(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 StatFs = class { constructor(type, bsize, blocks, bfree, bavail, files, ffree, frsize) { this.type = type; this.bsize = bsize; this.blocks = blocks; this.bfree = bfree; this.bavail = bavail; this.files = files; this.ffree = ffree; this.frsize = frsize; } }; 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 read2(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.chown = chown; exports.close = close; exports.copyFile = copyFile; exports.cp = cp; exports.exists = exists; exports.fchmod = fchmod; exports.fchown = fchown; exports.fdatasync = fdatasync; exports.fstat = fstat; exports.fsync = fsync; exports.ftruncate = ftruncate; exports.futimes = futimes; exports.lchown = lchown; exports.lutimes = lutimes; exports.link = link; exports.lstat = lstat; exports.mkdir = mkdir; exports.mkdtemp = mkdtemp; exports.open = open; exports.opendir = opendir; exports.read = read2; 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.statfs = statfs; exports.symlink = symlink; exports.truncate = truncate; 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.chownSync = chownSync; exports.closeSync = closeSync; exports.copyFileSync = copyFileSync; exports.cpSync = cpSync; exports.existsSync = existsSync; exports.fchmodSync = fchmodSync; exports.fchownSync = fchownSync; exports.fdatasyncSync = fdatasyncSync; exports.fstatSync = fstatSync; exports.fsyncSync = fsyncSync; exports.ftruncateSync = ftruncateSync; exports.futimesSync = futimesSync; exports.lchownSync = lchownSync; exports.lutimesSync = lutimesSync; exports.linkSync = linkSync; exports.lstatSync = lstatSync; exports.mkdirSync = mkdirSync; exports.mkdtempSync = mkdtempSync; 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.statfsSync = statfsSync; exports.symlinkSync = symlinkSync; exports.truncateSync = truncateSync; exports.unlinkSync = unlinkSync; exports.utimesSync = utimesSync; exports.writeFileSync = writeFileSync; exports.writeSync = writeSync; exports.writevSync = writevSync; exports.promises = require_promises(); exports.Stats = Stats; exports.StatFs = StatFs; 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-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_errors6 = __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 bareOsHttp501Factory(msg = "Method not implemented") { return new HTTPError(msg, HTTPError.bareOsHttp501Factory); } 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); } static INVALID_HEADER_NAME(msg = "Invalid header name") { return new HTTPError(msg, HTTPError.INVALID_HEADER_NAME); } static INVALID_HEADER_VALUE(msg = "Invalid header value") { return new HTTPError(msg, HTTPError.INVALID_HEADER_VALUE); } }; } }); // ../../node_modules/bare-http1/lib/validate.js var require_validate = __commonJS({ "../../node_modules/bare-http1/lib/validate.js"(exports) { var errors = require_errors6(); var TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; var VALUE_INVALID_RE = /[\r\n\0]/; var PATH_INVALID_RE = /[\r\n\0\s]/; exports.validateHeaderName = function(name) { if (typeof name !== "string" || !TOKEN_RE.test(name)) { throw errors.INVALID_HEADER_NAME(`Invalid header name: ${JSON.stringify(name)}`); } }; exports.validateHeaderValue = function(name, value) { if (value === void 0 || value === null) return; if (VALUE_INVALID_RE.test(String(value))) { throw errors.INVALID_HEADER_VALUE( `Invalid character in header value for ${JSON.stringify(name)}` ); } }; exports.validateStatusMessage = function(value) { if (value === void 0 || value === null) return; if (VALUE_INVALID_RE.test(String(value))) { throw errors.INVALID_HEADER_VALUE("Invalid character in status message"); } }; exports.validatePath = function(value) { if (typeof value !== "string" || value.length === 0 || PATH_INVALID_RE.test(value)) { throw errors.INVALID_HEADER_VALUE(`Invalid character in request path: ${JSON.stringify(value)}`); } }; exports.validateMethod = function(value) { if (typeof value !== "string" || !TOKEN_RE.test(value)) { throw errors.INVALID_HEADER_NAME(`Invalid HTTP method: ${JSON.stringify(value)}`); } }; } }); // ../../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_errors6(); var validate = require_validate(); 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) { if (value) { for (const name of Object.keys(value)) { const n = name.toLowerCase(); validate.validateHeaderName(n); validate.validateHeaderValue(n, value[name]); } } 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) { const n = name.toLowerCase(); validate.validateHeaderName(n); validate.validateHeaderValue(n, value); this._headers[n] = 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.bareOsHttp501Factory(); } _predestroy() { if (this._upgrade === false && this._socket !== null) this._socket.destroy(); } }; } }); // ../../node_modules/bare-dns/binding.js var require_binding14 = __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_binding14(); 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_binding15 = __commonJS({ "../../node_modules/bare-tcp/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-tcp/lib/constants.js var require_constants4 = __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_errors7 = __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); } static INVALID_PORT(msg) { return new TCPError(msg, TCPError.INVALID_PORT); } }; } }); // ../../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_binding15(); var constants = require_constants4(); var errors = require_errors7(); var ip = require_ip(); var defaultReadBufferSize = 65536; var empty = Buffer.alloc(0); var ipcHandle = Symbol.for("bare.ipc.handle"); var ipcAccept = Symbol.for("bare.ipc.accept"); 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._pendingWriteBatch = 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; } get [ipcHandle]() { return this._handle; } 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"); } 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"; validatePort(port); this._state |= constants.state.CONNECTING; 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) { this._state &= ~constants.state.CONNECTING; queueMicrotask(() => { if (this._pendingOpen) this._pendingOpen(err); else this.destroy(err); }); } return this; } open(fd, opts = {}, onconnect) { if (typeof opts === "function") { onconnect = opts; opts = {}; } if (typeof fd === "object" && fd !== null) { opts = fd; fd = opts.fd; } try { binding.open(this._handle, fd); this._state |= constants.state.CONNECTED; 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; } 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; } [ipcAccept]() { this._onaccept(); } _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; this._pendingWriteBatch = batch; try { binding.writev( this._handle, batch.map(({ chunk }) => chunk) ); } catch (err) { this._continueWrite(err); } } _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; this._pendingWrite = null; this._pendingWriteBatch = 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); } _updateAddresses() { try { this._localAddress = binding.address(this._handle, true); } catch { this._localAddress = null; } try { this._remoteAddress = binding.address(this._handle, false); } catch { this._remoteAddress = null; } } _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); } this._state &= ~constants.state.CONNECTING; 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._updateAddresses(); this._state |= constants.state.CONNECTED; this._state &= ~constants.state.CONNECTING; this._continueOpen(); this.emit("connect"); } _onaccept() { this._updateAddresses(); this._state |= constants.state.CONNECTED; this._continueOpen(); } _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, read2) { if (this._timer) this._timer.refresh(); if (err) { this.destroy(err); return; } if (read2 === 0) { this.push(null); if (this._allowHalfOpen === false) this.end(); return; } const copy = Buffer.allocUnsafe(read2); copy.set(this._buffer.subarray(0, read2)); 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._continueOpen(); 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, maxConnections = Infinity } = opts; this._state = 0; this._readBufferSize = readBufferSize; this._allowHalfOpen = allowHalfOpen; this._keepAlive = keepAlive; this._keepAliveInitialDelay = keepAliveInitialDelay; this._noDelay = noDelay; this._pauseOnConnect = pauseOnConnect; this._maxConnections = maxConnections; 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; } get maxConnections() { return this._maxConnections; } set maxConnections(value) { this._maxConnections = value; } 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"); } 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; validatePort(port); this._state |= constants.state.BINDING; 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 overLimit = this._connections.size >= this._maxConnections; const socket = new exports.Socket({ readBufferSize: overLimit ? 0 : this._readBufferSize, allowHalfOpen: this._allowHalfOpen, eagerOpen: !this._pauseOnConnect }); try { binding.accept(this._handle, socket._handle); socket._onaccept(); if (overLimit) { const info = { localAddress: socket.localAddress, localPort: socket.localPort, localFamily: socket.localFamily, remoteAddress: socket.remoteAddress, remotePort: socket.remotePort, remoteFamily: socket.remoteFamily }; socket.destroy(); this.emit("drop", info); return; } 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._state &= ~constants.state.BOUND; 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); }; exports.socketpair = function socketpair() { return binding.socketpair(); }; function validatePort(port) { if (typeof port !== "number") { throw errors.INVALID_PORT(`Port must be a number, got ${typeof port}`); } if (!Number.isInteger(port) || port < 0 || port > 65535) { throw errors.INVALID_PORT(`Port must be an integer between 0 and 65535, got ${port}`); } } function noop() { } } }); // ../../node_modules/bare-http-parser/lib/errors.js var require_errors8 = __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_errors8(); 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 = /* @__PURE__ */ Object.create(null); 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 slice2 = current.subarray(this._byteIndex, this._byteIndex + n); this._byteIndex += n; if (this._byteIndex >= current.byteLength) { this._bufferIndex++; this._byteIndex = 0; } return slice2; } 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 = /* @__PURE__ */ Object.create(null); 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"]; if (transferEncoding) { const encodings = transferEncoding.split(","); let chunkedCount = 0; for (let i = 0, n = encodings.length; i < n; i++) { if (encodings[i].trim().toLowerCase() === "chunked") chunkedCount++; } const lastEncoding = encodings[encodings.length - 1].trim().toLowerCase(); if (lastEncoding !== "chunked") { throw errors.INVALID_MESSAGE("'Transfer-Encoding' must end with 'chunked'"); } if (chunkedCount > 1) { throw errors.INVALID_MESSAGE( "'chunked' must not appear more than once in 'Transfer-Encoding'" ); } 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_errors6(); 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_errors6(); 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("error", noop).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)); function noop() { } } }); // ../../node_modules/bare-http1/lib/constants.js var require_constants5 = __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_constants5(); var validate = require_validate(); 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) { validate.validateStatusMessage(value); this._statusMessage = value; } writeHead(statusCode, statusMessage = null, headers = {}) { if (typeof statusMessage === "object" && statusMessage !== null) { headers = statusMessage; statusMessage = null; } if (statusMessage !== null) validate.validateStatusMessage(statusMessage); if (headers) { for (const name of Object.keys(headers)) { const n = name.toLowerCase(); validate.validateHeaderName(n); validate.validateHeaderValue(n, headers[name]); } } this._statusCode = statusCode; this._statusMessage = statusMessage || null; if (headers) this._headers = { ...this._headers, ...headers }; } _header() { const statusMessage = this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage; validate.validateStatusMessage(statusMessage); let h = "HTTP/1.1 " + this._statusCode + " " + statusMessage + "\r\n"; for (const name of Object.keys(this._headers)) { const n = name.toLowerCase(); const v = this._headers[name]; validate.validateHeaderName(n); validate.validateHeaderValue(n, v); 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 validate = require_validate(); 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 }; validate.validateMethod(method); validate.validatePath(path); for (const name of Object.keys(headers)) { const n = name.toLowerCase(); validate.validateHeaderName(n); validate.validateHeaderValue(n, headers[name]); } 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() { validate.validateMethod(this._method); validate.validatePath(this._path); 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]; validate.validateHeaderName(n); validate.validateHeaderValue(n, v); 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_constants5(); exports.errors = require_errors6(); 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-media/node_modules/bare-tls/binding.js var require_binding16 = __commonJS({ "../../node_modules/bare-media/node_modules/bare-tls/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-media/node_modules/bare-tls/lib/constants.js var require_constants6 = __commonJS({ "../../node_modules/bare-media/node_modules/bare-tls/lib/constants.js"(exports, module) { module.exports = { state: { CONNECTED: 1, ATTACHED: 2 } }; } }); // ../../node_modules/bare-media/node_modules/bare-tls/lib/errors.js var require_errors9 = __commonJS({ "../../node_modules/bare-media/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_binding17 = __commonJS({ "../../node_modules/bare-pipe/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-pipe/lib/constants.js var require_constants7 = __commonJS({ "../../node_modules/bare-pipe/lib/constants.js"(exports, module) { var binding = require_binding17(); module.exports = { state: { CONNECTING: 1, CONNECTED: 2, BINDING: 4, BOUND: 8, READING: 16, CLOSING: 32, READABLE: 64, WRITABLE: 128, UNREFED: 256 }, handle: { NAMED_PIPE: binding.UV_NAMED_PIPE, TCP: binding.UV_TCP, UDP: binding.UV_UDP } }; } }); // ../../node_modules/bare-pipe/lib/errors.js var require_errors10 = __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); } static INVALID_IPC_TARGET(msg) { return new PipeError(msg, PipeError.INVALID_IPC_TARGET); } }; } }); // ../../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_binding17(); var constants = require_constants7(); var errors = require_errors10(); var defaultReadBufferSize = 65536; var empty = Buffer.alloc(0); var ipcHandle = Symbol.for("bare.ipc.handle"); var ipcAccept = Symbol.for("bare.ipc.accept"); 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, ipc = false } = opts; super({ eagerOpen }); this._state = 0; this._allowHalfOpen = allowHalfOpen; this._ipc = ipc; this._fd = -1; this._path = null; this._pendingOpen = null; this._pendingWrite = null; this._pendingWriteBatch = null; this._pendingWriteSegments = null; this._pendingWriteIdx = 0; this._pendingFinal = null; this._pendingDestroy = null; this._handleQueue = []; this._handleQueueSize = 0; this._buffer = Buffer.alloc(readBufferSize); this._handle = binding.init( this._buffer, ipc, this, noop, this._onconnect, this._onwrite, this._onfinal, this._onread, this._onhandle, 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"; } get [ipcHandle]() { return this._handle; } 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) { this._state &= ~constants.state.CONNECTING; queueMicrotask(() => { if (this._pendingOpen) this._pendingOpen(err); else this.destroy(err); }); } return this; } write(chunk, encoding, handle, cb) { if (typeof encoding === "function") { cb = encoding; encoding = void 0; handle = null; } else if (typeof encoding === "object" && encoding !== null) { if (typeof handle === "function") cb = handle; handle = encoding; encoding = void 0; } else if (typeof handle === "function") { cb = handle; handle = null; } if (handle) this._handleQueueSize++; this._handleQueue.push(handle || null); if (encoding) return super.write(chunk, encoding, cb); return super.write(chunk, cb); } accept(target) { const handle = target[ipcHandle]; if (handle === void 0) { throw errors.INVALID_IPC_TARGET("Target does not implement the IPC handle protocol"); } binding.accept(this._handle, handle); if (typeof target[ipcAccept] === "function") target[ipcAccept](); return target; } ref() { binding.ref(this._handle); return this; } unref() { binding.unref(this._handle); return this; } [ipcAccept]() { this._onaccept(); } _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; this._pendingWriteBatch = batch; if (this._handleQueueSize === 0) { this._handleQueue = []; this._pendingWriteSegments = null; try { binding.writev( this._handle, batch.map(({ chunk }) => chunk), null ); } catch (err) { this._continueWrite(err); } return; } const handles = this._handleQueue.splice(0, batch.length); for (let i2 = 0; i2 < batch.length; i2++) { if (handles[i2] === void 0) handles[i2] = null; else if (handles[i2] !== null) this._handleQueueSize--; } const segments = []; let i = 0; while (i < batch.length) { if (handles[i] !== null) { segments.push({ chunks: [batch[i]], handle: handles[i] }); i++; } else { const start = i; while (i < batch.length && handles[i] === null) i++; segments.push({ chunks: batch.slice(start, i), handle: null }); } } this._pendingWriteSegments = segments; this._pendingWriteIdx = 0; this._writeNextSegment(); } _writeNextSegment() { const segment = this._pendingWriteSegments[this._pendingWriteIdx]; const chunks = []; for (let i = 0; i < segment.chunks.length; i++) { chunks.push(segment.chunks[i].chunk); } let sendHandle = null; if (segment.handle !== null) sendHandle = segment.handle[ipcHandle]; try { binding.writev(this._handle, chunks, sendHandle); } catch (err) { this._continueWrite(err); } } _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; if (this._pendingWriteSegments === null) { const cb2 = this._pendingWrite; this._pendingWrite = null; this._pendingWriteBatch = null; cb2(err); return; } this._pendingWriteIdx++; if (err === null && this._pendingWriteIdx < this._pendingWriteSegments.length) { this._writeNextSegment(); return; } const cb = this._pendingWrite; this._pendingWrite = null; this._pendingWriteBatch = null; this._pendingWriteSegments = null; this._pendingWriteIdx = 0; 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) { this._state &= ~constants.state.CONNECTING; 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"); } _onaccept() { this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE; this._continueOpen(); } _onread(err, read2) { if (err) { this.destroy(err); return; } if (read2 === 0) { this.push(null); if (this._allowHalfOpen === false) this.end(); return; } const copy = Buffer.allocUnsafe(read2); copy.set(this._buffer.subarray(0, read2)); if (this.push(copy) === false && this.destroying === false) { this._state &= ~constants.state.READING; binding.pause(this._handle); } } _onhandle(type) { this.emit("handle", type); } _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, ipc = false } = opts; this._state = 0; this._readBufferSize = readBufferSize; this._allowHalfOpen = allowHalfOpen; this._pauseOnConnect = pauseOnConnect; this._ipc = ipc; 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._ipc, 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, 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, ipc: this._ipc }); try { binding.accept(this._handle, pipe._handle); pipe._path = this._path; pipe._onaccept(); 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._state &= ~constants.state.BOUND; 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() { } } }); // ../bare-os-openssh/vendor/bare-node-shims/bare-net/lib/constants.js var require_constants8 = __commonJS({ "../bare-os-openssh/vendor/bare-node-shims/bare-net/lib/constants.js"(exports, module) { module.exports = { type: { TCP: 1, IPC: 2 }, state: { UNREFED: 1 } }; } }); // ../bare-os-openssh/vendor/bare-node-shims/bare-net/index.js var require_bare_net = __commonJS({ "../bare-os-openssh/vendor/bare-node-shims/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_constants8(); 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-media/node_modules/bare-tls/net.js var require_net = __commonJS({ "../../node_modules/bare-media/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, rejectUnauthorized = true, ca = null, alpnProtocols = null, eagerOpen = true, allowHalfOpen = true } = opts; super(); this._opts = { cert, key, host, rejectUnauthorized, ca, 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]; } if (!opts.host && !opts.path) opts.host = "localhost"; return new TLSNetSocket(net.createConnection(opts, onconnect), opts); }; exports.createServer = function createServer(opts, onconnection) { return new TLSNetServer(opts, onconnection); }; } }); // ../../node_modules/bare-media/node_modules/bare-tls/index.js var require_bare_tls = __commonJS({ "../../node_modules/bare-media/node_modules/bare-tls/index.js"(exports) { var { Duplex, Writable } = require_bare_stream(); var binding = require_binding16(); var constants = require_constants6(); var errors = require_errors9(); 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, rejectUnauthorized = true, ca = null, alpnProtocols = null, eagerOpen = true, allowHalfOpen = true, readBufferSize = defaultReadBufferSize } = opts; if (!isServer && rejectUnauthorized && !host) { throw new TypeError("'host' is required for client sockets when 'rejectUnauthorized' is true"); } super({ eagerOpen }); this._state = 0; this._socket = socket; this._allowHalfOpen = allowHalfOpen; this._pendingOpen = null; this._pendingWrite = null; this._pendingDestroy = null; this._reading = Buffer.alloc(readBufferSize); this._buffer = []; this._buffered = 0; this._ondata = this._ondata.bind(this); this._ondrain = this._ondrain.bind(this); this._onend = this._onend.bind(this); this._onclose = this._onclose.bind(this); this._onerror = this._onerror.bind(this); socket.on("close", this._onclose).on("error", this._onerror); 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, rejectUnauthorized, ca, 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 this._handle ? binding.alpnProtocol(this._handle) : null; } _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 read2; try { read2 = binding.read(this._handle, this._reading); } catch (err) { return this.destroy(errors.from(err)); } if (read2 < 0) break; if (read2 === 0) { this.push(null); if (this._allowHalfOpen === false) this.end(); return; } const copy = Buffer.allocUnsafe(read2); copy.set(this._reading.subarray(0, read2)); this.push(copy); } else { try { if (binding.handshake(this._handle)) this._onconnect(); else break; } catch (err) { err = errors.from(err); queueMicrotask(() => { if (this._pendingOpen) { const cb = this._pendingOpen; this._pendingOpen = null; cb(err); } else { this.destroy(err); } }); return; } } } } _ondrain() { if (this._pendingWrite === null) return; const cb = this._pendingWrite; this._pendingWrite = null; cb(null); } _onend() { this.push(null); } _onclose() { this._socket.off("close", this._onclose).off("error", this._onerror); if (this._pendingDestroy) { const cb = this._pendingDestroy; this._pendingDestroy = null; cb(); } } _onerror(err) { if (this._pendingOpen) { const cb = this._pendingOpen; this._pendingOpen = null; cb(err); } else if (this._pendingDestroy) { const cb = this._pendingDestroy; this._pendingDestroy = 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._socket.on("data", this._ondata).on("drain", this._ondrain).on("end", this._onend); } _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); } _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) { this._detach(); binding.destroy(this._handle); this._handle = null; } this._socket.destroy(); } _destroy(err, cb) { if (this._handle) { this._detach(); binding.destroy(this._handle); this._handle = null; } if (err) this._socket.destroy(); if (this._socket.destroyed) cb(err); else this._pendingDestroy = cb; } }; 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-media/node_modules/bare-https/lib/socket.js var require_socket = __commonJS({ "../../node_modules/bare-media/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-media/node_modules/bare-https/lib/agent.js var require_agent2 = __commonJS({ "../../node_modules/bare-media/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-media/node_modules/bare-https/lib/server.js var require_server2 = __commonJS({ "../../node_modules/bare-media/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-media/node_modules/bare-https/lib/client-request.js var require_client_request2 = __commonJS({ "../../node_modules/bare-media/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-media/node_modules/bare-https/index.js var require_bare_https = __commonJS({ "../../node_modules/bare-media/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-performance/binding.js var require_binding18 = __commonJS({ "../../node_modules/bare-performance/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-performance/lib/hr-time.js var require_hr_time = __commonJS({ "../../node_modules/bare-performance/lib/hr-time.js"(exports) { var binding = require_binding18(); var { TIME_ORIGIN } = binding; exports.now = function now() { return binding.now() / 1e6 - TIME_ORIGIN; }; exports.timeOrigin = TIME_ORIGIN; } }); // ../../node_modules/bare-performance/lib/constants.js var require_constants9 = __commonJS({ "../../node_modules/bare-performance/lib/constants.js"(exports, module) { module.exports = { observerType: { UNDEFINED: 1, SINGLE: 2, MULTIPLE: 3 } }; } }); // ../../node_modules/bare-performance/lib/errors.js var require_errors11 = __commonJS({ "../../node_modules/bare-performance/lib/errors.js"(exports) { var InvalidModificationError = class extends Error { get name() { return "InvalidModificationError"; } }; exports.InvalidModificationError = InvalidModificationError; } }); // ../../node_modules/bare-performance/lib/timing.js var require_timing = __commonJS({ "../../node_modules/bare-performance/lib/timing.js"(exports) { var binding = require_binding18(); var { now, timeOrigin } = require_hr_time(); var { observerType } = require_constants9(); var { InvalidModificationError } = require_errors11(); function noop() { } var globalObservers = /* @__PURE__ */ new Set(); var globalPendingObservers = /* @__PURE__ */ new Set(); var observerTaskQueued = false; var globalBuffer = []; var globalResourceTimingSecondaryBuffer = []; var resourceTimingFullEventPending = false; var resourceTimingSizeLimit = 250; var onResourceTimingBufferFull = noop; exports.PerformanceEntry = class PerformanceEntry { 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.PerformanceResourceTiming = class PerformanceResourceTiming extends exports.PerformanceEntry { constructor(initiatorType, requestedUrl, timingInfo, cacheMode, bodyInfo, responseStatus, deliveryType) { super(requestedUrl, "resource", timingInfo.startTime, timingInfo.endTime - timingInfo.startTime); this._initiatorType = initiatorType; this._requestedURL = requestedUrl; this._timingInfo = timingInfo; this._resourceInfo = bodyInfo; this._cacheMode = cacheMode; this._responseStatus = responseStatus; this._deliveryType = deliveryType; } get initiatorType() { return this._initiatorType; } get deliveryType() { return this._deliveryType; } get transferSize() { if (this._cacheMode === "local") return 0; if (this._cacheMode === "validated") return 300; return this.encodedBodySize * 300; } get responseStatus() { return this._responseStatus; } get encodedBodySize() { return this._resourceInfo.encodedSize; } }; var PerformanceGCEntry = class _PerformanceGCEntry extends exports.PerformanceEntry { static _handle = null; static _refs = 0; static _ref() { if (this._refs++ === 0) { this._handle = binding.enableGarbageCollectionTracking(this, this._onentry); } } static _unref() { if (--this._refs === 0) { binding.disableGarbageCollectionTracking(this._handle); this._handle = null; } } static _onentry(startTime, duration, kind) { startTime -= timeOrigin; const entry = new _PerformanceGCEntry(startTime, duration, kind); processEntry(entry); } constructor(startTime, duration, kind) { super("gc", "gc", startTime, duration); this._detail = { kind }; } get detail() { return this._detail; } }; exports.PerformanceMark = class PerformanceMark extends exports.PerformanceEntry { constructor(name, opts = {}) { const { startTime = now(), detail = null } = opts; super(name, "mark", startTime, 0); this._detail = detail; } get detail() { return this._detail; } }; exports.PerformanceMeasure = class PerformanceMeasure extends exports.PerformanceEntry { constructor(name, startTime, duration, opts = {}) { const { detail = null } = opts; super(name, "measure", startTime, duration); this._detail = detail; } get detail() { return this._detail; } }; exports.PerformanceObserverEntryList = class PerformanceObserverEntryList { 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.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", "gc", "resource"]; } 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); if (this._entryTypes.has("gc")) PerformanceGCEntry._ref(); } else { this.disconnect(); } } takeRecords() { const buf = this._buffer; this._buffer = []; return buf; } disconnect() { globalObservers.delete(this); if (this._entryTypes.has("gc")) PerformanceGCEntry._unref(); this._entryTypes.clear(); this._type = observerType.UNDEFINED; } }; exports.mark = function mark(name, opts) { const mark2 = new exports.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.start && opts.end && opts.duration) { throw new TypeError("One of opts.start, 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(opts.duration); } else { endTime = now(); } let startTime; if (start) { startTime = toTimestamp(start); } else if (end && opts.duration) { startTime = toTimestamp(end) - toTimestamp(opts.duration); } else { startTime = 0; } const duration = endTime - startTime; const measure2 = new exports.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.markResourceTiming = function markResourceTiming(timingInfo, requestedUrl, initiatorType, global2, cacheMode, bodyInfo, responseStatus, deliveryType = "") { const resource = new exports.PerformanceResourceTiming( initiatorType, requestedUrl, timingInfo, cacheMode, bodyInfo, responseStatus, deliveryType ); processEntry(resource); addResourceTimingEntry(resource); return resource; }; exports.clearResourceTimings = function clearResourceTimings(name) { if (name) { globalBuffer = globalBuffer.filter( (entry) => entry.name !== name && entry.entryType !== "resource" ); } else { globalBuffer = globalBuffer.filter((entry) => entry.entryType !== "resource"); } }; exports.getEntries = function getEntries() { return new exports.PerformanceObserverEntryList(globalBuffer).getEntries(); }; exports.getEntriesByName = function getEntriesByName(name) { return new exports.PerformanceObserverEntryList(globalBuffer).getEntriesByName(name); }; exports.getEntriesByType = function getEntriesByType(type) { return new exports.PerformanceObserverEntryList(globalBuffer).getEntriesByType(type); }; exports.setResourceTimingBufferSize = function setResourceTimingBufferSize(maxSize) { resourceTimingSizeLimit = maxSize; }; function processEntry(entry) { for (const observer of globalObservers) { if (observer._entryTypes.has(entry.entryType)) { observer._buffer.push(entry); globalPendingObservers.add(observer); processPendingObservers(); } } } function canAddResourceTimingEntry() { const bufferSize = globalBuffer.filter((entry) => entry.entryType === "resource").length; return bufferSize < resourceTimingSizeLimit; } function copySecondaryBuffer() { while (globalResourceTimingSecondaryBuffer.length > 0 && canAddResourceTimingEntry()) { const resource = globalResourceTimingSecondaryBuffer.shift(); globalBuffer.push(resource); } } function fireBufferFullEvent() { while (globalResourceTimingSecondaryBuffer.length > 0) { const numberOfExcessEntriesBefore = globalResourceTimingSecondaryBuffer.length; if (!canAddResourceTimingEntry()) { onResourceTimingBufferFull("resourcetimingbufferfull"); } copySecondaryBuffer(); const numberOfExcessEntriesAfter = globalResourceTimingSecondaryBuffer.length; if (numberOfExcessEntriesBefore <= numberOfExcessEntriesAfter) { globalResourceTimingSecondaryBuffer = []; } } resourceTimingFullEventPending = false; } function addResourceTimingEntry(entry) { if (canAddResourceTimingEntry() && resourceTimingFullEventPending === false) { globalBuffer.push(entry); return; } else if (resourceTimingFullEventPending === false) { resourceTimingFullEventPending = true; setImmediate(() => fireBufferFullEvent()); } globalResourceTimingSecondaryBuffer.push(entry); } function processPendingObservers() { if (observerTaskQueued) return; observerTaskQueued = true; setImmediate(() => { observerTaskQueued = 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; } } exports.registerEventHandler = function registerEventHandler(handler) { onResourceTimingBufferFull = handler; }; } }); // ../../node_modules/bare-performance/lib/histogram.js var require_histogram = __commonJS({ "../../node_modules/bare-performance/lib/histogram.js"(exports) { var binding = require_binding18(); 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); } }; exports.RecordableHistogram = class RecordableHistogram 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.IntervalHistogram = class IntervalHistogram 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._timerId.unref(); 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(); } }; } }); // ../../node_modules/bare-events/web.js var require_web2 = __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 REMOVED = 8; 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) { for (const existing of listeners) { if (callback === existing.callback && capture === existing.capture) { return; } } listener.link(listeners); } else { this._listeners.set(type, listener); } if (signal !== null) { let onabort2 = function() { self._unlink(type, listener); }; var onabort = onabort2; const self = this; 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) { this._unlink(type, existing); 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; const snapshot = Array.from(listeners); for (const listener of snapshot) { if (listener.removed) continue; if (listener.once) this._unlink(event.type, listener); 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 } }; } _unlink(type, listener) { if (listener.removed) return; const head = this._listeners.get(type); const next = listener.unlink(); if (head === listener) { if (next === listener) this._listeners.delete(type); else this._listeners.set(type, next); } } }; 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._state & REMOVED) !== 0; } 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; this._state |= REMOVED; 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-performance/index.js var require_bare_performance = __commonJS({ "../../node_modules/bare-performance/index.js"(exports, module) { var { now, timeOrigin } = require_hr_time(); var { PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceObserver, PerformanceObserverEntryList, PerformanceResourceTiming, clearMarks, clearMeasures, clearResourceTimings, getEntries, getEntriesByName, getEntriesByType, mark, markResourceTiming, measure, setResourceTimingBufferSize, registerEventHandler } = require_timing(); var { RecordableHistogram, IntervalHistogram } = require_histogram(); var { Event, EventTarget } = require_web2(); var binding = require_binding18(); var PerformanceNodeTiming = class { get idleTime() { return module.exports.idleTime(); } get uvMetricsInfo() { return module.exports.metricsInfo(); } }; var nodeTiming = new PerformanceNodeTiming(); var Performance = class extends EventTarget { constructor() { super(); registerEventHandler((eventName) => { this.dispatchEvent(new Event(eventName)); }); } // For Node.js compatibility get performance() { return this; } // For Node.js compatibility get nodeTiming() { return nodeTiming; } get PerformanceEntry() { return PerformanceEntry; } get PerformanceMark() { return PerformanceMark; } get PerformanceMeasure() { return PerformanceMeasure; } // For Node.js compatibility get PerformanceNodeTiming() { return PerformanceNodeTiming; } get PerformanceResourceTiming() { return PerformanceResourceTiming; } get PerformanceObserver() { return PerformanceObserver; } get PerformanceObserverEntryList() { return PerformanceObserverEntryList; } get timeOrigin() { return timeOrigin; } // For Node.js compatibility get constants() { return { NODE_PERFORMANCE_GC_MAJOR: binding.constants.MARK_COMPACT, NODE_PERFORMANCE_GC_MINOR: binding.constants.GENERATIONAL, NODE_PERFORMANCE_GC_INCREMENTAL: -1, NODE_PERFORMANCE_GC_WEAKCB: -1 }; } now() { return now(); } 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 = this.idleTime(); if (idle === 0) return { idle: 0, active: 0, utilization: 0 }; let active = 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) }; } idleTime() { return binding.idleTime(); } metricsInfo() { return binding.metricsInfo(); } getEntries() { return getEntries(); } getEntriesByName(name) { return getEntriesByName(name); } getEntriesByType(type) { return getEntriesByType(type); } mark(name, opts) { return mark(name, opts); } measure(name, start, end) { return measure(name, start, end); } markResourceTiming(timingInfo, requestedUrl, initiatorType, global2, cacheMode, bodyInfo, responseStatus, deliveryType) { return markResourceTiming( timingInfo, requestedUrl, initiatorType, global2, cacheMode, bodyInfo, responseStatus, deliveryType ); } clearMarks(name) { clearMarks(name); } clearMeasures(name) { clearMeasures(name); } clearResourceTimings(name) { clearResourceTimings(name); } setResourceTimingBufferSize(maxSize) { setResourceTimingBufferSize(maxSize); } createHistogram(opts) { return new RecordableHistogram(opts); } monitorEventLoopDelay(opts) { return new IntervalHistogram(opts); } }; module.exports = new Performance(); } }); // ../../node_modules/bare-buffer/binding.js var require_binding19 = __commonJS({ "../../node_modules/bare-buffer/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-buffer/lib/constants.js var require_constants10 = __commonJS({ "../../node_modules/bare-buffer/lib/constants.js"(exports, module) { var binding = require_binding19(); 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_binding19(); exports.byteLength = function byteLength(string) { return string.length; }; exports.toString = function toString(buffer, start = 0, end = buffer.byteLength) { const offset = buffer.byteOffset + start; const len = end - start; if (binding.validateAscii(buffer.buffer, offset, len)) { return binding.toStringLatin1(buffer.buffer, offset, len); } let result = ""; for (let i = start; i < end; i++) { result += String.fromCharCode(buffer[i] & 127); } return result; }; exports.write = function write(buffer, string, start = 0, end = buffer.byteLength) { return binding.writeLatin1(buffer.buffer, buffer.byteOffset + start, end - start, string); }; exports.validate = function validate(buffer) { return binding.validateAscii(buffer.buffer, buffer.byteOffset, buffer.byteLength); }; } }); // ../../node_modules/bare-buffer/lib/base64.js var require_base64 = __commonJS({ "../../node_modules/bare-buffer/lib/base64.js"(exports) { var binding = require_binding19(); 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, start = 0, end = buffer.byteLength) { return binding.toStringBase64(buffer.buffer, buffer.byteOffset + start, end - start); }; exports.write = function write(buffer, string, start = 0, end = buffer.byteLength) { return binding.writeBase64(buffer.buffer, buffer.byteOffset + start, end - start, string); }; } }); // ../../node_modules/bare-buffer/lib/base64url.js var require_base64url = __commonJS({ "../../node_modules/bare-buffer/lib/base64url.js"(exports) { var binding = require_binding19(); 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, start = 0, end = buffer.byteLength) { return binding.toStringBase64URL(buffer.buffer, buffer.byteOffset + start, end - start); }; exports.write = function write(buffer, string, start = 0, end = buffer.byteLength) { return binding.writeBase64(buffer.buffer, buffer.byteOffset + start, end - start, string); }; } }); // ../../node_modules/bare-buffer/lib/hex.js var require_hex = __commonJS({ "../../node_modules/bare-buffer/lib/hex.js"(exports) { var binding = require_binding19(); exports.byteLength = function byteLength(string) { return string.length >>> 1; }; exports.toString = function toString(buffer, start = 0, end = buffer.byteLength) { return binding.toStringHex(buffer.buffer, buffer.byteOffset + start, end - start); }; exports.write = function write(buffer, string, start = 0, end = buffer.byteLength) { return binding.writeHex(buffer.buffer, buffer.byteOffset + start, end - start, string); }; } }); // ../../node_modules/bare-buffer/lib/utf8.js var require_utf8 = __commonJS({ "../../node_modules/bare-buffer/lib/utf8.js"(exports) { var binding = require_binding19(); exports.byteLength = function byteLength(string) { return binding.byteLengthUTF8(string); }; exports.toString = function toString(buffer, start = 0, end = buffer.byteLength) { return binding.toStringUTF8(buffer.buffer, buffer.byteOffset + start, end - start); }; exports.write = function write(buffer, string, start = 0, end = buffer.byteLength) { return binding.writeUTF8(buffer.buffer, buffer.byteOffset + start, end - start, string); }; exports.validate = function validate(buffer) { return binding.validateUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength); }; } }); // ../../node_modules/bare-buffer/lib/utf16le.js var require_utf16le = __commonJS({ "../../node_modules/bare-buffer/lib/utf16le.js"(exports) { var binding = require_binding19(); exports.byteLength = function byteLength(string) { return string.length * 2; }; exports.toString = function toString(buffer, start = 0, end = buffer.byteLength) { return binding.toStringUTF16LE(buffer.buffer, buffer.byteOffset + start, end - start); }; exports.write = function write(buffer, string, start = 0, end = buffer.byteLength) { return binding.writeUTF16LE(buffer.buffer, buffer.byteOffset + start, end - start, string); }; } }); // ../../node_modules/bare-buffer/lib/latin1.js var require_latin1 = __commonJS({ "../../node_modules/bare-buffer/lib/latin1.js"(exports) { var binding = require_binding19(); exports.byteLength = function byteLength(string) { return string.length; }; exports.toString = function toString(buffer, start = 0, end = buffer.byteLength) { return binding.toStringLatin1(buffer.buffer, buffer.byteOffset + start, end - start); }; exports.write = function write(buffer, string, start = 0, end = buffer.byteLength) { return binding.writeLatin1(buffer.buffer, buffer.byteOffset + start, end - start, string); }; } }); // ../../node_modules/bare-buffer/index.js var require_bare_buffer = __commonJS({ "../../node_modules/bare-buffer/index.js"(exports, module) { var constants = require_constants10(); 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_binding19(); var kind = Symbol.for("bare.buffer.kind"); var SWAP_MIN_LENGTH = 128; var poolSize = 65536; var pool = null; var poolLength = 0; var poolOffset = 0; var Buffer2 = class _Buffer 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 (Number.isNaN(length) || length < 0 || length > constants.MAX_LENGTH) { throw new RangeError(`Buffer length must be between 0 and ${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 === "object" && length !== null) { opts = length; length = arrayBuffer.byteLength - offset; } } super(arrayBuffer, offset, length); } get [kind]() { return _Buffer[kind]; } copy(target, targetStart = 0, sourceStart = 0, sourceEnd = this.byteLength) { const 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) { target.set(source, targetStart); } else { target.set( new Uint8Array(source.buffer, source.byteOffset + sourceStart, sourceLength), 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) { const source = this; if (source === target) return 0; if (arguments.length === 1) { targetStart = 0; targetEnd = target.byteLength; sourceStart = 0; sourceEnd = source.byteLength; } else { 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; } return binding.compare( source.buffer, source.byteOffset + sourceStart, sourceEnd - sourceStart, target.buffer, target.byteOffset + targetStart, targetEnd - targetStart ); } 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; if (length === 0) return super.fill(0, offset, end); if (length === 1) return super.fill(value[0], offset, end); return fillPattern(this, value, length, offset, end); } 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"); } if (length < SWAP_MIN_LENGTH) { for (let i = 0; i < length; i += 2) swap(this, i, i + 1); } else { binding.swap16(this.buffer, this.byteOffset, length); } return this; } swap32() { const length = this.byteLength; if (length % 4 !== 0) { throw new RangeError("Buffer size must be a multiple of 32-bits"); } if (length < SWAP_MIN_LENGTH) { for (let i = 0; i < length; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } } else { binding.swap32(this.buffer, this.byteOffset, length); } return this; } swap64() { const length = this.byteLength; if (length % 8 !== 0) { throw new RangeError("Buffer size must be a multiple of 64-bits"); } if (length < SWAP_MIN_LENGTH) { 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); } } else { binding.swap64(this.buffer, this.byteOffset, length); } 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; return codecFor(encoding).toString(this, start, end); } toJSON() { const length = this.byteLength; const data = new Array(length); for (let i = 0; i < length; i++) data[i] = this[i]; return data; } 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; return codecFor(encoding).write(this, string, start, end); } readBigInt64BE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getBigInt64(offset, false); } readBigInt64LE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getBigInt64(offset, true); } readBigUint64BE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getBigUint64(offset, false); } readBigUint64LE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getBigUint64(offset, true); } readDoubleBE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getFloat64(offset, false); } readDoubleLE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getFloat64(offset, true); } readFloatBE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getFloat32(offset, false); } readFloatLE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); return viewOf(this).getFloat32(offset, true); } readInt8(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const value = this[offset]; if (value === void 0) boundsError(); return value << 24 >> 24; } readInt16BE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 1]; if (first === void 0 || last === void 0) boundsError(); return (first << 8 | last) << 16 >> 16; } readInt16LE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 1]; if (first === void 0 || last === void 0) boundsError(); return (last << 8 | first) << 16 >> 16; } readInt32BE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 3]; if (first === void 0 || last === void 0) boundsError(); return first << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | last; } readInt32LE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 3]; if (first === void 0 || last === void 0) boundsError(); return first | this[offset + 1] << 8 | this[offset + 2] << 16 | last << 24; } readIntBE(offset, byteLength) { if (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return readInt48BE(this, offset); if (byteLength === 5) return readInt40BE(this, offset); if (byteLength === 3) return readInt24BE(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 (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return readInt48LE(this, offset); if (byteLength === 5) return readInt40LE(this, offset); if (byteLength === 3) return readInt24LE(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) { if (!Number.isInteger(offset)) offsetError(offset); const value = this[offset]; if (value === void 0) boundsError(); return value; } readUint16BE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 1]; if (first === void 0 || last === void 0) boundsError(); return first << 8 | last; } readUint16LE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 1]; if (first === void 0 || last === void 0) boundsError(); return last << 8 | first; } readUint32BE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 3]; if (first === void 0 || last === void 0) boundsError(); return first * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | last); } readUint32LE(offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); const first = this[offset]; const last = this[offset + 3]; if (first === void 0 || last === void 0) boundsError(); return last * 16777216 + (this[offset + 2] << 16 | this[offset + 1] << 8 | first); } readUintBE(offset, byteLength) { if (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return readUint48BE(this, offset); if (byteLength === 5) return readUint40BE(this, offset); if (byteLength === 3) return readUint24BE(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 (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return readUint48LE(this, offset); if (byteLength === 5) return readUint40LE(this, offset); if (byteLength === 3) return readUint24LE(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`); } writeBigInt64BE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setBigInt64(offset, value, false); return offset + 8; } writeBigInt64LE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setBigInt64(offset, value, true); return offset + 8; } writeBigUint64BE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setBigUint64(offset, value, false); return offset + 8; } writeBigUint64LE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setBigUint64(offset, value, true); return offset + 8; } writeDoubleBE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setFloat64(offset, value, false); return offset + 8; } writeDoubleLE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setFloat64(offset, value, true); return offset + 8; } writeFloatBE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setFloat32(offset, value, false); return offset + 4; } writeFloatLE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); viewOf(this).setFloat32(offset, value, true); return offset + 4; } writeInt8(value, offset = 0) { return this.writeUint8(value, offset); } writeInt16BE(value, offset = 0) { return this.writeUint16BE(value, offset); } writeInt16LE(value, offset = 0) { return this.writeUint16LE(value, offset); } writeInt32BE(value, offset = 0) { return this.writeUint32BE(value, offset); } writeInt32LE(value, offset = 0) { return this.writeUint32LE(value, offset); } writeIntBE(value, offset, byteLength) { if (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return writeInt48BE(this, value, offset); if (byteLength === 5) return writeInt40BE(this, value, offset); if (byteLength === 3) return writeInt24BE(this, value, 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 (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return writeInt48LE(this, value, offset); if (byteLength === 5) return writeInt40LE(this, value, offset); if (byteLength === 3) return writeInt24LE(this, value, 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) { if (!Number.isInteger(offset)) offsetError(offset); if (this[offset] === void 0) boundsError(); this[offset] = value; return offset + 1; } writeUint16BE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); if (this[offset] === void 0 || this[offset + 1] === void 0) boundsError(); this[offset] = value >>> 8; this[offset + 1] = value; return offset + 2; } writeUint16LE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); if (this[offset] === void 0 || this[offset + 1] === void 0) boundsError(); this[offset] = value; this[offset + 1] = value >>> 8; return offset + 2; } writeUint32LE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); if (this[offset] === void 0 || this[offset + 3] === void 0) boundsError(); this[offset] = value; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; return offset + 4; } writeUint32BE(value, offset = 0) { if (!Number.isInteger(offset)) offsetError(offset); if (this[offset] === void 0 || this[offset + 3] === void 0) boundsError(); this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value; return offset + 4; } writeUintBE(value, offset, byteLength) { if (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return writeUint48BE(this, value, offset); if (byteLength === 5) return writeUint40BE(this, value, offset); if (byteLength === 3) return writeUint24BE(this, value, 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 (!Number.isInteger(offset)) offsetError(offset); if (byteLength === 6) return writeUint48LE(this, value, offset); if (byteLength === 5) return writeUint40LE(this, value, offset); if (byteLength === 3) return writeUint24LE(this, value, 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`); } }; for (const [alias, name] of [ ["readBigUInt64BE", "readBigUint64BE"], ["readBigUInt64LE", "readBigUint64LE"], ["readUInt8", "readUint8"], ["readUInt16BE", "readUint16BE"], ["readUInt16LE", "readUint16LE"], ["readUInt32BE", "readUint32BE"], ["readUInt32LE", "readUint32LE"], ["readUIntBE", "readUintBE"], ["readUIntLE", "readUintLE"], ["writeBigUInt64BE", "writeBigUint64BE"], ["writeBigUInt64LE", "writeBigUint64LE"], ["writeUInt8", "writeUint8"], ["writeUInt16BE", "writeUint16BE"], ["writeUInt16LE", "writeUint16LE"], ["writeUInt32BE", "writeUint32BE"], ["writeUInt32LE", "writeUint32LE"], ["writeUIntBE", "writeUintBE"], ["writeUIntLE", "writeUintLE"] ]) { Object.defineProperty(Buffer2.prototype, alias, { value: Buffer2.prototype[name], writable: true, configurable: true }); } module.exports = exports = Buffer2; exports.Buffer = Buffer2; exports.constants = constants; var codecs2 = /* @__PURE__ */ Object.create(null); codecs2.ascii = ascii; codecs2.base64 = base64; codecs2.base64url = base64url; codecs2.hex = hex; codecs2.utf8 = codecs2["utf-8"] = utf8; codecs2.utf16le = codecs2.ucs2 = codecs2["utf-16le"] = codecs2["ucs-2"] = utf16le; codecs2.latin1 = codecs2.binary = latin1; function codecFor(encoding) { if (encoding === void 0) return utf8; let codec = codecs2[encoding]; if (codec !== void 0) return codec; codec = codecs2[encoding.toLowerCase()]; if (codec !== void 0) return codec; 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) { if (fill !== void 0 && fill !== 0) { const buffer = new Buffer2(size, { uninitialized: true }); return buffer.fill(fill, 0, buffer.byteLength, encoding); } return new Buffer2(size); }; exports.allocUnsafe = function allocUnsafe(size) { return allocate(size); }; exports.allocUnsafeSlow = function allocUnsafeSlow(size) { return new Buffer2(size, { uninitialized: true }); }; 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) { const n = buffers.length; if (length === void 0) { length = 0; for (let i = 0; i < n; i++) length += buffers[i].byteLength; } const result = allocate(length); let offset = 0; for (let i = 0; i < n; i++) { const buffer = buffers[i]; if (offset + buffer.byteLength > length) { result.set(new Uint8Array(buffer.buffer, buffer.byteOffset, length - offset), offset); return result; } result.set(buffer, offset); offset += buffer.byteLength; } if (offset < length) result.fill(0, offset, length); 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 length = codec.byteLength(string); const buffer = allocate(length); const written = codec.write(buffer, string, 0, length); if (written < length) return buffer.subarray(0, written); return buffer; } function fromArray(array) { const buffer = allocate(array.length); buffer.set(array); return buffer; } function fromBuffer(buffer) { const copy = allocate(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); const needleLength = value.byteLength; if (needleLength === 0) return -1; const length = buffer.byteLength; const last = length - needleLength; if (first) { if (offset > last) return -1; } else { if (offset > last) offset = last; if (offset < 0) return -1; } let j = 0; while (j < needleLength && buffer[offset + j] === value[j]) j++; if (j === needleLength) return offset; if (first) { if (offset === last) return -1; return binding.indexOf( buffer.buffer, buffer.byteOffset, length, value.buffer, value.byteOffset, needleLength, offset + 1 ); } if (offset === 0) return -1; return binding.lastIndexOf( buffer.buffer, buffer.byteOffset, length, value.buffer, value.byteOffset, needleLength, offset - 1 ); } function fillPattern(buffer, value, length, offset, end) { const n = end - offset; if (n < 64) { for (let i = 0; i < n; i++) buffer[offset + i] = value[i % length]; return buffer; } let filled = length < n ? length : n; for (let i = 0; i < filled; i++) buffer[offset + i] = value[i]; while (filled < n) { const copy = filled < n - filled ? filled : n - filled; buffer.copyWithin(offset + filled, offset, offset + copy); filled += copy; } return buffer; } function allocate(size) { if (Number.isNaN(size) || size <= 0 || size >= poolSize >>> 1) { return new Buffer2(size, { uninitialized: true }); } if (pool === null || poolLength !== poolSize || poolLength - poolOffset < size) { pool = binding.allocUnsafe(poolSize); poolLength = poolSize; poolOffset = 0; } const buffer = new Buffer2(pool, poolOffset, size); poolOffset = poolOffset + size + 7 & ~7; return buffer; } 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 transcode2(buffer, from, to) { return Buffer2.from(buffer.toString(from), to); }; function boundsError() { throw new RangeError("Offset is outside the bounds of the buffer"); } function offsetError(offset) { if (typeof offset !== "number") { throw new TypeError(`Offset must be a number, received type ${typeof offset}`); } throw new RangeError("Offset is outside the bounds of the buffer"); } function readInt48BE(buffer, offset) { const value = readUint48BE(buffer, offset); return value >= 140737488355328 ? value - 281474976710656 : value; } function readInt48LE(buffer, offset) { const value = readUint48LE(buffer, offset); return value >= 140737488355328 ? value - 281474976710656 : value; } function readInt40BE(buffer, offset) { const value = readUint40BE(buffer, offset); return value >= 549755813888 ? value - 1099511627776 : value; } function readInt40LE(buffer, offset) { const value = readUint40LE(buffer, offset); return value >= 549755813888 ? value - 1099511627776 : value; } function readInt24BE(buffer, offset) { const value = readUint24BE(buffer, offset); return value & 8388608 ? value - 16777216 : value; } function readInt24LE(buffer, offset) { const value = readUint24LE(buffer, offset); return value & 8388608 ? value - 16777216 : value; } function readUint48BE(buffer, offset) { const first = buffer[offset]; const last = buffer[offset + 5]; if (first === void 0 || last === void 0) boundsError(); return (first * 256 + buffer[offset + 1]) * 4294967296 + (buffer[offset + 2] << 24 >>> 0) + (buffer[offset + 3] << 16) + (buffer[offset + 4] << 8) + last; } function readUint48LE(buffer, offset) { const first = buffer[offset]; const last = buffer[offset + 5]; if (first === void 0 || last === void 0) boundsError(); return (buffer[offset + 4] + last * 256) * 4294967296 + (buffer[offset + 3] << 24 >>> 0) + (buffer[offset + 2] << 16) + (buffer[offset + 1] << 8) + first; } function readUint40BE(buffer, offset) { const first = buffer[offset]; const last = buffer[offset + 4]; if (first === void 0 || last === void 0) boundsError(); return first * 4294967296 + (buffer[offset + 1] << 24 >>> 0) + (buffer[offset + 2] << 16) + (buffer[offset + 3] << 8) + last; } function readUint40LE(buffer, offset) { const first = buffer[offset]; const last = buffer[offset + 4]; if (first === void 0 || last === void 0) boundsError(); return last * 4294967296 + (buffer[offset + 3] << 24 >>> 0) + (buffer[offset + 2] << 16) + (buffer[offset + 1] << 8) + first; } function readUint24BE(buffer, offset) { const first = buffer[offset]; const last = buffer[offset + 2]; if (first === void 0 || last === void 0) boundsError(); return first << 16 | buffer[offset + 1] << 8 | last; } function readUint24LE(buffer, offset) { const first = buffer[offset]; const last = buffer[offset + 2]; if (first === void 0 || last === void 0) boundsError(); return last << 16 | buffer[offset + 1] << 8 | first; } function writeInt48BE(buffer, value, offset) { if (value < 0) value += 281474976710656; return writeUint48BE(buffer, value, offset); } function writeInt48LE(buffer, value, offset) { if (value < 0) value += 281474976710656; return writeUint48LE(buffer, value, offset); } function writeInt40BE(buffer, value, offset) { if (value < 0) value += 1099511627776; return writeUint40BE(buffer, value, offset); } function writeInt40LE(buffer, value, offset) { if (value < 0) value += 1099511627776; return writeUint40LE(buffer, value, offset); } function writeInt24BE(buffer, value, offset) { if (value < 0) value += 16777216; return writeUint24BE(buffer, value, offset); } function writeInt24LE(buffer, value, offset) { if (value < 0) value += 16777216; return writeUint24LE(buffer, value, offset); } function writeUint48BE(buffer, value, offset) { if (buffer[offset] === void 0 || buffer[offset + 5] === void 0) boundsError(); const hi = Math.floor(value / 4294967296); const lo = value >>> 0; buffer[offset] = hi >>> 8; buffer[offset + 1] = hi; buffer[offset + 2] = lo >>> 24; buffer[offset + 3] = lo >>> 16; buffer[offset + 4] = lo >>> 8; buffer[offset + 5] = lo; return offset + 6; } function writeUint48LE(buffer, value, offset) { if (buffer[offset] === void 0 || buffer[offset + 5] === void 0) boundsError(); const hi = Math.floor(value / 4294967296); const lo = value >>> 0; buffer[offset] = lo; buffer[offset + 1] = lo >>> 8; buffer[offset + 2] = lo >>> 16; buffer[offset + 3] = lo >>> 24; buffer[offset + 4] = hi; buffer[offset + 5] = hi >>> 8; return offset + 6; } function writeUint40BE(buffer, value, offset) { if (buffer[offset] === void 0 || buffer[offset + 4] === void 0) boundsError(); const lo = value >>> 0; buffer[offset] = Math.floor(value / 4294967296); buffer[offset + 1] = lo >>> 24; buffer[offset + 2] = lo >>> 16; buffer[offset + 3] = lo >>> 8; buffer[offset + 4] = lo; return offset + 5; } function writeUint40LE(buffer, value, offset) { if (buffer[offset] === void 0 || buffer[offset + 4] === void 0) boundsError(); const lo = value >>> 0; buffer[offset] = lo; buffer[offset + 1] = lo >>> 8; buffer[offset + 2] = lo >>> 16; buffer[offset + 3] = lo >>> 24; buffer[offset + 4] = Math.floor(value / 4294967296); return offset + 5; } function writeUint24BE(buffer, value, offset) { if (buffer[offset] === void 0 || buffer[offset + 2] === void 0) boundsError(); buffer[offset] = value >>> 16; buffer[offset + 1] = value >>> 8; buffer[offset + 2] = value; return offset + 3; } function writeUint24LE(buffer, value, offset) { if (buffer[offset] === void 0 || buffer[offset + 2] === void 0) boundsError(); buffer[offset] = value; buffer[offset + 1] = value >>> 8; buffer[offset + 2] = value >>> 16; return offset + 3; } } }); // ../../node_modules/bare-form-data/lib/errors.js var require_errors12 = __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_web(); var { isBuffer } = require_bare_buffer(); var errors = require_errors12(); 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); new Uint8Array(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-mime/index.js var require_bare_mime = __commonJS({ "../../node_modules/bare-mime/index.js"(exports, module) { var MIME = class { constructor(type, subtype, parameters = /* @__PURE__ */ new Map()) { this._type = type; this._subtype = subtype; this._parameters = parameters; } // https://mimesniff.spec.whatwg.org/#type get type() { return this._type; } // https://mimesniff.spec.whatwg.org/#subtype get subtype() { return this._subtype; } // https://mimesniff.spec.whatwg.org/#parameters get parameters() { return this._parameters; } }; module.exports = exports = MIME; exports.parse = function parse(input) { input = input.replace(httpWhitespaceLeadingAndTrailing, ""); let position = 0; let type = ""; while (position < input.length && input[position] !== "/") { type += input[position++]; } if (type === "" || !isHTTPTokenCodePoints(type)) return null; if (position >= input.length) return null; position++; let subtype = ""; while (position < input.length && input[position] !== ";") { subtype += input[position++]; } subtype = subtype.replace(httpWhitespaceTrailing, ""); if (subtype === "" || !isHTTPTokenCodePoints(subtype)) return null; const mimeType = new MIME(type.toLowerCase(), subtype.toLowerCase()); while (position < input.length) { position++; while (position < input.length && httpWhitespace.test(input[position])) { position++; } let parameterName = ""; while (position < input.length && input[position] !== ";" && input[position] !== "=") { parameterName += input[position++]; } parameterName = parameterName.toLowerCase(); if (position < input.length && input[position] === ";") continue; if (position >= input.length) break; position++; let parameterValue; if (position < input.length && input[position] === '"') { parameterValue = collectHTTPQuotedString(input, position); position = parameterValue.position; parameterValue = parameterValue.value; while (position < input.length && input[position] !== ";") { position++; } } else { parameterValue = ""; while (position < input.length && input[position] !== ";") { parameterValue += input[position++]; } parameterValue = parameterValue.replace(httpWhitespaceTrailing, ""); if (parameterValue === "") continue; } if (parameterName !== "" && isHTTPTokenCodePoints(parameterName) && isHTTPQuotedStringTokenCodePoints(parameterValue) && !mimeType._parameters.has(parameterName)) { mimeType._parameters.set(parameterName, parameterValue); } } return mimeType; }; var httpWhitespace = /[\t\n\r ]/; var httpWhitespaceLeadingAndTrailing = /^[\t\n\r ]+|[\t\n\r ]+$/g; var httpWhitespaceTrailing = /[\t\n\r ]+$/; var httpTokenCodePoints = /^[!#$%&'*+\-.^_`|~A-Za-z0-9]+$/; var httpQuotedStringTokenCodePoints = /^[\t\x20-\x7e\x80-\xff]*$/; function isHTTPTokenCodePoints(s) { return httpTokenCodePoints.test(s); } function isHTTPQuotedStringTokenCodePoints(s) { return httpQuotedStringTokenCodePoints.test(s); } function collectHTTPQuotedString(input, position) { let value = ""; position++; while (true) { while (position < input.length && input[position] !== '"' && input[position] !== "\\") { value += input[position++]; } if (position >= input.length) break; const quoteOrBackslash = input[position++]; if (quoteOrBackslash === "\\") { if (position >= input.length) { value += "\\"; break; } value += input[position++]; } else { break; } } return { value, position }; } } }); // ../../node_modules/bare-media/node_modules/bare-fetch/lib/errors.js var require_errors13 = __commonJS({ "../../node_modules/bare-media/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 INVALID_REDIRECT_STATUS(msg) { return new FetchError(msg, FetchError.INVALID_REDIRECT_STATUS); } static INVALID_JSON(msg, cause) { return new FetchError(msg, FetchError.INVALID_JSON, { 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); } static INVALID_FORM_DATA(msg) { return new FetchError(msg, FetchError.INVALID_FORM_DATA); } static INVALID_METHOD(msg) { return new FetchError(msg, FetchError.INVALID_METHOD); } static FORBIDDEN_METHOD(msg) { return new FetchError(msg, FetchError.FORBIDDEN_METHOD); } static INVALID_HEADER_NAME(msg) { return new FetchError(msg, FetchError.INVALID_HEADER_NAME); } static INVALID_HEADER_VALUE(msg) { return new FetchError(msg, FetchError.INVALID_HEADER_VALUE); } }; } }); // ../../node_modules/bare-media/node_modules/bare-fetch/lib/headers.js var require_headers = __commonJS({ "../../node_modules/bare-media/node_modules/bare-fetch/lib/headers.js"(exports, module) { var MIME = require_bare_mime(); var errors = require_errors13(); var NUL = 0; var LF = 10; var CR = 13; 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 b < TOKEN_BYTES.length && TOKEN_BYTES[b] === 1; } function isFieldByte(b) { return b !== NUL && b !== LF && b !== CR; } function validateName(name) { if (name.length === 0) { throw errors.INVALID_HEADER_NAME(`Header name must not be empty`); } for (let i = 0, n = name.length; i < n; i++) { if (!isTokenByte(name.charCodeAt(i))) { throw errors.INVALID_HEADER_NAME(`Invalid header name '${name}'`); } } } function validateValue(name, value) { for (let i = 0, n = value.length; i < n; i++) { if (!isFieldByte(value.charCodeAt(i))) { throw errors.INVALID_HEADER_VALUE(`Invalid header value for '${name}'`); } } } module.exports = 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) { value = value.trim(); validateName(name); validateValue(name, value); name = name.toLowerCase(); 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); } getSetCookie() { const list = this._headers.get("set-cookie"); if (list === void 0) return []; return [...list]; } // https://fetch.spec.whatwg.org/#dom-headers-set set(name, value) { value = value.trim(); validateName(name); validateValue(name, value); name = name.toLowerCase(); 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)]; } } }; exports.extractMIMEType = function extractMIMEType(headers) { const contentType = headers.get("content-type"); if (contentType === null) return null; const values = getDecodeSplit(contentType); let mimeType = null; for (const value of values) { const parsed = MIME.parse(value); if (parsed !== null) { mimeType = parsed; } } return mimeType; }; function getDecodeSplit(value) { const values = []; let current = ""; let position = 0; while (position < value.length) { if (value[position] === '"') { current += value[position++]; while (position < value.length) { if (value[position] === "\\" && position + 1 < value.length) { current += value[position++]; current += value[position++]; } else if (value[position] === '"') { current += value[position++]; break; } else { current += value[position++]; } } } else if (value[position] === ",") { values.push(current.trim()); current = ""; position++; } else { current += value[position++]; } } values.push(current.trim()); return values; } } }); // ../../node_modules/bare-media/node_modules/bare-fetch/lib/body.js var require_body = __commonJS({ "../../node_modules/bare-media/node_modules/bare-fetch/lib/body.js"(exports, module) { var { ReadableStream, isReadableStream, isReadableStreamDisturbed } = require_web(); var { isURLSearchParams } = require_bare_url(); var { FormData, File, isFormData, isBlob } = require_bare_form_data(); var Headers = require_headers(); var errors = require_errors13(); 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._contentType = 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 await 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()); } // https://fetch.spec.whatwg.org/#dom-body-formdata async formData() { const mimeType = getMIMEType(this); if (mimeType !== null && mimeType.type === "multipart" && mimeType.subtype === "form-data") { const body = await this.text(); const boundary = mimeType.parameters.get("boundary"); if (boundary === void 0) { throw errors.INVALID_FORM_DATA("Missing boundary parameter"); } return parseMultipart(body, boundary); } if (mimeType !== null && mimeType.type === "application" && mimeType.subtype === "x-www-form-urlencoded") { const body = await this.text(); const formData = new FormData(); for (const [name, value] of new URLSearchParams(body)) { formData.append(name, value); } return formData; } throw errors.INVALID_FORM_DATA("Could not parse content as form data"); } }; 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; }; function getMIMEType(body) { const headers = body._headers; if (headers === void 0) return null; return Headers.extractMIMEType(headers); } function parseMultipart(input, boundary) { const formData = new FormData(); const delimiter = `\r --${boundary}`; const close = `\r --${boundary}--`; let start = input.indexOf(`--${boundary}`); if (start === -1) return formData; start += `--${boundary}`.length; while (true) { if (input.startsWith("--", start)) break; if (input.startsWith("\r\n", start)) start += 2; let end = input.indexOf(delimiter, start); if (end === -1) end = input.indexOf(close, start); if (end === -1) break; const part = input.slice(start, end); const headerEnd = part.indexOf("\r\n\r\n"); if (headerEnd === -1) { start = end + delimiter.length; continue; } const headerSection = part.slice(0, headerEnd); const body = part.slice(headerEnd + 4); const contentDisposition = { name: null, filename: null }; let contentType = null; for (const line of headerSection.split("\r\n")) { const colon = line.indexOf(":"); if (colon === -1) continue; const name = line.slice(0, colon).trim().toLowerCase(); const value = line.slice(colon + 1).trim(); if (name === "content-disposition") { contentDisposition.name = getParameter(value, "name"); contentDisposition.filename = getParameter(value, "filename"); } else if (name === "content-type") { contentType = value; } } if (contentDisposition.name === null) { start = end + delimiter.length; continue; } if (contentDisposition.filename !== null) { const file = new File([body], contentDisposition.filename, { type: contentType || "application/octet-stream" }); formData.append(contentDisposition.name, file); } else { formData.append(contentDisposition.name, body); } start = end + delimiter.length; } return formData; } function getParameter(header, name) { const pattern = new RegExp(`${name}="([^"]*)"|${name}=([^;\\s]*)`, "i"); const match = header.match(pattern); if (match === null) return null; return match[1] !== void 0 ? match[1] : match[2]; } } }); // ../../node_modules/bare-media/node_modules/bare-fetch/lib/request.js var require_request = __commonJS({ "../../node_modules/bare-media/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_errors13(); 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 = input.signal || null, agent = input.agent || null } = init; super(body); this._url = url; if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(method)) { throw errors.INVALID_METHOD(`'${method}' is not a valid method`); } if (/^(connect|trace|track)$/i.test(method)) { throw errors.FORBIDDEN_METHOD(`'${method}' is a forbidden method`); } 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; if (this._contentType !== null && !this._headers.has("content-type")) { this._headers.set("content-type", this._contentType); } } // 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-media/node_modules/bare-fetch/lib/response.js var require_response = __commonJS({ "../../node_modules/bare-media/node_modules/bare-fetch/lib/response.js"(exports, module) { var Body = require_body(); var Headers = require_headers(); var errors = require_errors13(); 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._type = "default"; this._status = status; this._statusText = statusText; this._headers = new Headers(headers); if (this._contentType !== null && !this._headers.has("content-type")) { this._headers.set("content-type", this._contentType); } } // https://fetch.spec.whatwg.org/#dom-response-type get type() { return this._type; } // 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"); const cloned = new Response(Body.clone(this), this); cloned._type = this._type; return cloned; } // https://fetch.spec.whatwg.org/#dom-response-error static error() { const response = new Response(null); response._type = "error"; response._status = 0; response._statusText = ""; return response; } // https://fetch.spec.whatwg.org/#dom-response-redirect static redirect(url, status = 302) { let parsed; try { parsed = new URL(url); } catch (err) { throw errors.INVALID_URL("Invalid URL", err); } if (!isRedirectStatus(status)) { throw errors.INVALID_REDIRECT_STATUS(`'${status}' is not a redirect status`); } const response = new Response(null, { status }); response._headers.set("location", parsed.href); return response; } // https://fetch.spec.whatwg.org/#dom-response-json static json(data, init = {}) { let body; try { body = JSON.stringify(data); } catch (err) { throw errors.INVALID_JSON("Data could not be serialized to JSON", err); } if (body === void 0) { throw errors.INVALID_JSON("Data could not be serialized to JSON"); } const response = new Response(body, init); if (!response._headers.has("content-type")) { response._headers.set("content-type", "application/json"); } return response; } }; function isRedirectStatus(status) { return status === 301 || status === 302 || status === 303 || status === 307 || status === 308; } } }); // ../../node_modules/bare-zlib/binding.js var require_binding20 = __commonJS({ "../../node_modules/bare-zlib/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-zlib/lib/constants.js var require_constants11 = __commonJS({ "../../node_modules/bare-zlib/lib/constants.js"(exports, module) { var binding = require_binding20(); module.exports = binding.constants; } }); // ../../node_modules/bare-zlib/lib/errors.js var require_errors14 = __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); } static LIMIT_EXCEEDED(msg) { return new ZlibError(msg, "LIMIT_EXCEEDED", ZlibError.LIMIT_EXCEEDED); } }; } }); // ../../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_binding20(); var constants = require_constants11(); var errors = require_errors14(); exports.constants = constants; exports.errors = errors; var MAX_OUTPUT_LENGTH = Buffer.constants && Buffer.constants.MAX_LENGTH || 4294967296; 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, maxOutputLength = MAX_OUTPUT_LENGTH } = opts; this._mode = mode; this._flushMode = flush; this._finishFlushMode = finishFlush; this._allocations = []; this._maxOutputLength = maxOutputLength; this._outputLength = 0; 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() { this._outputLength = 0; 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 read2 = this._buffer.length - available; if (read2) { this._outputLength += read2; if (this._outputLength > this._maxOutputLength) { throw errors.LIMIT_EXCEEDED( `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes` ); } const copy = Buffer.allocUnsafe(read2); copy.set(this._buffer.subarray(0, read2)); yield copy; } } while (available === 0); } *flush() { let available; do { try { available = binding.transform(this._handle, this._finishFlushMode); } catch (err) { throw errors[err.code](err.message); } const read2 = this._buffer.length - available; if (read2) { this._outputLength += read2; if (this._outputLength > this._maxOutputLength) { throw errors.LIMIT_EXCEEDED( `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes` ); } const copy = Buffer.allocUnsafe(read2); copy.set(this._buffer.subarray(0, read2)); yield copy; } } while (available === 0); try { binding.end(this._handle); } catch (err) { throw errors[err.code](err.message); } this._handle = null; } }; var ZlibStream = class extends Transform { constructor(mode, opts = {}) { const { flush, ...streamOpts } = opts; super(streamOpts); 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.reset(); } _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-media/node_modules/bare-fetch/lib/response-stream.js var require_response_stream = __commonJS({ "../../node_modules/bare-media/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-media/node_modules/bare-fetch/index.js var require_bare_fetch = __commonJS({ "../../node_modules/bare-media/node_modules/bare-fetch/index.js"(exports, module) { var http = require_bare_http1(); var https = require_bare_https(); var { now, markResourceTiming } = require_bare_performance(); var { finished } = require_bare_stream(); var { ReadableStream } = require_web(); var Request = require_request(); var Response = require_response(); var ResponseStream = require_response_stream(); var Headers = require_headers(); var errors = require_errors13(); module.exports = exports = function fetch2(input, init = {}) { let resolve; let reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); const response = new Response(); response._type = "basic"; const timingInfo = { startTime: now(), endTime: 0 }; 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)}`); } 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) => { req.off("close", onclose); 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); } const responseStream = new ResponseStream(res); response._body = new ReadableStream(responseStream); response._status = res.statusCode; response._statusText = res.statusMessage; finished(responseStream, { cleanup: true }, processResponseEndOfBody); for (const [name, value] of Object.entries(res.headers)) { response._headers.set(name, value); } resolve(response); } ); req.on("error", onerror).on("close", onclose); try { if (request._body) { for await (const data of request._body) req.write(data); } req.end(); } catch (err) { req.destroy(err); } function processResponseEndOfBody(err) { if (err) return; timingInfo.endTime = now(); markResourceTiming(timingInfo, response._urls[0].href, "fetch", {}, "", {}, response.status); } function onerror(err) { req.off("close", onclose); reject(errors.NETWORK_ERROR("Network error", err)); } function onclose() { onerror(http.errors.CONNECTION_LOST()); } } }; 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-exif/binding.js var require_binding21 = __commonJS({ "../../node_modules/bare-exif/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-exif/index.js var require_bare_exif = __commonJS({ "../../node_modules/bare-exif/index.js"(exports) { var binding = require_binding21(); exports.constants = { tags: binding.tags, ifds: binding.ifds, formats: binding.formats, byteOrders: binding.byteOrders }; var EXIFEntry = class { // An entry borrows from the data tree it was read from. Holding on to the // parent keeps it reachable, so an entry can never be collected after the // tree it points into. constructor(data) { this._data = data; this._destroyed = false; this.tag = 0; this.format = 0; this.components = 0; this.size = 0; this.byteOrder = 0; this.data = null; } #readComponent(index) { const { formats, byteOrders } = binding; const littleEndian = this.byteOrder === byteOrders.INTEL; const view = new DataView(this.data); switch (this.format) { case formats.BYTE: return view.getUint8(index); case formats.SBYTE: return view.getInt8(index); case formats.SHORT: return view.getUint16(index * 2, littleEndian); case formats.SSHORT: return view.getInt16(index * 2, littleEndian); case formats.LONG: return view.getUint32(index * 4, littleEndian); case formats.SLONG: return view.getInt32(index * 4, littleEndian); case formats.FLOAT: return view.getFloat32(index * 4, littleEndian); case formats.DOUBLE: return view.getFloat64(index * 8, littleEndian); case formats.RATIONAL: { return { numerator: view.getUint32(index * 4, littleEndian), denominator: view.getUint32(index * 4 + 4, littleEndian) }; } case formats.SRATIONAL: { return { numerator: view.getInt32(index * 4, littleEndian), denominator: view.getInt32(index * 4 + 4, littleEndian) }; } case formats.ASCII: { let text = ""; for (let i = 0; i < view.byteLength; i++) { const c = view.getUint8(i); if (c === 0) break; text += String.fromCharCode(c); } return text; } case formats.UNDEFINED: return Buffer.from(this.data); default: return null; } } read() { if (this._destroyed) { throw new Error("EXIF entry has been destroyed"); } if (!this.components || this.components < 0) return null; if (this.components === 1 || this.format === binding.formats.ASCII || this.format === binding.formats.UNDEFINED) { return this.#readComponent(0); } const values = []; for (let i = 0; i < this.components; i++) { values.push(this.#readComponent(i)); } return values; } value() { return binding.entryValue(this); } destroy() { if (this._destroyed) return; this._data._entries.delete(this); binding.destroyEntry(this, this.data); this.data = null; this._destroyed = true; } [Symbol.dispose]() { this.destroy(); } }; exports.Data = class EXIFData { constructor(data) { this._destroyed = false; this._entries = /* @__PURE__ */ new Set(); binding.initData(this, data.buffer, data.byteOffset, data.byteLength); } entry(tag) { const entry = new EXIFEntry(this); if (binding.initEntry(entry, this, tag) === void 0) return null; this._entries.add(entry); return entry; } removeEntry(tag) { for (const entry of this._entries) { if (entry.tag === tag) entry.destroy(); } binding.removeEntry(this, tag); } saveData() { return new Uint8Array(binding.saveData(this)); } destroy() { if (this._destroyed) return; for (const entry of [...this._entries]) entry.destroy(); binding.destroyData(this); this._destroyed = true; } [Symbol.dispose]() { this.destroy(); } }; } }); // ../../node_modules/bare-image-resample/binding.js var require_binding22 = __commonJS({ "../../node_modules/bare-image-resample/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-image-resample/index.js var require_bare_image_resample = __commonJS({ "../../node_modules/bare-image-resample/index.js"(exports) { var binding = require_binding22(); exports.resize = function resize2(image2, width = 0, height = 0, opts = {}) { if (typeof width === "object") { opts = width; width = opts.width || 0; height = opts.height || 0; } let scale = opts.scale || 1; if (width) scale = width / image2.width; else if (height) scale = height / image2.height; if (width <= 0) width = image2.width * scale; if (height <= 0) height = image2.height * scale; width = Math.round(width); height = Math.round(height); const buffer = binding.resize( image2.data, image2.width, image2.height, width, height ); return { data: Buffer.from(buffer), width, height }; }; } }); // ../../node_modules/bare-media/src/video/io.js function createIOContext(fd, ffmpeg2) { const fileSize = import_bare_fs2.default.fstatSync(fd).size; let offset = 0; return new ffmpeg2.IOContext(4096, { onread: (buffer, requested) => { const read2 = import_bare_fs2.default.readSync(fd, buffer, 0, requested, offset); if (read2 === 0) return 0; offset += read2; return read2; }, onseek: (o, whence) => { if (whence === ffmpeg2.constants.seek.SIZE) return fileSize; if (whence === ffmpeg2.constants.seek.SET) offset = o; else if (whence === ffmpeg2.constants.seek.CUR) offset += o; else if (whence === ffmpeg2.constants.seek.END) offset = fileSize + o; else return -1; return offset; } }); } var import_bare_fs2; var init_io = __esm({ "../../node_modules/bare-media/src/video/io.js"() { import_bare_fs2 = __toESM(require_bare_fs(), 1); } }); // ../../node_modules/bare-media/src/video/metadata.js async function metadata2(fd) { const ffmpeg2 = await importFFmpeg(); const io = createIOContext(fd, ffmpeg2); using inputFormat = new ffmpeg2.InputFormatContext(io); const stream = inputFormat.getBestStream(ffmpeg2.constants.mediaTypes.VIDEO); if (!stream) throw new Error("No video stream found"); let displayRotation = 0; let correctiveRotation = 0; let flipH = false; let flipV = false; for (const entry of stream.sideData) { if (entry.type === ffmpeg2.constants.packetSideDataType.DISPLAYMATRIX) { const transform = parseDisplayMatrix(entry.data); if (transform) { displayRotation = transform.rotation; flipH = transform.flipH; flipV = transform.flipV; } break; } } correctiveRotation = (-displayRotation % 360 + 360) % 360; const { codec, codecParameters } = stream; const duration = getDuration(inputFormat, stream); return { width: codecParameters.width, height: codecParameters.height, codec: { id: codec.id, name: codec.name }, duration, avgFramerate: { numerator: stream.avgFramerate.numerator, denominator: stream.avgFramerate.denominator }, displayRotation, rotation: correctiveRotation, flipH, flipV }; } function getDuration(inputFormat, stream) { const streamDuration = getStreamDuration(stream); if (streamDuration > 0) return streamDuration; const formatDuration = getFormatDuration(inputFormat); if (formatDuration > 0) return formatDuration; return 0; } function getStreamDuration(stream) { if (!Number.isFinite(stream.duration) || stream.timeBase.denominator === 0) { return stream.duration; } return stream.duration * stream.timeBase.numerator / stream.timeBase.denominator; } function getFormatDuration(inputFormat) { if (!Number.isFinite(inputFormat.duration) || inputFormat.duration < 0) return 0; return inputFormat.duration / AV_TIME_BASE; } function parseDisplayMatrix(matrix) { const a = snap(matrix.readInt32LE(0) / 65536); const b = snap(matrix.readInt32LE(4) / 65536); const c = snap(matrix.readInt32LE(12) / 65536); const d = snap(matrix.readInt32LE(16) / 65536); let rotation = 0; let flipH = false; let flipV = false; const det = a * d - b * c; if (det > 0) { if (a === 1 && d === 1) rotation = 0; else if (b === -1 && c === 1) rotation = 90; else if (a === -1 && d === -1) rotation = 180; else if (b === 1 && c === -1) rotation = 270; } else { if (a === -1 && d === 1) { flipH = true; } else if (a === 1 && d === -1) { flipV = true; } else if (b === 1 && c === 1) { rotation = 90; flipH = true; } else if (b === -1 && c === -1) { rotation = 90; flipV = true; } } return { rotation, flipH, flipV }; } function snap(value, epsilon = 1e-3) { if (Math.abs(value - 1) < epsilon) return 1; if (Math.abs(value + 1) < epsilon) return -1; if (Math.abs(value) < epsilon) return 0; return value; } var AV_TIME_BASE; var init_metadata = __esm({ "../../node_modules/bare-media/src/video/metadata.js"() { init_codecs(); init_io(); AV_TIME_BASE = 1e6; } }); // ../../node_modules/bare-media/src/video/transcoder.js var transcoder_exports = {}; __export(transcoder_exports, { Transcoder: () => Transcoder, formatRegistry: () => formatRegistry }); function getOrientationFilter({ rotation, flipH, flipV }) { if (rotation === 90) { if (flipH) return "transpose=cclock_flip"; if (flipV) return "transpose=clock_flip"; return "transpose=cclock"; } if (rotation === 180) return "hflip,vflip"; if (rotation === 270) return "transpose=clock"; if (flipH) return "hflip"; if (flipV) return "vflip"; return null; } var import_bare_fs3, import_b4a, import_bare_ffmpeg, VIDEO, AUDIO, FormatRegistry, formatRegistry, TranscodeStreamConfig, VideoFrameProcessor, AudioFrameProcessor, Transcoder; var init_transcoder = __esm({ "../../node_modules/bare-media/src/video/transcoder.js"() { import_bare_fs3 = __toESM(require_bare_fs(), 1); import_b4a = __toESM(require_b4a(), 1); import_bare_ffmpeg = __toESM(require_bare_ffmpeg(), 1); init_metadata(); ({ VIDEO, AUDIO } = import_bare_ffmpeg.default.constants.mediaTypes); FormatRegistry = class { #formats = /* @__PURE__ */ new Map(); register(formatName, config) { this.#formats.set(formatName, { video: config.video, audio: config.audio, muxer: config.muxer || {} }); } getVideoConfig(formatName) { const format = this.#formats.get(formatName); if (!format?.video) { throw new Error(`Unsupported video output format: ${formatName}`); } return format.video; } getAudioConfig(formatName) { const format = this.#formats.get(formatName); if (!format?.audio) { throw new Error(`Unsupported audio output format: ${formatName}`); } return format.audio; } getMuxerOptions(formatName) { const format = this.#formats.get(formatName); return format?.muxer || {}; } hasFormat(formatName) { return this.#formats.has(formatName); } }; formatRegistry = new FormatRegistry(); formatRegistry.register("webm", { video: { id: import_bare_ffmpeg.default.constants.codecs.VP9, format: import_bare_ffmpeg.default.constants.pixelFormats.YUV420P, encoder: "libvpx-vp9" }, audio: { id: import_bare_ffmpeg.default.constants.codecs.OPUS, format: import_bare_ffmpeg.default.constants.sampleFormats.S16, sampleRate: 48e3, encoder: "libopus" }, muxer: { live: "1" } }); formatRegistry.register("mp4", { video: { id: import_bare_ffmpeg.default.constants.codecs.VP9, format: import_bare_ffmpeg.default.constants.pixelFormats.YUV420P, encoder: "libvpx-vp9" }, audio: { id: import_bare_ffmpeg.default.constants.codecs.OPUS, format: import_bare_ffmpeg.default.constants.sampleFormats.S16, sampleRate: 48e3, encoder: "libopus" }, muxer: { movflags: "frag_keyframe+delay_moov+default_base_moof" } }); formatRegistry.register("matroska", { video: { id: import_bare_ffmpeg.default.constants.codecs.VP9, format: import_bare_ffmpeg.default.constants.pixelFormats.YUV420P, encoder: "libvpx-vp9" }, audio: { id: import_bare_ffmpeg.default.constants.codecs.OPUS, format: import_bare_ffmpeg.default.constants.sampleFormats.S16, sampleRate: 48e3, encoder: "libopus" }, muxer: { live: "1" } }); formatRegistry.register("mkv", { video: { id: import_bare_ffmpeg.default.constants.codecs.VP9, format: import_bare_ffmpeg.default.constants.pixelFormats.YUV420P, encoder: "libvpx-vp9" }, audio: { id: import_bare_ffmpeg.default.constants.codecs.OPUS, format: import_bare_ffmpeg.default.constants.sampleFormats.S16, sampleRate: 48e3, encoder: "libopus" }, muxer: { live: "1" } }); TranscodeStreamConfig = class _TranscodeStreamConfig { static create(inputStream, outputFormatContext, containerFormat, outputParameters) { const config = new _TranscodeStreamConfig( inputStream, outputFormatContext, containerFormat, outputParameters ); return config.#initialize() ? config : null; } constructor(inputStream, outputFormatContext, containerFormat, outputParameters) { this.inputStream = inputStream; this.outputFormatContext = outputFormatContext; this.containerFormat = containerFormat; this.outputParameters = outputParameters; this.codecType = inputStream.codecParameters.type; this.outputStream = null; this.decoder = null; this.encoder = null; this.rescaler = null; this.resampler = null; this.fifo = null; this.fifoFrame = null; this.nextAudioPts = null; this.nextVideoPts = 0; this.lastWidth = null; this.lastHeight = null; this.lastFormat = null; this.orientation = null; this.orientationGraph = null; this.orientationSource = null; this.orientationSink = null; this.orientationFrame = null; this.orientationWidth = null; this.orientationHeight = null; this.orientationFormat = null; } isVideo() { return this.codecType === VIDEO; } isAudio() { return this.codecType === AUDIO; } getConfig() { return this.isVideo() ? formatRegistry.getVideoConfig(this.containerFormat) : formatRegistry.getAudioConfig(this.containerFormat); } #initialize() { this.decoder = this.#createDecoder(); if (!this.decoder) return false; if (this.isVideo()) this.orientation = this.#resolveOrientation(); this.outputStream = this.outputFormatContext.createStream(); this.#configureOutputStream(this.outputStream, this.decoder); this.encoder = this.#createEncoder(this.outputStream, this.decoder); this.outputStream.codecParameters.fromContext(this.encoder); return true; } #resolveOrientation() { for (const entry of this.inputStream.sideData) { if (entry.type !== import_bare_ffmpeg.default.constants.packetSideDataType.DISPLAYMATRIX) continue; const transform = parseDisplayMatrix(entry.data); const filter = getOrientationFilter(transform); if (!filter) return null; return { filter, swapsDimensions: transform.rotation === 90 || transform.rotation === 270 }; } return null; } #createDecoder() { let decoderContext = null; try { decoderContext = this.inputStream.decoder(); decoderContext.open(); return decoderContext; } catch (err) { console.warn(`Failed to create decoder for stream ${this.inputStream.index}: ${err.message}`); if (decoderContext) decoderContext.destroy(); return null; } } #configureOutputStream(outputStream, decoder) { const config = this.getConfig(); outputStream.codecParameters.type = this.codecType; outputStream.codecParameters.id = config.id; outputStream.codecParameters.format = config.format; if (this.isVideo()) { const swap = this.orientation?.swapsDimensions; const width = swap ? decoder.height : decoder.width; const height = swap ? decoder.width : decoder.height; outputStream.codecParameters.width = this.outputParameters?.width || width; outputStream.codecParameters.height = this.outputParameters?.height || height; outputStream.timeBase = new import_bare_ffmpeg.default.Rational(1, 9e4); } else { outputStream.codecParameters.sampleRate = config.sampleRate; outputStream.codecParameters.channelLayout = decoder.channelLayout.nbChannels > 2 ? import_bare_ffmpeg.default.ChannelLayout.from(import_bare_ffmpeg.default.constants.channelLayouts.STEREO) : decoder.channelLayout; outputStream.timeBase = new import_bare_ffmpeg.default.Rational(1, config.sampleRate); } } #createEncoder(outputStream, decoder) { const config = this.getConfig(); const encoder = new import_bare_ffmpeg.default.CodecContext(new import_bare_ffmpeg.default.Encoder(config.encoder)); outputStream.codecParameters.toContext(encoder); if (this.isVideo()) { this.#configureVideoEncoder(encoder, outputStream, decoder); } else { this.#configureAudioEncoder(encoder, outputStream); } if (this.outputFormatContext.outputFormat.flags & import_bare_ffmpeg.default.constants.formatFlags.GLOBALHEADER) { encoder.flags |= import_bare_ffmpeg.default.constants.codecFlags.GLOBAL_HEADER; } using encoderOptions = this.isVideo() ? import_bare_ffmpeg.default.Dictionary.from({ allow_sw: "1", deadline: "realtime", "cpu-used": "6", crf: "34", b: "0" }) : new import_bare_ffmpeg.default.Dictionary(); encoder.open(encoderOptions); return encoder; } #configureVideoEncoder(encoder, outputStream, decoder) { encoder.timeBase = outputStream.timeBase; encoder.width = outputStream.codecParameters.width; encoder.height = outputStream.codecParameters.height; encoder.pixelFormat = outputStream.codecParameters.format; if (decoder.frameRate && decoder.frameRate.valid) { encoder.frameRate = decoder.frameRate; } else { encoder.frameRate = new import_bare_ffmpeg.default.Rational(30, 1); } encoder.gopSize = 30; } #configureAudioEncoder(encoder, outputStream) { encoder.timeBase = outputStream.timeBase; encoder.sampleRate = outputStream.codecParameters.sampleRate; encoder.channelLayout = outputStream.codecParameters.channelLayout; encoder.sampleFormat = outputStream.codecParameters.format; } }; VideoFrameProcessor = class { constructor(transcoder) { this.transcoder = transcoder; } process(frame, config, packet) { if (!config.orientation) { this.#encodeFrame(frame, config, packet); return; } this.#ensureOrientationFilter(frame, config); const err = config.orientationGraph.pushFrame(config.orientationSource, frame); if (err < 0) throw new Error(`Failed to push video frame into orientation filter (${err})`); while (config.orientationGraph.pullFrame(config.orientationSink, config.orientationFrame) >= 0) { this.#encodeFrame(config.orientationFrame, config, packet); config.orientationFrame.unref(); } } #ensureOrientationFilter(frame, config) { if (config.orientationGraph && config.orientationWidth === frame.width && config.orientationHeight === frame.height && config.orientationFormat === frame.format) { return; } if (config.orientationGraph) config.orientationGraph.destroy(); const graph = new import_bare_ffmpeg.default.FilterGraph(); config.orientationGraph = graph; const source = new import_bare_ffmpeg.default.FilterContext(); const sink = new import_bare_ffmpeg.default.FilterContext(); const timeBase = config.inputStream.timeBase; graph.createFilter( source, new import_bare_ffmpeg.default.Filter("buffer"), "in", `video_size=${frame.width}x${frame.height}:pix_fmt=${frame.format}:time_base=${timeBase.numerator}/${timeBase.denominator}:pixel_aspect=1/1` ); graph.createFilter(sink, new import_bare_ffmpeg.default.Filter("buffersink"), "out"); using outputs = new import_bare_ffmpeg.default.FilterInOut(); outputs.name = "in"; outputs.filterContext = source; outputs.padIdx = 0; using inputs = new import_bare_ffmpeg.default.FilterInOut(); inputs.name = "out"; inputs.filterContext = sink; inputs.padIdx = 0; graph.parse(config.orientation.filter, inputs, outputs); graph.configure(); config.orientationSource = source; config.orientationSink = sink; if (!config.orientationFrame) config.orientationFrame = new import_bare_ffmpeg.default.Frame(); config.orientationWidth = frame.width; config.orientationHeight = frame.height; config.orientationFormat = frame.format; } #encodeFrame(frame, config, packet) { const { inputStream, encoder, outputStream } = config; if (!config.rescaler || config.lastWidth !== frame.width || config.lastHeight !== frame.height || config.lastFormat !== frame.format) { if (config.rescaler) config.rescaler.destroy(); config.rescaler = new import_bare_ffmpeg.default.Scaler( frame.format, frame.width, frame.height, encoder.pixelFormat, encoder.width, encoder.height ); config.lastWidth = frame.width; config.lastHeight = frame.height; config.lastFormat = frame.format; } const outFrame = new import_bare_ffmpeg.default.Frame(); outFrame.format = encoder.pixelFormat; outFrame.width = encoder.width; outFrame.height = encoder.height; outFrame.alloc(); outFrame.copyProperties(frame); config.rescaler.scale(frame, outFrame); const frameDuration = encoder.timeBase.denominator * encoder.frameRate.denominator / (encoder.timeBase.numerator * encoder.frameRate.numerator); outFrame.pts = frame.pts === -1 ? config.nextVideoPts : import_bare_ffmpeg.default.Rational.rescaleQ(frame.pts, inputStream.timeBase, encoder.timeBase); config.nextVideoPts = outFrame.pts + frameDuration; this.transcoder._encodeAndWrite(encoder, outFrame, outputStream, packet); outFrame.destroy(); } }; AudioFrameProcessor = class { constructor(transcoder) { this.transcoder = transcoder; } process(frame, config, packet) { const { inputStream, encoder, outputStream } = config; if (config.nextAudioPts === null) { config.nextAudioPts = frame.pts === -1 ? 0 : import_bare_ffmpeg.default.Rational.rescaleQ(frame.pts, inputStream.timeBase, encoder.timeBase); } if (!config.resampler) { config.resampler = new import_bare_ffmpeg.default.Resampler( frame.sampleRate, frame.channelLayout, frame.format, encoder.sampleRate, encoder.channelLayout, encoder.sampleFormat ); } if (!config.fifo) { config.fifo = new import_bare_ffmpeg.default.AudioFIFO( encoder.sampleFormat, encoder.channelLayout.nbChannels, encoder.frameSize ); config.fifoFrame = new import_bare_ffmpeg.default.Frame(); } const outFrame = new import_bare_ffmpeg.default.Frame(); outFrame.format = encoder.sampleFormat; outFrame.channelLayout = encoder.channelLayout; outFrame.sampleRate = encoder.sampleRate; const outSamples = Math.ceil(frame.nbSamples * encoder.sampleRate / frame.sampleRate) + 32; outFrame.nbSamples = outSamples; outFrame.alloc(); const convertedSamples = config.resampler.convert(frame, outFrame); outFrame.nbSamples = convertedSamples; config.fifo.write(outFrame); outFrame.destroy(); const frameSize = encoder.frameSize; while (config.fifo.size >= frameSize) { const fifoFrame = this.#readFifo(config, frameSize); this.transcoder._encodeAndWrite(encoder, fifoFrame, outputStream, packet); } } flush(config, packet) { if (config.fifo && config.fifo.size > 0) { const fifoFrame = this.#readFifo(config, config.fifo.size); this.transcoder._encodeAndWrite(config.encoder, fifoFrame, config.outputStream, packet); } } // av_frame_get_buffer() leaks if the frame still holds a buffer, so unref // before every realloc. Unref also resets the frame properties. #readFifo(config, nbSamples) { const { encoder, fifoFrame } = config; fifoFrame.unref(); fifoFrame.format = encoder.sampleFormat; fifoFrame.channelLayout = encoder.channelLayout; fifoFrame.sampleRate = encoder.sampleRate; fifoFrame.nbSamples = nbSamples; fifoFrame.alloc(); config.fifo.read(fifoFrame, nbSamples); fifoFrame.pts = config.nextAudioPts; config.nextAudioPts += fifoFrame.nbSamples; return fifoFrame; } }; Transcoder = class { constructor(fd, opts = {}) { this.fd = fd; this.outputParameters = opts.outputParameters || {}; this.bufferSize = opts.bufferSize || 32 * 1024; this.chunks = []; this.currentTime = 0; this.inputFormatContext = null; this.outputFormatContext = null; this.configs = []; this.containerFormat = null; this.videoProcessor = new VideoFrameProcessor(this); this.audioProcessor = new AudioFrameProcessor(this); } async *transcode() { try { this.#setupIOContexts(); this.#discoverAndConfigureStreams(); this.#configureOutput(); yield* this.#processFrames(); yield* this.#finalize(); } finally { this.#cleanup(); } } #setupIOContexts() { const fileSize = import_bare_fs3.default.fstatSync(this.fd).size; let offset = 0; const inIO = new import_bare_ffmpeg.default.IOContext(4096, { onread: (buffer, requested) => { const read2 = import_bare_fs3.default.readSync(this.fd, buffer, 0, requested, offset); if (read2 === 0) return 0; offset += read2; return read2; }, onseek: (o, whence) => { if (whence === import_bare_ffmpeg.default.constants.seek.SIZE) return fileSize; if (whence === import_bare_ffmpeg.default.constants.seek.SET) offset = o; else if (whence === import_bare_ffmpeg.default.constants.seek.CUR) offset += o; else if (whence === import_bare_ffmpeg.default.constants.seek.END) offset = fileSize + o; else return -1; return offset; } }); this.inputFormatContext = new import_bare_ffmpeg.default.InputFormatContext(inIO); this.containerFormat = this.outputParameters?.format || "mp4"; if (!formatRegistry.hasFormat(this.containerFormat)) { throw new Error(`Unsupported output format: ${this.containerFormat}`); } const outIO = new import_bare_ffmpeg.default.IOContext(this.bufferSize, { onwrite: (chunk) => { this.chunks.push(import_b4a.default.from(chunk)); return chunk.length; } }); this.outputFormatContext = new import_bare_ffmpeg.default.OutputFormatContext(this.containerFormat, outIO); } #discoverAndConfigureStreams() { const videoBestStreamIndex = this.inputFormatContext.getBestStreamIndex(VIDEO); const audioBestStreamIndex = this.inputFormatContext.getBestStreamIndex(AUDIO); for (const inputStream of this.inputFormatContext.streams) { const codecType = inputStream.codecParameters.type; if (codecType !== VIDEO && codecType !== AUDIO) { continue; } const config = TranscodeStreamConfig.create( inputStream, this.outputFormatContext, this.containerFormat, this.outputParameters ); if (!config) { if (inputStream.index !== videoBestStreamIndex && inputStream.index !== audioBestStreamIndex) { continue; } throw new Error(`Input ${codecType === VIDEO ? "video" : "audio"} stream is not decodable`); } this.configs[inputStream.index] = config; } } #configureOutput() { const options = formatRegistry.getMuxerOptions(this.containerFormat); const muxerOptions = import_bare_ffmpeg.default.Dictionary.from(options); const duration = this.inputFormatContext.duration; if (duration > 0) { this.outputFormatContext.duration = duration; if (muxerOptions.get("live") === "1") { muxerOptions.set("live", "0"); } } this.outputFormatContext.writeHeader(muxerOptions); } #trackTime(packet, config) { const ts = packet.dts; const tb = config.inputStream.timeBase; if (!Number.isFinite(ts) || ts < 0 || !tb.denominator) return; const seconds = ts * tb.numerator / tb.denominator; if (Number.isFinite(seconds) && seconds > this.currentTime) { this.currentTime = seconds; } } #handleDecodedFrame(frame, config, packet) { if (config.isVideo()) { this.videoProcessor.process(frame, config, packet); } else if (config.isAudio()) { this.audioProcessor.process(frame, config, packet); } } *#drainChunks() { for (const chunk of this.chunks) { yield { buffer: chunk, time: this.currentTime }; } this.chunks = []; } *#processFrames() { const packet = new import_bare_ffmpeg.default.Packet(); const frame = new import_bare_ffmpeg.default.Frame(); try { while (this.inputFormatContext.readFrame(packet)) { const config = this.configs[packet.streamIndex]; if (!config) { packet.unref(); continue; } this.#trackTime(packet, config); const { decoder } = config; if (decoder.sendPacket(packet)) { while (decoder.receiveFrame(frame)) { this.#handleDecodedFrame(frame, config, packet); } } packet.unref(); yield* this.#drainChunks(); } } finally { packet.destroy(); frame.destroy(); } } *#finalize() { const packet = new import_bare_ffmpeg.default.Packet(); const frame = new import_bare_ffmpeg.default.Frame(); try { for (const index in this.configs) { const config = this.configs[index]; this.#drainDecoder(config, packet, frame); this.audioProcessor.flush(config, packet); this._encodeAndWrite(config.encoder, null, config.outputStream, packet); } this.outputFormatContext.writeTrailer(); yield* this.#drainChunks(); } finally { packet.destroy(); frame.destroy(); } } #drainDecoder(config, packet, frame) { const { decoder } = config; packet.unref(); if (!decoder.sendPacket(packet)) return; while (decoder.receiveFrame(frame)) { this.#handleDecodedFrame(frame, config, packet); } } #cleanup() { for (const index in this.configs) { const config = this.configs[index]; config.decoder.destroy(); config.encoder.destroy(); if (config.rescaler) config.rescaler.destroy(); if (config.resampler) config.resampler.destroy(); if (config.fifo) config.fifo.destroy(); if (config.fifoFrame) config.fifoFrame.destroy(); if (config.orientationGraph) config.orientationGraph.destroy(); if (config.orientationFrame) config.orientationFrame.destroy(); } if (this.inputFormatContext) this.inputFormatContext.destroy(); if (this.outputFormatContext) this.outputFormatContext.destroy(); } _encodeAndWrite(encoder, frame, outputStream, packet) { if (encoder.sendFrame(frame)) { while (encoder.receivePacket(packet)) { packet.streamIndex = outputStream.index; packet.rescaleTimestamps(encoder.timeBase, outputStream.timeBase); this.outputFormatContext.writeFrame(packet); packet.unref(); } } } }; } }); // ../../bare-lib-entry-bareMedia.js var bare_lib_entry_bareMedia_exports = {}; __export(bare_lib_entry_bareMedia_exports, { default: () => bare_lib_entry_bareMedia_default }); // ../../node_modules/bare-media/index.js var bare_media_exports = {}; __export(bare_media_exports, { codecs: () => codecs, detectMimeType: () => detectMimeType, image: () => image, importCodec: () => importCodec, importFFmpeg: () => importFFmpeg, supportsQuality: () => supportsQuality, video: () => video }); init_codecs(); // ../../node_modules/bare-media/src/image.js var import_bare_fs = __toESM(require_bare_fs(), 1); var import_bare_fetch = __toESM(require_bare_fetch(), 1); init_types(); init_codecs(); // ../../node_modules/bare-media/src/image/dimensions.js function calculateFitDimensions(width, height, maxWidth = Infinity, maxHeight = Infinity) { if (width <= maxWidth && height <= maxHeight) { return { width, height }; } const widthRatio = maxWidth / width; const heightRatio = maxHeight / height; const ratio = Math.min(widthRatio, heightRatio); return { width: Math.round(width * ratio), height: Math.round(height * ratio) }; } // ../../node_modules/bare-media/src/image/metadata.js init_types(); init_codecs(); var supportedExifMimetypes = /* @__PURE__ */ new Set([IMAGE.JPEG, IMAGE.JPG, IMAGE.TIFF, IMAGE.TIF]); function isExifSupported(buffer) { return supportedExifMimetypes.has(detectMimeType(buffer)); } function readEntry(entry) { const value = entry.read(); return Buffer.isBuffer(value) ? Buffer.from(value) : value; } function resolveExifTag(exif, tag) { if (typeof tag === "number") return tag; if (typeof tag === "string") { for (const [name, value] of Object.entries(exif.constants.tags)) { if (name.toLowerCase() === tag.toLowerCase()) { return value; } } } return null; } async function exifValue(buffer, tag) { try { const exif = await Promise.resolve().then(() => __toESM(require_bare_exif(), 1)); using exifData = new exif.Data(buffer); const entry = exifData.entry(resolveExifTag(exif, tag)); return entry ? readEntry(entry) : void 0; } catch { return null; } } async function exifMetadata(buffer) { if (!isExifSupported(buffer)) return {}; const data = {}; try { const exif = await Promise.resolve().then(() => __toESM(require_bare_exif(), 1)); using exifData = new exif.Data(buffer); for (const [name, tag] of Object.entries(exif.constants.tags)) { const entry = exifData.entry(tag); if (!entry) continue; data[name] = readEntry(entry); } } finally { return data; } } function metadataTag(buffer, tag) { if (!isExifSupported(buffer)) return null; return exifValue(buffer, tag); } async function metadata(buffer, opts = {}) { if (!isExifSupported(buffer)) return {}; if (opts.tag) { return metadataTag(buffer, opts.tag); } const data = {}; data.exif = await exifMetadata(buffer); if (data.exif.ORIENTATION) { data.orientation = data.exif.ORIENTATION; } return data; } async function stripJPEG(buffer, opts = {}) { const { keepColor = true, keepOrientation = false } = opts; const jpeg = await Promise.resolve().then(() => __toESM(require_bare_jpeg(), 1)); const APP1 = 225; const APP14 = 238; const { markers } = jpeg.readHeader(buffer); let newMarkers = []; if (keepColor) { newMarkers = markers.filter((m) => m.marker === APP14); } if (keepOrientation) { const exif = await Promise.resolve().then(() => __toESM(require_bare_exif(), 1)); const tags = exif.constants.tags; using data = new exif.Data(buffer); for (const tag of Object.values(tags)) { if (tag !== tags.ORIENTATION) { data.removeEntry(tag); } } const rawExif = data.saveData(); newMarkers.push({ marker: APP1, data: rawExif }); } return jpeg.replaceMarkers(buffer, newMarkers); } function strip(buffer, opts = {}) { const mimetype = detectMimeType(buffer); if (mimetype === IMAGE.JPEG || mimetype === IMAGE.JPG) { return stripJPEG(buffer, opts); } throw new Error(`metadata strip(): unsupported type ${mimetype}`); } var ImageMetadataPipeline = class { constructor(input, opts = {}) { this.input = input; this.steps = []; this.read = opts.read; this.write = opts.save; const methods = ["strip"]; for (let method of methods) { this[method] = (opts2) => { this.steps.push({ op: method, opts: opts2 }); return this; }; } } async then(resolve, reject) { try { let buffer = await this.read(this.input); for (const step of this.steps) { if (step.op === "strip") { buffer = await strip(buffer, step.opts); } } resolve(buffer); } catch (err) { reject(err); } } async save(filename, opts) { const buffer = await this; return this.write(filename, buffer, opts); } }; metadata.strip = strip; // ../../node_modules/bare-media/src/image.js var animatableMimetypes = ["image/gif", "image/webp"]; async function read(input) { let buffer; if (typeof input === "string") { if (_isHttpUrl(input)) { const response = await (0, import_bare_fetch.default)(input); buffer = await response.buffer(); } else { buffer = await import_bare_fs.default.readFile(input); } } else { buffer = input; } return buffer; } function save(filename, buffer, opts) { return import_bare_fs.default.writeFile(filename, buffer, opts); } async function decode(buffer, opts = {}) { const { maxFrames = 0 } = opts; let rgba; const mimetype = detectMimeType(buffer); const codec = await importCodec(mimetype); if (animatableMimetypes.includes(mimetype)) { const { width, height, loops, frames } = codec.decodeAnimated(buffer); const data = []; for (const frame of frames) { if (maxFrames > 0 && data.length >= maxFrames) break; data.push(frame); } rgba = { width, height, loops, frames: data }; } else { rgba = codec.decode(buffer); } return rgba; } async function encode(rgba, opts = {}) { const { mimetype, maxBytes, ...codecOpts } = opts; let encoded = await _encodeRGBA(rgba, mimetype, codecOpts); if (maxBytes) { if (encoded.byteLength > maxBytes && supportsQuality(mimetype)) { const MIN_QUALITY = 50; for (let quality = 80; quality >= MIN_QUALITY; quality -= 15) { encoded = await _encodeRGBA(rgba, mimetype, { quality }); if (encoded.byteLength <= maxBytes) { break; } } } if (encoded.byteLength > maxBytes && rgba.frames?.length > 1) { const quality = 75; for (const dropEvery of [4, 3, 2]) { const frames = rgba.frames.filter((frame, index) => index % dropEvery !== 0); const filtered = { ...rgba, frames }; encoded = await _encodeRGBA(filtered, mimetype, { quality }); if (encoded.byteLength <= maxBytes) { break; } } if (encoded.byteLength > maxBytes) { const frames = rgba.frames.slice(0, 50).filter((frame, index) => index % 2 === 0); const capped = { ...rgba, frames }; encoded = await _encodeRGBA(capped, mimetype, { quality }); } if (encoded.byteLength > maxBytes) { const oneFrame = { ...rgba, frames: rgba.frames.slice(0, 1) }; encoded = await _encodeRGBA(oneFrame, mimetype); } } if (encoded.byteLength > maxBytes) { throw new Error( `Could not create preview under maxBytes, reached ${encoded.byteLength} bytes` ); } } return encoded; } function _cropFrame(frame, opts) { const { left, top, width, height } = opts; const data = Buffer.alloc(width * height * 4); for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcIndex = ((y + top) * frame.width + (x + left)) * 4; const dstIndex = (y * width + x) * 4; data[dstIndex] = frame.data[srcIndex]; data[dstIndex + 1] = frame.data[srcIndex + 1]; data[dstIndex + 2] = frame.data[srcIndex + 2]; data[dstIndex + 3] = frame.data[srcIndex + 3]; } } return { ...frame, width, height, data }; } function crop(rgba, opts = {}) { const { left, top, width, height } = opts; if (left < 0 || top < 0 || width <= 0 || height <= 0 || left + width > rgba.width || top + height > rgba.height) { throw new Error("Crop rectangle out of bounds"); } if (!Number.isInteger(left) || !Number.isInteger(top) || !Number.isInteger(width) || !Number.isInteger(height)) { throw new Error("Crop rectangle coordinates must be integers"); } if (Array.isArray(rgba.frames)) { const frames = rgba.frames.map((frame) => _cropFrame(frame, opts)); return { ...rgba, width, height, frames }; } return _cropFrame(rgba, opts); } async function resize(rgba, opts = {}) { const { maxWidth, maxHeight } = opts; const { width, height } = rgba; let maybeResizedRGBA; if ((maxWidth || maxHeight) && (width > maxWidth || height > maxHeight)) { const { resize: resize2 } = await Promise.resolve().then(() => __toESM(require_bare_image_resample(), 1)); const dimensions = calculateFitDimensions(width, height, maxWidth, maxHeight); if (Array.isArray(rgba.frames)) { const frames = []; for (const frame of rgba.frames) { const resized = resize2(frame, dimensions.width, dimensions.height); frames.push({ ...resized, timestamp: frame.timestamp }); } maybeResizedRGBA = { width: frames[0].width, height: frames[0].height, loops: rgba.loops, frames }; } else { maybeResizedRGBA = resize2(rgba, dimensions.width, dimensions.height); } } else { maybeResizedRGBA = rgba; } return maybeResizedRGBA; } function slice(rgba, opts = {}) { if (Array.isArray(rgba.frames)) { let { start = 0, end = rgba.frames.length } = opts; start = Math.max(0, start); end = Math.max(0, end); if (start >= end) { throw new Error('slice(): "start" must be less than "end"'); } return { ...rgba, frames: rgba.frames.slice(start, end) }; } return rgba; } function rotate(rgba, opts = {}) { const { deg } = opts; if (![0, 90, 180, 270].includes(deg)) { throw new Error("rotate(): deg can only be [0, 90, 180, 270]"); } return _transform(rgba, { rotate: deg }); } function flip(rgba, opts = {}) { const { h = true, v } = opts; if (typeof h !== "boolean" && typeof v !== "boolean") { throw new Error("flip(): needs axis h or v to be a boolean"); } return _transform(rgba, { flipH: h, flipV: v }); } async function orientate(rgba, opts = {}) { if (opts.transform !== void 0) { const { rotate: rotate2 = 0, flipH = false, flipV = false } = opts.transform; if (![0, 90, 180, 270].includes(rotate2)) { throw new Error("orientate(): transform.rotate can only be [0, 90, 180, 270]"); } if (typeof flipH !== "boolean" || typeof flipV !== "boolean") { throw new Error("orientate(): transform.flipH and transform.flipV must be boolean"); } return _transform(rgba, { rotate: rotate2, flipH, flipV }); } let orientation; if (opts.file) { orientation = await metadata(opts.file, { tag: "orientation" }); } else if (opts.exif !== void 0) { orientation = opts.exif; } else { throw new Error('orientate(): needs either "file", "exif", or "transform"'); } let transformOpts; switch (orientation) { case EXIF.ORIENTATION.NORMAL: break; case EXIF.ORIENTATION.MIRROR_HORIZONTAL: transformOpts = { flipH: true }; break; case EXIF.ORIENTATION.ROTATE_180: transformOpts = { rotate: 180 }; break; case EXIF.ORIENTATION.MIRROR_VERTICAL: transformOpts = { flipV: true }; break; case EXIF.ORIENTATION.TRANSPOSE: transformOpts = { rotate: 270, flipH: true }; break; case EXIF.ORIENTATION.ROTATE_90: transformOpts = { rotate: 90 }; break; case EXIF.ORIENTATION.TRANSVERSE: transformOpts = { rotate: 90, flipH: true }; break; case EXIF.ORIENTATION.ROTATE_270: transformOpts = { rotate: 270 }; break; default: break; } if (!transformOpts) return rgba; return _transform(rgba, transformOpts); } function _transform(rgba, opts) { const { rotate: rotate2 = 0, flipH = false, flipV = false } = opts; if (rotate2 === 0 && !flipH && !flipV) return rgba; const transformFrame = (frame) => { const srcWidth = frame.width; const srcHeight = frame.height; const dstWidth = rotate2 === 90 || rotate2 === 270 ? srcHeight : srcWidth; const dstHeight = rotate2 === 90 || rotate2 === 270 ? srcWidth : srcHeight; const data = Buffer.alloc(dstWidth * dstHeight * 4); for (let y = 0; y < srcHeight; y++) { for (let x = 0; x < srcWidth; x++) { const transformedX = flipH ? srcWidth - 1 - x : x; const transformedY = flipV ? srcHeight - 1 - y : y; let dstX; let dstY; switch (rotate2) { case 90: dstX = srcHeight - 1 - transformedY; dstY = transformedX; break; case 180: dstX = srcWidth - 1 - transformedX; dstY = srcHeight - 1 - transformedY; break; case 270: dstX = transformedY; dstY = srcWidth - 1 - transformedX; break; default: dstX = transformedX; dstY = transformedY; break; } const srcIndex = (y * srcWidth + x) * 4; const dstIndex = (dstY * dstWidth + dstX) * 4; data[dstIndex] = frame.data[srcIndex]; data[dstIndex + 1] = frame.data[srcIndex + 1]; data[dstIndex + 2] = frame.data[srcIndex + 2]; data[dstIndex + 3] = frame.data[srcIndex + 3]; } } return { ...frame, width: dstWidth, height: dstHeight, data }; }; if (Array.isArray(rgba.frames)) { const frames = rgba.frames.map(transformFrame); return { ...rgba, width: frames[0].width, height: frames[0].height, frames }; } return transformFrame(rgba); } async function _encodeRGBA(rgba, mimetype, opts) { const codec = await importCodec(mimetype); let encoded; if (Array.isArray(rgba.frames)) { encoded = codec.encodeAnimated(rgba, opts); } else { encoded = codec.encode(rgba, opts); } return encoded; } function _isHttpUrl(value) { try { const url = new URL(value); return url.protocol === "http:" || url.protocol === "https:"; } catch { return false; } } var ImagePipeline = class { constructor(input) { this.input = input; this.steps = []; const methods = ["decode", "resize", "crop", "slice", "orientate", "rotate", "flip", "encode"]; for (let method of methods) { this[method] = (opts) => { this.steps.push({ op: method, opts }); return this; }; } this.metadata = (opts) => read(input).then((buffer) => metadata(buffer, opts)); this.metadata.strip = (opts) => new ImageMetadataPipeline(input, { read, save }).strip(opts); } async then(resolve, reject) { try { let buffer = await read(this.input); let inputBuffer; if (this.steps.some((step) => step.op === "orientate" && !step.opts)) { inputBuffer = buffer; } for (const step of this.steps) { if (step.op === "decode") { buffer = await decode(buffer, step.opts); } if (step.op === "resize") { buffer = await resize(buffer, step.opts); } if (step.op === "crop") { buffer = await crop(buffer, step.opts); } if (step.op === "slice") { buffer = slice(buffer, step.opts); } if (step.op === "orientate") { buffer = await orientate(buffer, step.opts || { file: inputBuffer }); } if (step.op === "rotate") { buffer = await rotate(buffer, step.opts); } if (step.op === "flip") { buffer = await flip(buffer, step.opts); } if (step.op === "encode") { buffer = await encode(buffer, step.opts); } } resolve(buffer); } catch (err) { reject(err); } } async save(filename, opts) { const buffer = await this; return save(filename, buffer, opts); } }; function image(input) { return new ImagePipeline(input); } image.read = read; image.save = save; image.decode = decode; image.orientate = orientate; image.rotate = rotate; image.flip = flip; image.resize = resize; image.crop = crop; image.slice = slice; image.encode = encode; image.metadata = metadata; // ../../node_modules/bare-media/src/video.js var import_bare_fs4 = __toESM(require_bare_fs(), 1); init_codecs(); init_io(); init_metadata(); async function extractFrames(fd, opts = {}) { const { frameIndex } = opts; const ffmpeg2 = await importFFmpeg(); const io = createIOContext(fd, ffmpeg2); using inputFormat = new ffmpeg2.InputFormatContext(io); const stream = inputFormat.getBestStream(ffmpeg2.constants.mediaTypes.VIDEO); using decoder = stream.decoder(); decoder.open(); using packet = new ffmpeg2.Packet(); using frame = new ffmpeg2.Frame(); let currentFrame = 0; let result = null; while (inputFormat.readFrame(packet)) { if (packet.streamIndex === stream.index) { if (decoder.sendPacket(packet)) { while (decoder.receiveFrame(frame)) { if (currentFrame === frameIndex) { using scaler = new ffmpeg2.Scaler( frame.format, frame.width, frame.height, ffmpeg2.constants.pixelFormats.RGBA, frame.width, frame.height ); using rgbaFrame = new ffmpeg2.Frame(); rgbaFrame.width = frame.width; rgbaFrame.height = frame.height; rgbaFrame.format = ffmpeg2.constants.pixelFormats.RGBA; rgbaFrame.alloc(); scaler.scale(frame, rgbaFrame); const image2 = new ffmpeg2.Image( ffmpeg2.constants.pixelFormats.RGBA, rgbaFrame.width, rgbaFrame.height ); image2.read(rgbaFrame); result = { width: rgbaFrame.width, height: rgbaFrame.height, data: image2.data }; break; } currentFrame++; } } } packet.unref(); if (result) break; } if (!result) { throw new Error(`Frame ${frameIndex} not found (video only has ${currentFrame} frames)`); } return result; } async function* transcode(fd, opts = {}) { const { Transcoder: Transcoder2 } = await Promise.resolve().then(() => (init_transcoder(), transcoder_exports)); const transcoder = new Transcoder2(fd, { outputParameters: { format: opts.format, width: opts.width, height: opts.height }, bufferSize: opts.bufferSize }); yield* transcoder.transcode(); } var VideoPipeline = class { constructor(input) { this.input = input; this.steps = []; } async extractFrames(opts) { let fd; let result; try { fd = import_bare_fs4.default.openSync(this.input, "r"); result = await extractFrames(fd, opts); } finally { import_bare_fs4.default.closeSync(fd); } return result; } async metadata() { let fd; let result; try { fd = import_bare_fs4.default.openSync(this.input, "r"); result = await metadata2(fd); } finally { import_bare_fs4.default.closeSync(fd); } return result; } async *transcode(opts) { const fd = import_bare_fs4.default.openSync(this.input, "r"); try { yield* transcode(fd, opts); } finally { import_bare_fs4.default.closeSync(fd); } } }; function video(input) { return new VideoPipeline(input); } async function getFormatRegistry() { const { formatRegistry: formatRegistry2 } = await Promise.resolve().then(() => (init_transcoder(), transcoder_exports)); return formatRegistry2; } async function getConstants() { const ffmpeg2 = await Promise.resolve().then(() => __toESM(require_bare_ffmpeg(), 1)); return ffmpeg2.constants; } video.extractFrames = extractFrames; video.metadata = metadata2; video.transcode = transcode; video.getFormatRegistry = getFormatRegistry; video.getConstants = getConstants; // ../../bare-lib-entry-bareMedia.js var bare_lib_entry_bareMedia_default = bare_media_exports; return __toCommonJS(bare_lib_entry_bareMedia_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]["bareMedia"]=v;})();