"use strict";
const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
  return typeof document === 'undefined'
    ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
    : (document.currentScript && document.currentScript.src) ||
      new URL('main.js', document.baseURI).href;
})();
;
exports.ids = ["20"];
exports.modules = {
"../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/index.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  Adb: () => (/* reexport */ Adb),
  AdbServerClient: () => (/* reexport */ AdbServerClient)
});

// UNUSED EXPORTS: adbSyncPushV2, AdbSyncError, AdbNoneProtocolSpawner, ADB_DAEMON_DEFAULT_FEATURES, AdbBanner, ADB_DAEMON_VERSION_OMIT_CHECKSUM, AdbSync, adbSyncOpenDir, AdbBannerKey, AdbShellProtocolId, AdbShellProtocolSpawner, AdbDaemonSocketController, AdbSyncSendV2Flags, AdbShellProtocolPtyProcess, AdbSyncLstatResponse, AdbDaemonTransport, AdbReverseErrorResponse, AdbShellProtocolPacket, adbSyncLstat, encodeUtf8, AdbDaemonSocket, LinuxFileType, AdbFeature, calculateChecksum, dirname, adbSyncReadResponses, raceSignal, setBigUint, adbSyncPushV1, ADB_SERVER_DEFAULT_FEATURES, ADB_SYNC_MAX_PACKET_SIZE, AdbFrameBufferV1, AdbNoneProtocolSubprocessService, rsaParsePrivateKey, AdbShellProtocolSubprocessService, adbSyncEncodeId, AdbPublicKeyAuthenticator, FAIL, hexToNumber, unreachable, AdbPower, AdbSyncResponseId, AdbSyncDataResponse, AdbAuthType, adbSyncReadResponse, SHA1_DIGEST_INFO, AdbFrameBufferForbiddenError, AdbServerTransport, AdbServerStream, AdbAuthenticationProcessor, AdbReverseNotSupportedError, AdbReverseService, ASN1_OID, ASN1_OCTET_STRING, ASN1_NULL, rsaSign, AdbSubprocessService, ASN1_SEQUENCE, AdbSyncSocketLocked, AdbSyncFailResponse, AdbSyncStatErrorCode, adbSyncWriteRequest, adbGetPublicKeySize, decodeUtf8, AdbReverseError, AdbNoneProtocolProcessImpl, AdbServiceBase, adbSyncPullGenerator, NOOP, sequenceEqual, AdbSyncStatResponse, adbSyncPush, AdbPacketSerializeStream, AdbSignatureAuthenticator, AdbFrameBufferUnsupportedVersionError, Ref, ADB_DEFAULT_AUTHENTICATORS, AdbFrameBufferError, splitCommand, getBigUint, AdbFrameBufferV2, AdbSyncSocket, adbSyncStat, AdbSyncSendV2Request, unorderedRemove, AdbTcpIpService, SHA1_DIGEST_LENGTH, write4HexDigits, AdbSyncEntry2Response, decodeBase64, modInverse, adbGeneratePublicKey, AdbNoneProtocolPtyProcess, adbSyncOpenDirV1, AdbServerDeviceObserverOwner, AdbShellProtocolProcessImpl, AdbSyncEntryResponse, AutoResetEvent, adbSyncPull, encodeBase64, AdbSyncOkResponse, AdbPacketDispatcher, escapeArg, AdbPacket, AdbSyncRequestId, toLocalUint8Array, AdbSyncNumberRequest, powMod, framebuffer, adbSyncOpenDirV2, ADB_DAEMON_DEFAULT_INITIAL_PAYLOAD_SIZE, AdbPacketHeader, calculateBase64EncodedLength, AdbCommand

// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/encoding.js
var encoding = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/encoding.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+async@4.1.3/node_modules/@yume-chan/async/esm/promise-resolver.js
var promise_resolver = __webpack_require__("../../node_modules/.pnpm/@yume-chan+async@4.1.3/node_modules/@yume-chan/async/esm/promise-resolver.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/buffer.js
var esm_buffer = __webpack_require__("../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/buffer.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/stream.js
var esm_stream = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/stream.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/concat.js



// `TransformStream` only calls its `source.flush` method when its `readable` is being read.
// If the user want to use the `Promise` interface, the `flush` method will never be called,
// so the `PromiseResolver` will never be resolved.
// Thus we need to implement our own `TransformStream` using a `WritableStream` and a `ReadableStream`.
/**
 * A `TransformStream` that concatenates strings.
 *
 * Its `readable` is also a `Promise<string>`, so it's possible to `await` it to get the result.
 *
 * ```ts
 * const result: string = await readable.pipeThrough(new ConcatStringStream());
 * ```
 */
class ConcatStringStream {
    // PERF: rope (concat strings) is faster than `[].join('')`
    #result = "";
    #resolver = new promise_resolver/* .PromiseResolver */.O();
    #writable = new esm_stream/* .WritableStream */.ho({
        write: (chunk) => {
            this.#result += chunk;
        },
        close: () => {
            this.#resolver.resolve(this.#result);
            this.#readableController.enqueue(this.#result);
            this.#readableController.close();
        },
        abort: (reason) => {
            this.#resolver.reject(reason);
            this.#readableController.error(reason);
        },
    });
    get writable() {
        return this.#writable;
    }
    #readableController;
    #readable = new esm_stream/* .ReadableStream */.ZY({
        start: (controller) => {
            this.#readableController = controller;
        },
    });
    get readable() {
        return this.#readable;
    }
    constructor() {
        void Object.defineProperties(this.#readable, {
            then: {
                get: () => this.#resolver.promise.then.bind(this.#resolver.promise),
            },
            catch: {
                get: () => this.#resolver.promise.catch.bind(this.#resolver.promise),
            },
            finally: {
                get: () => this.#resolver.promise.finally.bind(this.#resolver.promise),
            },
        });
    }
}
/**
 * A `TransformStream` that concatenates `Uint8Array`s.
 *
 * If you want to decode the result as string,
 * prefer `.pipeThrough(new TextDecoderStream()).pipeThrough(new ConcatStringStream())`,
 * than `.pipeThough(new ConcatBufferStream()).pipeThrough(new TextDecoderStream())`,
 * because of JavaScript engine optimizations,
 * concatenating strings is faster than concatenating `Uint8Array`s.
 */
class ConcatBufferStream {
    #segments = [];
    #resolver = new promise_resolver/* .PromiseResolver */.O();
    #writable = new esm_stream/* .WritableStream */.ho({
        write: (chunk) => {
            this.#segments.push(chunk);
        },
        close: () => {
            let result;
            let offset = 0;
            switch (this.#segments.length) {
                case 0:
                    result = esm_buffer/* .EmptyUint8Array */.j;
                    break;
                case 1:
                    result = this.#segments[0];
                    break;
                default:
                    result = new Uint8Array(this.#segments.reduce((prev, item) => prev + item.length, 0));
                    for (const segment of this.#segments) {
                        result.set(segment, offset);
                        offset += segment.length;
                    }
                    break;
            }
            this.#resolver.resolve(result);
            this.#readableController.enqueue(result);
            this.#readableController.close();
        },
        abort: (reason) => {
            this.#resolver.reject(reason);
            this.#readableController.error(reason);
        },
    });
    get writable() {
        return this.#writable;
    }
    #readableController;
    #readable = new esm_stream/* .ReadableStream */.ZY({
        start: (controller) => {
            this.#readableController = controller;
        },
    });
    get readable() {
        return this.#readable;
    }
    constructor() {
        void Object.defineProperties(this.#readable, {
            then: {
                get: () => this.#resolver.promise.then.bind(this.#resolver.promise),
            },
            catch: {
                get: () => this.#resolver.promise.catch.bind(this.#resolver.promise),
            },
            finally: {
                get: () => this.#resolver.promise.finally.bind(this.#resolver.promise),
            },
        });
    }
}
//# sourceMappingURL=concat.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/features.js
// The order follows
// https://cs.android.com/android/platform/superproject/+/master:packages/modules/adb/transport.cpp;l=77;drc=6d14d35d0241f6fee145f8e54ffd77252e8d29fd
const AdbFeature = {
    ShellV2: "shell_v2",
    Cmd: "cmd",
    StatV2: "stat_v2",
    ListV2: "ls_v2",
    FixedPushMkdir: "fixed_push_mkdir",
    Abb: "abb",
    AbbExec: "abb_exec",
    SendReceiveV2: "sendrecv_v2",
    DelayedAck: "delayed_ack",
};
//# sourceMappingURL=features.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/none/process.js

class AdbNoneProtocolProcessImpl {
    #socket;
    get stdin() {
        return this.#socket.writable;
    }
    get output() {
        return this.#socket.readable;
    }
    #exited;
    get exited() {
        return this.#exited;
    }
    constructor(socket, signal) {
        this.#socket = socket;
        if (signal) {
            // `signal` won't affect `this.output`
            // So remaining data can still be read
            // (call `controller.error` will discard all pending data)
            const exited = new promise_resolver/* .PromiseResolver */.O();
            this.#socket.closed.then(() => exited.resolve(undefined), (e) => exited.reject(e));
            signal.addEventListener("abort", () => {
                exited.reject(signal.reason);
                this.#socket.close();
            });
            this.#exited = exited.promise;
        }
        else {
            this.#exited = this.#socket.closed;
        }
    }
    kill() {
        return this.#socket.close();
    }
}
//# sourceMappingURL=process.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/maybe-consumable/writable.js
var maybe_consumable_writable = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/maybe-consumable/writable.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/none/pty.js

class AdbNoneProtocolPtyProcess {
    #socket;
    #writer;
    #input;
    get input() {
        return this.#input;
    }
    get output() {
        return this.#socket.readable;
    }
    get exited() {
        return this.#socket.closed;
    }
    constructor(socket) {
        this.#socket = socket;
        this.#writer = this.#socket.writable.getWriter();
        this.#input = new maybe_consumable_writable/* .MaybeConsumableWritableStream */.g({
            write: (chunk) => this.#writer.write(chunk),
        });
    }
    sigint() {
        return this.#writer.write(new Uint8Array([0x03]));
    }
    kill() {
        return this.#socket.close();
    }
}
//# sourceMappingURL=pty.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/utils.js
function escapeArg(s) {
    let result = "";
    result += `'`;
    let base = 0;
    while (true) {
        const found = s.indexOf(`'`, base);
        if (found === -1) {
            result += s.substring(base);
            break;
        }
        result += s.substring(base, found);
        // a'b becomes a'\'b (the backslash is not a escape character)
        result += String.raw `'\''`;
        base = found + 1;
    }
    result += `'`;
    return result;
}
function splitCommand(command) {
    const result = [];
    let quote;
    let isEscaped = false;
    let start = 0;
    for (let i = 0, len = command.length; i < len; i += 1) {
        if (isEscaped) {
            isEscaped = false;
            continue;
        }
        const char = command.charAt(i);
        switch (char) {
            case " ":
                if (!quote && i !== start) {
                    result.push(command.substring(start, i));
                    start = i + 1;
                }
                break;
            case "'":
            case '"':
                if (!quote) {
                    quote = char;
                }
                else if (char === quote) {
                    quote = undefined;
                }
                break;
            case "\\":
                isEscaped = true;
                break;
        }
    }
    if (start < command.length) {
        result.push(command.substring(start));
    }
    return result;
}
//# sourceMappingURL=utils.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/none/spawner.js


class AdbNoneProtocolSpawner {
    #spawn;
    constructor(spawn) {
        this.#spawn = spawn;
    }
    spawn(command, signal) {
        signal?.throwIfAborted();
        if (typeof command === "string") {
            command = splitCommand(command);
        }
        return this.#spawn(command, signal);
    }
    async spawnWait(command) {
        const process = await this.spawn(command);
        return await process.output.pipeThrough(new ConcatBufferStream());
    }
    async spawnWaitText(command) {
        const process = await this.spawn(command);
        return await process.output
            .pipeThrough(new encoding/* .TextDecoderStream */.W())
            .pipeThrough(new ConcatStringStream());
    }
}
//# sourceMappingURL=spawner.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/none/service.js



class AdbNoneProtocolSubprocessService extends AdbNoneProtocolSpawner {
    #adb;
    get adb() {
        return this.#adb;
    }
    constructor(adb) {
        super(async (command, signal) => {
            // `shell,raw:${command}` also triggers raw mode,
            // But is not supported on Android version <7.
            const socket = await this.#adb.createSocket(`exec:${command.join(" ")}`);
            if (signal?.aborted) {
                await socket.close();
                throw signal.reason;
            }
            return new AdbNoneProtocolProcessImpl(socket, signal);
        });
        this.#adb = adb;
    }
    async pty(command) {
        if (command === undefined) {
            command = "";
        }
        else if (Array.isArray(command)) {
            command = command.join(" ");
        }
        return new AdbNoneProtocolPtyProcess(
        // https://github.com/microsoft/typescript/issues/17002
        await this.#adb.createSocket(`shell:${command}`));
    }
}
//# sourceMappingURL=service.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/push-readable.js
var push_readable = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/push-readable.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/struct-deserialize.js + 1 modules
var struct_deserialize = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/struct-deserialize.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/struct.js
var struct = __webpack_require__("../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/struct.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/number.js + 3 modules
var number = __webpack_require__("../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/number.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/shell/shared.js

const AdbShellProtocolId = {
    Stdin: 0,
    Stdout: 1,
    Stderr: 2,
    Exit: 3,
    CloseStdin: 4,
    WindowSizeChange: 5,
};
// This packet format is used in both directions.
const AdbShellProtocolPacket = (0,struct/* .struct */.w3)({
    id: (0,number.u8)(),
    data: (0,esm_buffer/* .buffer */.r)(number/* .u32 */.DH),
}, { littleEndian: true });
//# sourceMappingURL=shared.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/shell/process.js




class AdbShellProtocolProcessImpl {
    #socket;
    #writer;
    #stdin;
    get stdin() {
        return this.#stdin;
    }
    #stdout;
    get stdout() {
        return this.#stdout;
    }
    #stderr;
    get stderr() {
        return this.#stderr;
    }
    #exited;
    get exited() {
        return this.#exited;
    }
    constructor(socket, signal) {
        this.#socket = socket;
        let stdoutController;
        let stderrController;
        this.#stdout = new push_readable/* .PushReadableStream */.F((controller) => {
            stdoutController = controller;
        });
        this.#stderr = new push_readable/* .PushReadableStream */.F((controller) => {
            stderrController = controller;
        });
        const exited = new promise_resolver/* .PromiseResolver */.O();
        this.#exited = exited.promise;
        socket.readable
            .pipeThrough(new struct_deserialize/* .StructDeserializeStream */.f(AdbShellProtocolPacket))
            .pipeTo(new esm_stream/* .WritableStream */.ho({
            write: async (chunk) => {
                switch (chunk.id) {
                    case AdbShellProtocolId.Exit:
                        exited.resolve(chunk.data[0]);
                        break;
                    case AdbShellProtocolId.Stdout:
                        await stdoutController.enqueue(chunk.data);
                        break;
                    case AdbShellProtocolId.Stderr:
                        await stderrController.enqueue(chunk.data);
                        break;
                    default:
                        // Ignore unknown messages like Google ADB does
                        // https://cs.android.com/android/platform/superproject/main/+/main:packages/modules/adb/daemon/shell_service.cpp;l=684;drc=61197364367c9e404c7da6900658f1b16c42d0da
                        break;
                }
            },
        }))
            .then(() => {
            stdoutController.close();
            stderrController.close();
            // If `exited` has already settled, this will be a no-op
            exited.reject(new Error("Socket ended without exit message"));
        }, (e) => {
            stdoutController.error(e);
            stderrController.error(e);
            // If `exited` has already settled, this will be a no-op
            exited.reject(e);
        });
        if (signal) {
            // `signal` won't affect `this.stdout` and `this.stderr`
            // So remaining data can still be read
            // (call `controller.error` will discard all pending data)
            signal.addEventListener("abort", () => {
                exited.reject(signal.reason);
                this.#socket.close();
            });
        }
        this.#writer = this.#socket.writable.getWriter();
        this.#stdin = new maybe_consumable_writable/* .MaybeConsumableWritableStream */.g({
            write: async (chunk) => {
                await this.#writer.write(AdbShellProtocolPacket.serialize({
                    id: AdbShellProtocolId.Stdin,
                    data: chunk,
                }));
            },
            close: () => 
            // Only shell protocol + raw mode supports closing stdin
            this.#writer.write(AdbShellProtocolPacket.serialize({
                id: AdbShellProtocolId.CloseStdin,
                data: esm_buffer/* .EmptyUint8Array */.j,
            })),
        });
    }
    kill() {
        return this.#socket.close();
    }
}
//# sourceMappingURL=process.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/utils.js
var utils = __webpack_require__("../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/utils.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/shell/pty.js




class AdbShellProtocolPtyProcess {
    #socket;
    #writer;
    #input;
    get input() {
        return this.#input;
    }
    #stdout;
    get output() {
        return this.#stdout;
    }
    #exited = new promise_resolver/* .PromiseResolver */.O();
    get exited() {
        return this.#exited.promise;
    }
    constructor(socket) {
        this.#socket = socket;
        let stdoutController;
        this.#stdout = new push_readable/* .PushReadableStream */.F((controller) => {
            stdoutController = controller;
        });
        socket.readable
            .pipeThrough(new struct_deserialize/* .StructDeserializeStream */.f(AdbShellProtocolPacket))
            .pipeTo(new esm_stream/* .WritableStream */.ho({
            write: async (chunk) => {
                switch (chunk.id) {
                    case AdbShellProtocolId.Exit:
                        this.#exited.resolve(chunk.data[0]);
                        break;
                    case AdbShellProtocolId.Stdout:
                        await stdoutController.enqueue(chunk.data);
                        break;
                }
            },
        }))
            .then(() => {
            stdoutController.close();
            // If `#exit` has already resolved, this will be a no-op
            this.#exited.reject(new Error("Socket ended without exit message"));
        }, (e) => {
            stdoutController.error(e);
            // If `#exit` has already resolved, this will be a no-op
            this.#exited.reject(e);
        });
        this.#writer = this.#socket.writable.getWriter();
        this.#input = new maybe_consumable_writable/* .MaybeConsumableWritableStream */.g({
            write: (chunk) => this.#writeStdin(chunk),
        });
    }
    #writeStdin(chunk) {
        return this.#writer.write(AdbShellProtocolPacket.serialize({
            id: AdbShellProtocolId.Stdin,
            data: chunk,
        }));
    }
    async resize(rows, cols) {
        await this.#writer.write(AdbShellProtocolPacket.serialize({
            id: AdbShellProtocolId.WindowSizeChange,
            // The "correct" format is `${rows}x${cols},${x_pixels}x${y_pixels}`
            // However, according to https://linux.die.net/man/4/tty_ioctl
            // `x_pixels` and `y_pixels` are unused, so always sending `0` should be fine.
            data: (0,utils/* .encodeUtf8 */.Af)(`${rows}x${cols},0x0\0`),
        }));
    }
    sigint() {
        return this.#writeStdin(new Uint8Array([0x03]));
    }
    kill() {
        return this.#socket.close();
    }
}
//# sourceMappingURL=pty.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/shell/spawner.js


class AdbShellProtocolSpawner {
    #spawn;
    constructor(spawn) {
        this.#spawn = spawn;
    }
    spawn(command, signal) {
        signal?.throwIfAborted();
        if (typeof command === "string") {
            command = splitCommand(command);
        }
        return this.#spawn(command, signal);
    }
    async spawnWait(command) {
        const process = await this.spawn(command);
        const [stdout, stderr, exitCode] = await Promise.all([
            process.stdout.pipeThrough(new ConcatBufferStream()),
            process.stderr.pipeThrough(new ConcatBufferStream()),
            process.exited,
        ]);
        return { stdout, stderr, exitCode };
    }
    async spawnWaitText(command) {
        const process = await this.spawn(command);
        const [stdout, stderr, exitCode] = await Promise.all([
            process.stdout
                .pipeThrough(new encoding/* .TextDecoderStream */.W())
                .pipeThrough(new ConcatStringStream()),
            process.stderr
                .pipeThrough(new encoding/* .TextDecoderStream */.W())
                .pipeThrough(new ConcatStringStream()),
            process.exited,
        ]);
        return { stdout, stderr, exitCode };
    }
}
//# sourceMappingURL=spawner.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/shell/service.js




class AdbShellProtocolSubprocessService extends AdbShellProtocolSpawner {
    #adb;
    get adb() {
        return this.#adb;
    }
    get isSupported() {
        return this.#adb.canUseFeature(AdbFeature.ShellV2);
    }
    constructor(adb) {
        super(async (command, signal) => {
            const socket = await this.#adb.createSocket(`shell,v2,raw:${command.join(" ")}`);
            if (signal?.aborted) {
                await socket.close();
                throw signal.reason;
            }
            return new AdbShellProtocolProcessImpl(socket, signal);
        });
        this.#adb = adb;
    }
    async pty(options) {
        let service = "shell,v2,pty";
        if (options?.terminalType) {
            service += `,TERM=` + options.terminalType;
        }
        service += ":";
        if (options) {
            if (typeof options.command === "string") {
                service += options.command;
            }
            else if (Array.isArray(options.command)) {
                service += options.command.join(" ");
            }
        }
        return new AdbShellProtocolPtyProcess(await this.#adb.createSocket(service));
    }
}
//# sourceMappingURL=service.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/subprocess/service.js



class AdbSubprocessService {
    #adb;
    get adb() {
        return this.#adb;
    }
    #noneProtocol;
    get noneProtocol() {
        return this.#noneProtocol;
    }
    #shellProtocol;
    get shellProtocol() {
        return this.#shellProtocol;
    }
    constructor(adb) {
        this.#adb = adb;
        this.#noneProtocol = new AdbNoneProtocolSubprocessService(adb);
        if (adb.canUseFeature(AdbFeature.ShellV2)) {
            this.#shellProtocol = new AdbShellProtocolSubprocessService(adb);
        }
    }
}
//# sourceMappingURL=service.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/base.js + 1 modules
var commands_base = __webpack_require__("../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/base.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/power.js
// cspell: ignore bootloader
// cspell: ignore fastboot
// cspell: ignore keyevent
// cspell: ignore longpress

class AdbPower extends commands_base/* .AdbServiceBase */.Y {
    reboot(mode = "") {
        return this.adb.createSocketAndWait(`reboot:${mode}`);
    }
    bootloader() {
        return this.reboot("bootloader");
    }
    fastboot() {
        return this.reboot("fastboot");
    }
    recovery() {
        return this.reboot("recovery");
    }
    sideload() {
        return this.reboot("sideload");
    }
    /**
     * Reboot to Qualcomm Emergency Download (EDL) Mode.
     *
     * Only works on some Qualcomm devices.
     */
    qualcommEdlMode() {
        return this.reboot("edl");
    }
    powerOff() {
        return this.adb.subprocess.noneProtocol.spawnWaitText(["reboot", "-p"]);
    }
    powerButton(longPress = false) {
        const args = ["input", "keyevent"];
        if (longPress) {
            args.push("--longpress");
        }
        args.push("POWER");
        return this.adb.subprocess.noneProtocol.spawnWaitText(args);
    }
    /**
     * Reboot to Samsung Odin download mode.
     *
     * Only works on Samsung devices.
     */
    samsungOdin() {
        return this.reboot("download");
    }
}
//# sourceMappingURL=power.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/reverse.js
var reverse = __webpack_require__("../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/reverse.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/tcpip.js

function parsePort(value) {
    if (!value || value === "0") {
        return undefined;
    }
    return Number.parseInt(value, 10);
}
class AdbTcpIpService extends commands_base/* .AdbServiceBase */.Y {
    async getListenAddresses() {
        const serviceListenAddresses = await this.adb.getProp("service.adb.listen_addrs");
        const servicePort = await this.adb.getProp("service.adb.tcp.port");
        const persistPort = await this.adb.getProp("persist.adb.tcp.port");
        return {
            serviceListenAddresses: serviceListenAddresses != ""
                ? serviceListenAddresses.split(",")
                : [],
            servicePort: parsePort(servicePort),
            persistPort: parsePort(persistPort),
        };
    }
    async setPort(port) {
        if (port <= 0) {
            throw new TypeError(`Invalid port ${port}`);
        }
        const output = await this.adb.createSocketAndWait(`tcpip:${port}`);
        if (output !== `restarting in TCP mode port: ${port}\n`) {
            throw new Error(output);
        }
        return output;
    }
    async disable() {
        const output = await this.adb.createSocketAndWait("usb:");
        if (output !== "restarting in USB mode\n") {
            throw new Error(output);
        }
        return output;
    }
}
//# sourceMappingURL=tcpip.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/extend.js
var extend = __webpack_require__("../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/extend.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/string.js
var string = __webpack_require__("../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/string.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+no-data-view@2.0.0/node_modules/@yume-chan/no-data-view/esm/uint32.js
var uint32 = __webpack_require__("../../node_modules/.pnpm/@yume-chan+no-data-view@2.0.0/node_modules/@yume-chan/no-data-view/esm/uint32.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/no-op.js
var no_op = __webpack_require__("../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/no-op.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/response.js



function encodeAsciiUnchecked(value) {
    const result = new Uint8Array(value.length);
    for (let i = 0; i < value.length; i += 1) {
        result[i] = value.charCodeAt(i);
    }
    return result;
}
/**
 * Encode ID to numbers for faster comparison
 * @param value A 4-character string
 * @returns A 32-bit integer by encoding the string as little-endian
 *
 * #__NO_SIDE_EFFECTS__
 */
function adbSyncEncodeId(value) {
    const buffer = encodeAsciiUnchecked(value);
    return (0,uint32/* .getUint32LittleEndian */.FQ)(buffer, 0);
}
const AdbSyncResponseId = {
    Entry: adbSyncEncodeId("DENT"),
    Entry2: adbSyncEncodeId("DNT2"),
    Lstat: adbSyncEncodeId("STAT"),
    Stat: adbSyncEncodeId("STA2"),
    Lstat2: adbSyncEncodeId("LST2"),
    Done: adbSyncEncodeId("DONE"),
    Data: adbSyncEncodeId("DATA"),
    Ok: adbSyncEncodeId("OKAY"),
    Fail: adbSyncEncodeId("FAIL"),
};
class AdbSyncError extends Error {
}
const AdbSyncFailResponse = (0,struct/* .struct */.w3)({ message: (0,string/* .string */.Y)(number/* .u32 */.DH) }, {
    littleEndian: true,
    postDeserialize(value) {
        throw new AdbSyncError(value.message);
    },
});
async function adbSyncReadResponse(stream, id, type) {
    if (typeof id === "string") {
        id = adbSyncEncodeId(id);
    }
    const buffer = await stream.readExactly(4);
    switch ((0,uint32/* .getUint32LittleEndian */.FQ)(buffer, 0)) {
        case AdbSyncResponseId.Fail:
            await AdbSyncFailResponse.deserialize(stream);
            throw new Error("Unreachable");
        case id:
            return await type.deserialize(stream);
        default:
            throw new Error(`Expected '${id}', but got '${(0,utils/* .decodeUtf8 */._6)(buffer)}'`);
    }
}
async function* adbSyncReadResponses(stream, id, type) {
    if (typeof id === "string") {
        id = adbSyncEncodeId(id);
    }
    while (true) {
        const buffer = await stream.readExactly(4);
        switch ((0,uint32/* .getUint32LittleEndian */.FQ)(buffer, 0)) {
            case AdbSyncResponseId.Fail:
                await AdbSyncFailResponse.deserialize(stream);
                (0,no_op/* .unreachable */.H)();
            case AdbSyncResponseId.Done:
                // `DONE` responses' size are always same as the request's normal response.
                //
                // For example, `DONE` responses for `LIST` requests are 16 bytes (same as `DENT` responses),
                // but `DONE` responses for `STAT` requests are 12 bytes (same as `STAT` responses).
                await stream.readExactly(type.size);
                return;
            case id:
                yield await type.deserialize(stream);
                break;
            default:
                throw new Error(`Expected '${id}' or '${AdbSyncResponseId.Done}', but got '${(0,utils/* .decodeUtf8 */._6)(buffer)}'`);
        }
    }
}
//# sourceMappingURL=response.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/request.js


const AdbSyncRequestId = {
    List: adbSyncEncodeId("LIST"),
    ListV2: adbSyncEncodeId("LIS2"),
    Send: adbSyncEncodeId("SEND"),
    SendV2: adbSyncEncodeId("SND2"),
    Lstat: adbSyncEncodeId("STAT"),
    Stat: adbSyncEncodeId("STA2"),
    LstatV2: adbSyncEncodeId("LST2"),
    Data: adbSyncEncodeId("DATA"),
    Done: adbSyncEncodeId("DONE"),
    Receive: adbSyncEncodeId("RECV"),
};
const AdbSyncNumberRequest = (0,struct/* .struct */.w3)({ id: number/* .u32 */.DH, arg: number/* .u32 */.DH }, { littleEndian: true });
async function adbSyncWriteRequest(writable, id, value) {
    if (typeof id === "string") {
        id = adbSyncEncodeId(id);
    }
    if (typeof value === "number") {
        await writable.write(AdbSyncNumberRequest.serialize({ id, arg: value }));
        return;
    }
    if (typeof value === "string") {
        value = (0,utils/* .encodeUtf8 */.Af)(value);
    }
    // `writable` is buffered, it copies inputs to an internal buffer,
    // so don't concatenate headers and data here, that will be an unnecessary copy.
    await writable.write(AdbSyncNumberRequest.serialize({ id, arg: value.length }));
    await writable.write(value);
}
//# sourceMappingURL=request.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/stat.js



// https://github.com/python/cpython/blob/4e581d64b8aff3e2eda99b12f080c877bb78dfca/Lib/stat.py#L36
const LinuxFileType = {
    Directory: 0o04,
    File: 0o10,
    Link: 0o12,
};
const AdbSyncLstatResponse = (0,struct/* .struct */.w3)({ mode: number/* .u32 */.DH, size: number/* .u32 */.DH, mtime: number/* .u32 */.DH }, {
    littleEndian: true,
    extra: {
        get type() {
            return (this.mode >> 12);
        },
        get permission() {
            return this.mode & 0b00001111_11111111;
        },
    },
    postDeserialize(value) {
        if (value.mode === 0 && value.size === 0 && value.mtime === 0) {
            throw new Error("lstat error");
        }
        return value;
    },
});
const AdbSyncStatErrorCode = {
    SUCCESS: 0,
    EACCES: 13,
    EEXIST: 17,
    EFAULT: 14,
    EFBIG: 27,
    EINTR: 4,
    EINVAL: 22,
    EIO: 5,
    EISDIR: 21,
    ELOOP: 40,
    EMFILE: 24,
    ENAMETOOLONG: 36,
    ENFILE: 23,
    ENOENT: 2,
    ENOMEM: 12,
    ENOSPC: 28,
    ENOTDIR: 20,
    EOVERFLOW: 75,
    EPERM: 1,
    EROFS: 30,
    ETXTBSY: 26,
};
const AdbSyncStatErrorName = /* #__PURE__ */ (() => Object.fromEntries(Object.entries(AdbSyncStatErrorCode).map(([key, value]) => [
    value,
    key,
])))();
const AdbSyncStatResponse = (0,struct/* .struct */.w3)({
    error: (0,number/* .u32 */.DH)(),
    dev: number/* .u64 */._l,
    ino: number/* .u64 */._l,
    mode: number/* .u32 */.DH,
    nlink: number/* .u32 */.DH,
    uid: number/* .u32 */.DH,
    gid: number/* .u32 */.DH,
    size: number/* .u64 */._l,
    atime: number/* .u64 */._l,
    mtime: number/* .u64 */._l,
    ctime: number/* .u64 */._l,
}, {
    littleEndian: true,
    extra: {
        get type() {
            return (this.mode >> 12);
        },
        get permission() {
            return this.mode & 0b00001111_11111111;
        },
    },
    postDeserialize(value) {
        if (value.error) {
            throw new Error(AdbSyncStatErrorName[value.error]);
        }
        return value;
    },
});
async function adbSyncLstat(socket, path, v2) {
    const locked = await socket.lock();
    try {
        if (v2) {
            await adbSyncWriteRequest(locked, AdbSyncRequestId.LstatV2, path);
            return await adbSyncReadResponse(locked, AdbSyncResponseId.Lstat2, AdbSyncStatResponse);
        }
        else {
            await adbSyncWriteRequest(locked, AdbSyncRequestId.Lstat, path);
            const response = await adbSyncReadResponse(locked, AdbSyncResponseId.Lstat, AdbSyncLstatResponse);
            return {
                mode: response.mode,
                // Convert to `BigInt` to make it compatible with `AdbSyncStatResponse`
                size: BigInt(response.size),
                mtime: BigInt(response.mtime),
                get type() {
                    return response.type;
                },
                get permission() {
                    return response.permission;
                },
            };
        }
    }
    finally {
        locked.release();
    }
}
async function adbSyncStat(socket, path) {
    const locked = await socket.lock();
    try {
        await adbSyncWriteRequest(locked, AdbSyncRequestId.Stat, path);
        return await adbSyncReadResponse(locked, AdbSyncResponseId.Stat, AdbSyncStatResponse);
    }
    finally {
        locked.release();
    }
}
//# sourceMappingURL=stat.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/list.js




const AdbSyncEntryResponse = (0,extend/* .extend */.X)(AdbSyncLstatResponse, {
    name: (0,string/* .string */.Y)(number/* .u32 */.DH),
});
const AdbSyncEntry2Response = (0,extend/* .extend */.X)(AdbSyncStatResponse, {
    name: (0,string/* .string */.Y)(number/* .u32 */.DH),
});
async function* adbSyncOpenDirV2(socket, path) {
    const locked = await socket.lock();
    try {
        await adbSyncWriteRequest(locked, AdbSyncRequestId.ListV2, path);
        for await (const item of adbSyncReadResponses(locked, AdbSyncResponseId.Entry2, AdbSyncEntry2Response)) {
            // `LST2` can return error codes for failed `lstat` calls.
            // `LIST` just ignores them.
            // But they only contain `name` so still pretty useless.
            if (item.error !== AdbSyncStatErrorCode.SUCCESS) {
                continue;
            }
            yield item;
        }
    }
    finally {
        locked.release();
    }
}
async function* adbSyncOpenDirV1(socket, path) {
    const locked = await socket.lock();
    try {
        await adbSyncWriteRequest(locked, AdbSyncRequestId.List, path);
        for await (const item of adbSyncReadResponses(locked, AdbSyncResponseId.Entry, AdbSyncEntryResponse)) {
            yield item;
        }
    }
    finally {
        locked.release();
    }
}
async function* adbSyncOpenDir(socket, path, v2) {
    if (v2) {
        yield* adbSyncOpenDirV2(socket, path);
    }
    else {
        for await (const item of adbSyncOpenDirV1(socket, path)) {
            // Convert to same format as `AdbSyncEntry2Response` for easier consumption.
            // However it will add some overhead.
            yield {
                mode: item.mode,
                size: BigInt(item.size),
                mtime: BigInt(item.mtime),
                get type() {
                    return item.type;
                },
                get permission() {
                    return item.permission;
                },
                name: item.name,
            };
        }
    }
}
//# sourceMappingURL=list.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/pull.js




const AdbSyncDataResponse = (0,struct/* .struct */.w3)({ data: (0,esm_buffer/* .buffer */.r)(number/* .u32 */.DH) }, { littleEndian: true });
async function* adbSyncPullGenerator(socket, path) {
    const locked = await socket.lock();
    let done = false;
    try {
        await adbSyncWriteRequest(locked, AdbSyncRequestId.Receive, path);
        for await (const packet of adbSyncReadResponses(locked, AdbSyncResponseId.Data, AdbSyncDataResponse)) {
            yield packet.data;
        }
        done = true;
    }
    catch (e) {
        done = true;
        throw e;
    }
    finally {
        if (!done) {
            // sync pull can't be cancelled, so we have to read all data
            for await (const packet of adbSyncReadResponses(locked, AdbSyncResponseId.Data, AdbSyncDataResponse)) {
                void packet;
            }
        }
        locked.release();
    }
}
function adbSyncPull(socket, path) {
    return esm_stream/* .ReadableStream.from */.ZY.from(adbSyncPullGenerator(socket, path));
}
//# sourceMappingURL=pull.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/consumable.js + 5 modules
var consumable = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/consumable.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/maybe-consumable/utils.js
var maybe_consumable_utils = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/maybe-consumable/utils.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/distribution.js



/**
 * Splits or combines buffers to specified size.
 */
class BufferCombiner {
    #capacity;
    #buffer;
    #offset;
    #available;
    constructor(size) {
        this.#capacity = size;
        this.#buffer = new Uint8Array(size);
        this.#offset = 0;
        this.#available = size;
    }
    /**
     * Pushes data to the combiner.
     * @param data The input data to be split or combined.
     * @returns
     * A generator that yields buffers of specified size.
     * It may yield the same buffer multiple times, consume the data before calling `next`.
     */
    *push(data) {
        let offset = 0;
        let available = data.length;
        if (this.#offset !== 0) {
            if (available >= this.#available) {
                this.#buffer.set(data.subarray(0, this.#available), this.#offset);
                offset += this.#available;
                available -= this.#available;
                yield this.#buffer;
                this.#offset = 0;
                this.#available = this.#capacity;
                if (available === 0) {
                    return;
                }
            }
            else {
                this.#buffer.set(data, this.#offset);
                this.#offset += available;
                this.#available -= available;
                return;
            }
        }
        while (available >= this.#capacity) {
            const end = offset + this.#capacity;
            yield data.subarray(offset, end);
            offset = end;
            available -= this.#capacity;
        }
        if (available > 0) {
            this.#buffer.set(data.subarray(offset), this.#offset);
            this.#offset += available;
            this.#available -= available;
        }
    }
    flush() {
        if (this.#offset === 0) {
            return undefined;
        }
        const output = this.#buffer.subarray(0, this.#offset);
        this.#offset = 0;
        this.#available = this.#capacity;
        return output;
    }
}
class DistributionStream extends esm_stream/* .TransformStream */.Rv {
    constructor(size, combine = false) {
        const combiner = combine ? new BufferCombiner(size) : undefined;
        super({
            async transform(chunk, controller) {
                await maybe_consumable_utils/* .tryConsume */.W(chunk, async (chunk) => {
                    if (combiner) {
                        for (const buffer of combiner.push(chunk)) {
                            await consumable/* .Consumable.ReadableStream.enqueue */.G.ReadableStream.enqueue(controller, buffer);
                        }
                    }
                    else {
                        let offset = 0;
                        let available = chunk.length;
                        while (available > 0) {
                            const end = offset + size;
                            await consumable/* .Consumable.ReadableStream.enqueue */.G.ReadableStream.enqueue(controller, chunk.subarray(offset, end));
                            offset = end;
                            available -= size;
                        }
                    }
                });
            },
            flush(controller) {
                if (combiner) {
                    const data = combiner.flush();
                    if (data) {
                        controller.enqueue(data);
                    }
                }
            },
        });
    }
}
//# sourceMappingURL=distribution.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/push.js






const ADB_SYNC_MAX_PACKET_SIZE = 64 * 1024;
const AdbSyncOkResponse = (0,struct/* .struct */.w3)({ unused: number/* .u32 */.DH }, { littleEndian: true });
async function pipeFileData(locked, file, packetSize, mtime) {
    // Read and write in parallel,
    // allow error response to abort the write.
    const abortController = new esm_stream/* .AbortController */.z1();
    file.pipeThrough(new DistributionStream(packetSize, true))
        .pipeTo(new maybe_consumable_writable/* .MaybeConsumableWritableStream */.g({
        write(chunk) {
            return adbSyncWriteRequest(locked, AdbSyncRequestId.Data, chunk);
        },
    }), { signal: abortController.signal })
        .then(async () => {
        await adbSyncWriteRequest(locked, AdbSyncRequestId.Done, mtime);
        await locked.flush();
    }, no_op/* .NOOP */.t);
    await adbSyncReadResponse(locked, AdbSyncResponseId.Ok, AdbSyncOkResponse).catch((e) => {
        abortController.abort();
        throw e;
    });
}
async function adbSyncPushV1({ socket, filename, file, type = LinuxFileType.File, permission = 0o666, mtime = (Date.now() / 1000) | 0, packetSize = ADB_SYNC_MAX_PACKET_SIZE, }) {
    const locked = await socket.lock();
    try {
        const mode = (type << 12) | permission;
        const pathAndMode = `${filename},${mode.toString()}`;
        await adbSyncWriteRequest(locked, AdbSyncRequestId.Send, pathAndMode);
        await pipeFileData(locked, file, packetSize, mtime);
    }
    finally {
        locked.release();
    }
}
const AdbSyncSendV2Flags = {
    None: 0,
    Brotli: 1,
    /**
     * 2
     */
    Lz4: 1 << 1,
    /**
     * 4
     */
    Zstd: 1 << 2,
    DryRun: 0x80000000,
};
const AdbSyncSendV2Request = (0,struct/* .struct */.w3)({ id: number/* .u32 */.DH, mode: number/* .u32 */.DH, flags: (0,number/* .u32 */.DH)() }, { littleEndian: true });
async function adbSyncPushV2({ socket, filename, file, type = LinuxFileType.File, permission = 0o666, mtime = (Date.now() / 1000) | 0, packetSize = ADB_SYNC_MAX_PACKET_SIZE, dryRun = false, }) {
    const locked = await socket.lock();
    try {
        await adbSyncWriteRequest(locked, AdbSyncRequestId.SendV2, filename);
        const mode = (type << 12) | permission;
        let flags = AdbSyncSendV2Flags.None;
        if (dryRun) {
            flags |= AdbSyncSendV2Flags.DryRun;
        }
        await locked.write(AdbSyncSendV2Request.serialize({
            id: AdbSyncRequestId.SendV2,
            mode,
            flags,
        }));
        await pipeFileData(locked, file, packetSize, mtime);
    }
    finally {
        locked.release();
    }
}
function adbSyncPush(options) {
    if (options.v2) {
        return adbSyncPushV2(options);
    }
    if (options.dryRun) {
        throw new Error("dryRun is not supported in v1");
    }
    return adbSyncPushV1(options);
}
//# sourceMappingURL=push.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/buffered.js
var buffered = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/buffered.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/auto-reset-event.js

class AutoResetEvent {
    #set;
    #queue = [];
    constructor(initialSet = false) {
        this.#set = initialSet;
    }
    wait() {
        if (!this.#set) {
            this.#set = true;
            if (this.#queue.length === 0) {
                return Promise.resolve();
            }
        }
        const resolver = new promise_resolver/* .PromiseResolver */.O();
        this.#queue.push(resolver);
        return resolver.promise;
    }
    notifyOne() {
        if (this.#queue.length !== 0) {
            this.#queue.pop().resolve();
        }
        else {
            this.#set = false;
        }
    }
    dispose() {
        for (const item of this.#queue) {
            item.reject(new Error("The AutoResetEvent has been disposed"));
        }
        this.#queue.length = 0;
    }
}
//# sourceMappingURL=auto-reset-event.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/socket.js


class AdbSyncSocketLocked {
    #writer;
    #readable;
    #socketLock;
    #writeLock = new AutoResetEvent();
    #combiner;
    get position() {
        return this.#readable.position;
    }
    constructor(writer, readable, bufferSize, lock) {
        this.#writer = writer;
        this.#readable = readable;
        this.#socketLock = lock;
        this.#combiner = new BufferCombiner(bufferSize);
    }
    #write(buffer) {
        // `#combiner` will reuse the buffer, so we need to use the Consumable pattern
        return consumable/* .Consumable.WritableStream.write */.G.WritableStream.write(this.#writer, buffer);
    }
    async flush() {
        try {
            await this.#writeLock.wait();
            const buffer = this.#combiner.flush();
            if (buffer) {
                await this.#write(buffer);
            }
        }
        finally {
            this.#writeLock.notifyOne();
        }
    }
    async write(data) {
        try {
            await this.#writeLock.wait();
            for (const buffer of this.#combiner.push(data)) {
                await this.#write(buffer);
            }
        }
        finally {
            this.#writeLock.notifyOne();
        }
    }
    async readExactly(length) {
        // The request may still be in the internal buffer.
        // Call `flush` to send it before starting reading
        await this.flush();
        return await this.#readable.readExactly(length);
    }
    release() {
        // In theory, the writer shouldn't leave anything in the buffer,
        // but to be safe, call `flush` to throw away any remaining data.
        this.#combiner.flush();
        this.#socketLock.notifyOne();
    }
    async close() {
        await this.#readable.cancel();
    }
}
class AdbSyncSocket {
    #lock = new AutoResetEvent();
    #socket;
    #locked;
    constructor(socket, bufferSize) {
        this.#socket = socket;
        this.#locked = new AdbSyncSocketLocked(socket.writable.getWriter(), new buffered/* .BufferedReadableStream */.y(socket.readable), bufferSize, this.#lock);
    }
    async lock() {
        await this.#lock.wait();
        return this.#locked;
    }
    async close() {
        await this.#locked.close();
        await this.#socket.close();
    }
}
//# sourceMappingURL=socket.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/sync/sync.js







/**
 * A simplified `dirname` function that only handles absolute unix paths.
 * @param path an absolute unix path
 * @returns the directory name of the input path
 */
function dirname(path) {
    const end = path.lastIndexOf("/");
    if (end === -1) {
        throw new Error(`Invalid path`);
    }
    if (end === 0) {
        return "/";
    }
    return path.substring(0, end);
}
class AdbSync {
    _adb;
    _socket;
    #supportsStat;
    #supportsListV2;
    #fixedPushMkdir;
    #supportsSendReceiveV2;
    #needPushMkdirWorkaround;
    get supportsStat() {
        return this.#supportsStat;
    }
    get supportsListV2() {
        return this.#supportsListV2;
    }
    get fixedPushMkdir() {
        return this.#fixedPushMkdir;
    }
    get supportsSendReceiveV2() {
        return this.#supportsSendReceiveV2;
    }
    get needPushMkdirWorkaround() {
        return this.#needPushMkdirWorkaround;
    }
    constructor(adb, socket) {
        this._adb = adb;
        this._socket = new AdbSyncSocket(socket, adb.maxPayloadSize);
        this.#supportsStat = adb.canUseFeature(AdbFeature.StatV2);
        this.#supportsListV2 = adb.canUseFeature(AdbFeature.ListV2);
        this.#fixedPushMkdir = adb.canUseFeature(AdbFeature.FixedPushMkdir);
        this.#supportsSendReceiveV2 = adb.canUseFeature(AdbFeature.SendReceiveV2);
        // https://android.googlesource.com/platform/packages/modules/adb/+/91768a57b7138166e0a3d11f79cd55909dda7014/client/file_sync_client.cpp#1361
        this.#needPushMkdirWorkaround =
            this._adb.canUseFeature(AdbFeature.ShellV2) && !this.fixedPushMkdir;
    }
    /**
     * Gets information of a file or folder.
     *
     * If `path` points to a symbolic link, the returned information is about the link itself (with `type` being `LinuxFileType.Link`).
     */
    async lstat(path) {
        return await adbSyncLstat(this._socket, path, this.#supportsStat);
    }
    /**
     * Gets the information of a file or folder.
     *
     * If `path` points to a symbolic link, it will be resolved and the returned information is about the target (with `type` being `LinuxFileType.File` or `LinuxFileType.Directory`).
     */
    async stat(path) {
        if (!this.#supportsStat) {
            throw new Error("Not supported");
        }
        return await adbSyncStat(this._socket, path);
    }
    /**
     * Checks if `path` is a directory, or a symbolic link to a directory.
     *
     * This uses `lstat` internally, thus works on all Android versions.
     */
    async isDirectory(path) {
        try {
            await this.lstat(path + "/");
            return true;
        }
        catch {
            return false;
        }
    }
    opendir(path) {
        return adbSyncOpenDir(this._socket, path, this.supportsListV2);
    }
    async readdir(path) {
        const results = [];
        for await (const entry of this.opendir(path)) {
            results.push(entry);
        }
        return results;
    }
    /**
     * Reads the content of a file on device.
     *
     * @param filename The full path of the file on device to read.
     * @returns A `ReadableStream` that contains the file content.
     */
    read(filename) {
        return adbSyncPull(this._socket, filename);
    }
    /**
     * Writes a file on device. If the file name already exists, it will be overwritten.
     *
     * @param options The content and options of the file to write.
     */
    async write(options) {
        if (this.needPushMkdirWorkaround) {
            // It may fail if `filename` already exists.
            // Ignore the result.
            // TODO: sync: test push mkdir workaround (need an Android 8 device)
            await this._adb.subprocess.noneProtocol.spawnWait([
                "mkdir",
                "-p",
                escapeArg(dirname(options.filename)),
            ]);
        }
        await adbSyncPush({
            v2: this.supportsSendReceiveV2,
            socket: this._socket,
            ...options,
        });
    }
    lockSocket() {
        return this._socket.lock();
    }
    dispose() {
        return this._socket.close();
    }
}
//# sourceMappingURL=sync.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/commands/framebuffer.js


const Version = (0,struct/* .struct */.w3)({ version: number/* .u32 */.DH }, { littleEndian: true });
const AdbFrameBufferV1 = (0,struct/* .struct */.w3)({
    bpp: number/* .u32 */.DH,
    size: number/* .u32 */.DH,
    width: number/* .u32 */.DH,
    height: number/* .u32 */.DH,
    red_offset: number/* .u32 */.DH,
    red_length: number/* .u32 */.DH,
    blue_offset: number/* .u32 */.DH,
    blue_length: number/* .u32 */.DH,
    green_offset: number/* .u32 */.DH,
    green_length: number/* .u32 */.DH,
    alpha_offset: number/* .u32 */.DH,
    alpha_length: number/* .u32 */.DH,
    data: (0,esm_buffer/* .buffer */.r)("size"),
}, { littleEndian: true });
const AdbFrameBufferV2 = (0,struct/* .struct */.w3)({
    bpp: number/* .u32 */.DH,
    colorSpace: number/* .u32 */.DH,
    size: number/* .u32 */.DH,
    width: number/* .u32 */.DH,
    height: number/* .u32 */.DH,
    red_offset: number/* .u32 */.DH,
    red_length: number/* .u32 */.DH,
    blue_offset: number/* .u32 */.DH,
    blue_length: number/* .u32 */.DH,
    green_offset: number/* .u32 */.DH,
    green_length: number/* .u32 */.DH,
    alpha_offset: number/* .u32 */.DH,
    alpha_length: number/* .u32 */.DH,
    data: (0,esm_buffer/* .buffer */.r)("size"),
}, { littleEndian: true });
class AdbFrameBufferError extends Error {
    constructor(message, options) {
        super(message, options);
    }
}
class AdbFrameBufferUnsupportedVersionError extends AdbFrameBufferError {
    constructor(version) {
        super(`Unsupported FrameBuffer version ${version}`);
    }
}
class AdbFrameBufferForbiddenError extends AdbFrameBufferError {
    constructor() {
        super("FrameBuffer is disabled by current app");
    }
}
async function framebuffer(adb) {
    const socket = await adb.createSocket("framebuffer:");
    const stream = new buffered/* .BufferedReadableStream */.y(socket.readable);
    let version;
    try {
        ({ version } = await Version.deserialize(stream));
    }
    catch (e) {
        if (e instanceof struct/* .StructEmptyError */.r1) {
            throw new AdbFrameBufferForbiddenError();
        }
        throw e;
    }
    switch (version) {
        case 1:
            // TODO: AdbFrameBuffer: does all v1 responses uses the same color space? Add it so the command returns same format for all versions.
            return await AdbFrameBufferV1.deserialize(stream);
        case 2:
            return await AdbFrameBufferV2.deserialize(stream);
        default:
            throw new AdbFrameBufferUnsupportedVersionError(version);
    }
}
//# sourceMappingURL=framebuffer.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/adb.js


class Adb {
    #transport;
    get transport() {
        return this.#transport;
    }
    get serial() {
        return this.#transport.serial;
    }
    get maxPayloadSize() {
        return this.#transport.maxPayloadSize;
    }
    get banner() {
        return this.#transport.banner;
    }
    get disconnected() {
        return this.#transport.disconnected;
    }
    get clientFeatures() {
        return this.#transport.clientFeatures;
    }
    get deviceFeatures() {
        return this.banner.features;
    }
    subprocess;
    power;
    reverse;
    tcpip;
    constructor(transport) {
        this.#transport = transport;
        this.subprocess = new AdbSubprocessService(this);
        this.power = new AdbPower(this);
        this.reverse = new reverse/* .AdbReverseService */.nQ(this);
        this.tcpip = new AdbTcpIpService(this);
    }
    canUseFeature(feature) {
        return (this.clientFeatures.includes(feature) &&
            this.deviceFeatures.includes(feature));
    }
    /**
     * Creates a new ADB Socket to the specified service or socket address.
     */
    async createSocket(service) {
        return this.#transport.connect(service);
    }
    async createSocketAndWait(service) {
        const socket = await this.createSocket(service);
        return await socket.readable
            .pipeThrough(new encoding/* .TextDecoderStream */.W())
            .pipeThrough(new ConcatStringStream());
    }
    getProp(key) {
        return this.subprocess.noneProtocol
            .spawnWaitText(["getprop", key])
            .then((output) => output.trim());
    }
    rm(filenames, options) {
        const args = ["rm"];
        if (options?.recursive) {
            args.push("-r");
        }
        if (options?.force) {
            args.push("-f");
        }
        if (Array.isArray(filenames)) {
            for (const filename of filenames) {
                // https://github.com/microsoft/typescript/issues/17002
                args.push(escapeArg(filename));
            }
        }
        else {
            // https://github.com/microsoft/typescript/issues/17002
            args.push(escapeArg(filenames));
        }
        // https://android.googlesource.com/platform/packages/modules/adb/+/1a0fb8846d4e6b671c8aa7f137a8c21d7b248716/client/adb_install.cpp#984
        args.push("</dev/null");
        return this.subprocess.noneProtocol.spawnWaitText(args);
    }
    async sync() {
        const socket = await this.createSocket("sync:");
        return new AdbSync(this, socket);
    }
    async framebuffer() {
        return framebuffer(this);
    }
    async close() {
        await this.#transport.close();
    }
}
//# sourceMappingURL=adb.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+no-data-view@2.0.0/node_modules/@yume-chan/no-data-view/esm/uint64.js
var uint64 = __webpack_require__("../../node_modules/.pnpm/@yume-chan+no-data-view@2.0.0/node_modules/@yume-chan/no-data-view/esm/uint64.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/banner.js
const AdbBannerKey = {
    Product: "ro.product.name",
    Model: "ro.product.model",
    Device: "ro.product.device",
    Features: "features",
};
class AdbBanner {
    static parse(banner) {
        let product;
        let model;
        let device;
        let features = [];
        const pieces = banner.split("::");
        if (pieces.length > 1) {
            const props = pieces[1];
            for (const prop of props.split(";")) {
                // istanbul ignore if
                if (!prop) {
                    continue;
                }
                const keyValue = prop.split("=");
                if (keyValue.length !== 2) {
                    continue;
                }
                const [key, value] = keyValue;
                switch (key) {
                    case AdbBannerKey.Product:
                        product = value;
                        break;
                    case AdbBannerKey.Model:
                        model = value;
                        break;
                    case AdbBannerKey.Device:
                        device = value;
                        break;
                    case AdbBannerKey.Features:
                        features = value.split(",");
                        break;
                }
            }
        }
        return new AdbBanner(product, model, device, features);
    }
    #product;
    get product() {
        return this.#product;
    }
    #model;
    get model() {
        return this.#model;
    }
    #device;
    get device() {
        return this.#device;
    }
    #features = [];
    get features() {
        return this.#features;
    }
    constructor(product, model, device, features) {
        this.#product = product;
        this.#model = model;
        this.#device = device;
        this.#features = features;
    }
}
//# sourceMappingURL=banner.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/hex.js
var hex = __webpack_require__("../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/hex.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/sequence-equal.js
var sequence_equal = __webpack_require__("../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/sequence-equal.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/try-close.js
var try_close = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/try-close.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/bipedal.js
var bipedal = __webpack_require__("../../node_modules/.pnpm/@yume-chan+struct@2.3.2/node_modules/@yume-chan/struct/esm/bipedal.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/server/stream.js



const OKAY = (0,utils/* .encodeUtf8 */.Af)("OKAY");
const FAIL = (0,utils/* .encodeUtf8 */.Af)("FAIL");
class AdbServerStream {
    #connection;
    #buffered;
    #writer;
    constructor(connection) {
        this.#connection = connection;
        this.#buffered = new buffered/* .BufferedReadableStream */.y(connection.readable);
        this.#writer = connection.writable.getWriter();
    }
    readExactly(length) {
        return this.#buffered.readExactly(length);
    }
    readString = (0,bipedal/* .bipedal */.q)(function* (then) {
        const data = yield* then(this.readExactly(4));
        const length = (0,hex/* .hexToNumber */.M)(data);
        if (length === 0) {
            return "";
        }
        else {
            const decoder = new utils/* .TextDecoder */.Ay();
            let result = "";
            const iterator = this.#buffered.iterateExactly(length);
            while (true) {
                const { done, value } = iterator.next();
                if (done) {
                    break;
                }
                result += decoder.decode(yield* then(value), { stream: true });
            }
            result += decoder.decode();
            return result;
        }
    });
    async readOkay() {
        const response = await this.readExactly(4);
        if ((0,sequence_equal/* .sequenceEqual */.m)(response, OKAY)) {
            // `OKAY` is followed by data length and data
            // But different services want to parse the data differently
            // So don't read the data here
            return;
        }
        if ((0,sequence_equal/* .sequenceEqual */.m)(response, FAIL)) {
            const reason = await this.readString();
            throw new Error(reason);
        }
        throw new Error(`Unexpected response: ${(0,utils/* .decodeUtf8 */._6)(response)}`);
    }
    async writeString(value) {
        // TODO: investigate using `encodeUtf8("0000" + value)` then modifying the length
        // That way allocates a new string (hopefully only a rope) instead of a new buffer
        const encoded = (0,utils/* .encodeUtf8 */.Af)(value);
        const buffer = new Uint8Array(4 + encoded.length);
        (0,hex/* .write4HexDigits */.h)(buffer, 0, encoded.length);
        buffer.set(encoded, 4);
        await this.#writer.write(buffer);
    }
    release() {
        this.#writer.releaseLock();
        return {
            readable: this.#buffered.release(),
            writable: this.#connection.writable,
            closed: this.#connection.closed,
            close: () => this.#connection.close(),
        };
    }
    async dispose() {
        void (0,try_close/* .tryCancel */.S)(this.#buffered);
        void (0,try_close/* .tryClose */.i)(this.#writer);
        await this.#connection.close();
    }
}
//# sourceMappingURL=stream.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/server/commands/wireless.js
// cspell:ignore tport


class NetworkError extends Error {
    constructor(message) {
        super(message);
        this.name = "NetworkError";
    }
}
class UnauthorizedError extends Error {
    constructor(message) {
        super(message);
        this.name = "UnauthorizedError";
    }
}
class AlreadyConnectedError extends Error {
    constructor(message) {
        super(message);
        this.name = "AlreadyConnectedError";
    }
}
class WirelessCommands {
    #client;
    constructor(client) {
        this.#client = client;
    }
    /**
     * `adb pair <password> <address>`
     */
    async pair(address, password) {
        const connection = await this.#client.createConnection(`host:pair:${password}:${address}`);
        try {
            const response = await connection.readExactly(4);
            // `response` is either `FAIL`, or 4 hex digits for length of the string
            if ((0,sequence_equal/* .sequenceEqual */.m)(response, FAIL)) {
                throw new Error(await connection.readString());
            }
            const length = (0,hex/* .hexToNumber */.M)(response);
            // Ignore the string as it's always `Successful ...`
            await connection.readExactly(length);
        }
        finally {
            await connection.dispose();
        }
    }
    /**
     * `adb connect <address>`
     */
    async connect(address) {
        const connection = await this.#client.createConnection(`host:connect:${address}`);
        try {
            const response = await connection.readString();
            switch (response) {
                case `already connected to ${address}`:
                    throw new AlreadyConnectedError(response);
                case `failed to connect to ${address}`: // `adb pair` mode not authorized
                case `failed to authenticate to ${address}`: // `adb tcpip` mode not authorized
                    throw new UnauthorizedError(response);
                case `connected to ${address}`:
                    return;
                default:
                    throw new NetworkError(response);
            }
        }
        finally {
            await connection.dispose();
        }
    }
    /**
     * `adb disconnect <address>`
     */
    async disconnect(address) {
        const connection = await this.#client.createConnection(`host:disconnect:${address}`);
        try {
            await connection.readString();
        }
        finally {
            await connection.dispose();
        }
    }
}
//# sourceMappingURL=wireless.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/server/commands/m-dns.js
// cspell:ignore mdns
class MDnsCommands {
    #client;
    constructor(client) {
        this.#client = client;
    }
    async check() {
        const connection = await this.#client.createConnection("host:mdns:check");
        try {
            const response = await connection.readString();
            return !response.startsWith("ERROR:");
        }
        finally {
            await connection.dispose();
        }
    }
    async getServices() {
        const connection = await this.#client.createConnection("host:mdns:services");
        try {
            const response = await connection.readString();
            return response
                .split("\n")
                .filter(Boolean)
                .map((line) => {
                const parts = line.split("\t");
                return {
                    name: parts[0],
                    service: parts[1],
                    address: parts[2],
                };
            });
        }
        finally {
            await connection.dispose();
        }
    }
}
//# sourceMappingURL=m-dns.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+event@2.0.0/node_modules/@yume-chan/event/esm/event-emitter.js
var event_emitter = __webpack_require__("../../node_modules/.pnpm/@yume-chan+event@2.0.0/node_modules/@yume-chan/event/esm/event-emitter.js");
// EXTERNAL MODULE: ../../node_modules/.pnpm/@yume-chan+event@2.0.0/node_modules/@yume-chan/event/esm/sticky-event-emitter.js
var sticky_event_emitter = __webpack_require__("../../node_modules/.pnpm/@yume-chan+event@2.0.0/node_modules/@yume-chan/event/esm/sticky-event-emitter.js");
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/utils/ref.js
const { setInterval: ref_setInterval, clearInterval: ref_clearInterval } = globalThis;
/**
 * An object to keep current Node.js process alive even when no code is running.
 *
 * Does nothing in Web environments.
 *
 * Note that it does't have reference counting. Calling `unref` will
 * remove the ref no matter how many times `ref` has been previously called, and vice versa.
 * This is the same as how Node.js works.
 */
class Ref {
    #intervalId;
    constructor(options) {
        if (!options?.unref) {
            this.ref();
        }
    }
    ref() {
        // `setInterval` can keep current Node.js alive, the delay value doesn't matter
        this.#intervalId = ref_setInterval(() => { }, 60 * 1000);
    }
    unref() {
        if (this.#intervalId) {
            ref_clearInterval(this.#intervalId);
            this.#intervalId = undefined;
        }
    }
}
//# sourceMappingURL=ref.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/server/observer.js



function unorderedRemove(array, index) {
    if (index < 0 || index >= array.length) {
        return;
    }
    array[index] = array[array.length - 1];
    array.length -= 1;
}
function filterDeviceStates(devices, states) {
    return devices.filter((device) => states.includes(device.state));
}
class AdbServerDeviceObserverOwner {
    current = [];
    #client;
    #stream;
    #observers = [];
    constructor(client) {
        this.#client = client;
    }
    async #receive(stream) {
        const response = await stream.readString();
        const next = AdbServerClient.parseDeviceList(response);
        const removed = this.current.slice();
        const added = [];
        for (const nextDevice of next) {
            const index = removed.findIndex((device) => device.transportId === nextDevice.transportId);
            if (index === -1) {
                added.push(nextDevice);
                continue;
            }
            unorderedRemove(removed, index);
        }
        this.current = next;
        if (added.length) {
            for (const observer of this.#observers) {
                const filtered = filterDeviceStates(added, observer.includeStates);
                if (filtered.length) {
                    observer.onDeviceAdd.fire(filtered);
                }
            }
        }
        if (removed.length) {
            for (const observer of this.#observers) {
                const filtered = filterDeviceStates(removed, observer.includeStates);
                if (filtered.length) {
                    observer.onDeviceRemove.fire(removed);
                }
            }
        }
        for (const observer of this.#observers) {
            const filtered = filterDeviceStates(this.current, observer.includeStates);
            observer.onListChange.fire(filtered);
        }
    }
    async #receiveLoop(stream) {
        try {
            while (true) {
                await this.#receive(stream);
            }
        }
        catch (e) {
            this.#stream = undefined;
            for (const observer of this.#observers) {
                observer.onError.fire(e);
            }
        }
    }
    async #connect() {
        const stream = await this.#client.createConnection("host:track-devices-l", 
        // Each individual observer will ref depending on their options
        { unref: true });
        // Set `current` and `onListChange` value before returning
        await this.#receive(stream);
        // Then start receive loop
        void this.#receiveLoop(stream);
        return stream;
    }
    async #handleObserverStop(stream) {
        if (this.#observers.length === 0) {
            this.#stream = undefined;
            await stream.dispose();
        }
    }
    async createObserver(options) {
        options?.signal?.throwIfAborted();
        let current = [];
        const onDeviceAdd = new event_emitter/* .EventEmitter */.b();
        const onDeviceRemove = new event_emitter/* .EventEmitter */.b();
        const onListChange = new sticky_event_emitter/* .StickyEventEmitter */.O();
        const onError = new sticky_event_emitter/* .StickyEventEmitter */.O();
        const includeStates = options?.includeStates ?? [
            "device",
            "unauthorized",
        ];
        const observer = {
            includeStates,
            onDeviceAdd,
            onDeviceRemove,
            onListChange,
            onError,
        };
        // Register `observer` before `#connect`.
        // So `#handleObserverStop` knows if there is any observer.
        this.#observers.push(observer);
        // Read the filtered `current` value from `onListChange` event
        onListChange.event((value) => (current = value));
        let stream;
        if (!this.#stream) {
            // `#connect` will initialize `onListChange` and `current`
            this.#stream = this.#connect();
            try {
                stream = await this.#stream;
            }
            catch (e) {
                this.#stream = undefined;
                throw e;
            }
        }
        else {
            stream = await this.#stream;
            // Initialize `onListChange` and `current` ourselves
            onListChange.fire(filterDeviceStates(this.current, includeStates));
        }
        const ref = new Ref(options);
        const stop = async () => {
            unorderedRemove(this.#observers, this.#observers.indexOf(observer));
            await this.#handleObserverStop(stream);
            ref.unref();
        };
        if (options?.signal) {
            if (options.signal.aborted) {
                await stop();
                throw options.signal.reason;
            }
            options.signal.addEventListener("abort", () => void stop());
        }
        return {
            onDeviceAdd: onDeviceAdd.event,
            onDeviceRemove: onDeviceRemove.event,
            onListChange: onListChange.event,
            onError: onError.event,
            get current() {
                return current;
            },
            stop,
        };
    }
}
//# sourceMappingURL=observer.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/server/transport.js


const ADB_SERVER_DEFAULT_FEATURES = /* #__PURE__ */ (() => [
    AdbFeature.ShellV2,
    AdbFeature.Cmd,
    AdbFeature.StatV2,
    AdbFeature.ListV2,
    AdbFeature.FixedPushMkdir,
    "apex",
    AdbFeature.Abb,
    // only tells the client the symlink timestamp issue in `adb push --sync` has been fixed.
    // No special handling required.
    "fixed_push_symlink_timestamp",
    AdbFeature.AbbExec,
    "remount_shell",
    "track_app",
    AdbFeature.SendReceiveV2,
    "sendrecv_v2_brotli",
    "sendrecv_v2_lz4",
    "sendrecv_v2_zstd",
    "sendrecv_v2_dry_run_send",
])();
class AdbServerTransport {
    #client;
    serial;
    transportId;
    maxPayloadSize = 1 * 1024 * 1024;
    banner;
    #sockets = [];
    #closed = new promise_resolver/* .PromiseResolver */.O();
    #disconnected;
    get disconnected() {
        return this.#disconnected;
    }
    get clientFeatures() {
        // No need to get host features (features supported by ADB server)
        // Because we create all ADB packets ourselves
        return ADB_SERVER_DEFAULT_FEATURES;
    }
    // eslint-disable-next-line @typescript-eslint/max-params
    constructor(client, serial, banner, transportId, disconnected) {
        this.#client = client;
        this.serial = serial;
        this.banner = banner;
        this.transportId = transportId;
        this.#disconnected = Promise.race([this.#closed.promise, disconnected]);
    }
    async connect(service) {
        const socket = await this.#client.createDeviceConnection({ transportId: this.transportId }, service);
        this.#sockets.push(socket);
        return socket;
    }
    async addReverseTunnel(handler, address) {
        return await this.#client.connector.addReverseTunnel(handler, address);
    }
    async removeReverseTunnel(address) {
        await this.#client.connector.removeReverseTunnel(address);
    }
    async clearReverseTunnels() {
        await this.#client.connector.clearReverseTunnels();
    }
    async close() {
        for (const socket of this.#sockets) {
            await socket.close();
        }
        this.#sockets.length = 0;
        this.#closed.resolve();
    }
}
//# sourceMappingURL=transport.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/server/client.js
// cspell:ignore tport










/**
 * Client for the ADB Server.
 */
class AdbServerClient {
    static NetworkError = NetworkError;
    static UnauthorizedError = UnauthorizedError;
    static AlreadyConnectedError = AlreadyConnectedError;
    static parseDeviceList(value, includeStates = [
        "device",
        "unauthorized",
    ]) {
        const devices = [];
        for (const line of value.split("\n")) {
            if (!line) {
                continue;
            }
            const parts = line.split(" ").filter(Boolean);
            const serial = parts[0];
            const state = parts[1];
            if (!includeStates.includes(state)) {
                continue;
            }
            let product;
            let model;
            let device;
            let transportId;
            for (let i = 2; i < parts.length; i += 1) {
                const [key, value] = parts[i].split(":");
                switch (key) {
                    case "product":
                        product = value;
                        break;
                    case "model":
                        model = value;
                        break;
                    case "device":
                        device = value;
                        break;
                    case "transport_id":
                        transportId = BigInt(value);
                        break;
                }
            }
            if (!transportId) {
                throw new Error(`No transport id for device ${serial}`);
            }
            devices.push({
                serial,
                state,
                authenticating: state === "unauthorized",
                product,
                model,
                device,
                transportId,
            });
        }
        return devices;
    }
    static formatDeviceService(device, command) {
        if (!device) {
            return `host:${command}`;
        }
        if ("transportId" in device) {
            return `host-transport-id:${device.transportId}:${command}`;
        }
        if ("serial" in device) {
            return `host-serial:${device.serial}:${command}`;
        }
        if ("usb" in device) {
            return `host-usb:${command}`;
        }
        if ("tcp" in device) {
            return `host-local:${command}`;
        }
        throw new TypeError("Invalid device selector");
    }
    connector;
    wireless = new WirelessCommands(this);
    mDns = new MDnsCommands(this);
    #observerOwner = new AdbServerDeviceObserverOwner(this);
    constructor(connector) {
        this.connector = connector;
    }
    async createConnection(request, options) {
        const connection = await this.connector.connect(options);
        const stream = new AdbServerStream(connection);
        try {
            await stream.writeString(request);
        }
        catch (e) {
            await stream.dispose();
            throw e;
        }
        try {
            // `raceSignal` throws when the signal is aborted,
            // so the `catch` block can close the connection.
            await raceSignal(() => stream.readOkay(), options?.signal);
            return stream;
        }
        catch (e) {
            await stream.dispose();
            throw e;
        }
    }
    /**
     * `adb version`
     */
    async getVersion() {
        const connection = await this.createConnection("host:version");
        try {
            const length = (0,hex/* .hexToNumber */.M)(await connection.readExactly(4));
            const version = (0,hex/* .hexToNumber */.M)(await connection.readExactly(length));
            return version;
        }
        finally {
            await connection.dispose();
        }
    }
    async validateVersion(minimalVersion) {
        const version = await this.getVersion();
        if (version < minimalVersion) {
            throw new Error(`adb server version (${version}) doesn't match this client (${minimalVersion})`);
        }
    }
    /**
     * `adb kill-server`
     */
    async killServer() {
        const connection = await this.createConnection("host:kill");
        await connection.dispose();
    }
    /**
     * `adb host-features`
     */
    async getServerFeatures() {
        const connection = await this.createConnection("host:host-features");
        try {
            const response = await connection.readString();
            return response.split(",");
        }
        finally {
            await connection.dispose();
        }
    }
    /**
     * Get a list of connected devices from ADB Server.
     *
     * Equivalent ADB Command: `adb devices -l`
     */
    async getDevices(includeStates = [
        "device",
        "unauthorized",
    ]) {
        const connection = await this.createConnection("host:devices-l");
        try {
            const response = await connection.readString();
            return AdbServerClient.parseDeviceList(response, includeStates);
        }
        finally {
            await connection.dispose();
        }
    }
    /**
     * Monitors device list changes.
     */
    async trackDevices(options) {
        return this.#observerOwner.createObserver(options);
    }
    /**
     * `adb -s <device> reconnect` or `adb reconnect offline`
     */
    async reconnectDevice(device) {
        const connection = await this.createConnection(device === "offline"
            ? "host:reconnect-offline"
            : AdbServerClient.formatDeviceService(device, "reconnect"));
        try {
            await connection.readString();
        }
        finally {
            await connection.dispose();
        }
    }
    /**
     * Gets the features supported by the device.
     * The transport ID of the selected device is also returned,
     * so the caller can execute other commands against the same device.
     * @param device The device selector
     * @returns The transport ID of the selected device, and the features supported by the device.
     */
    async getDeviceFeatures(device) {
        // On paper, `host:features` is a host service (device features are cached in host),
        // so it shouldn't use `createDeviceConnection`,
        // which is used to forward the service to the device.
        //
        // However, `createDeviceConnection` is a two step process:
        //
        //    1. Send a switch device service to host, to switch the connection to the device.
        //    2. Send the actual service to host, let it forward the service to the device.
        //
        // In step 2, the host only forward the service to device if the service is unknown to host.
        // If the service is a host service, it's still handled by host.
        //
        // Even better, if the service needs a device selector, but the selector is not provided,
        // the service will be executed against the device selected by the switch device service.
        // So we can use all device selector formats for the host service,
        // and get the transport ID in the same time.
        const connection = await this.createDeviceConnection(device, "host:features");
        // Luckily `AdbServerClient.Socket` is compatible with `AdbServerClient.ServerConnection`
        const stream = new AdbServerStream(connection);
        try {
            const featuresString = await stream.readString();
            const features = featuresString.split(",");
            return { transportId: connection.transportId, features };
        }
        finally {
            await stream.dispose();
        }
    }
    /**
     * Creates a connection that will forward the service to device.
     * @param device The device selector
     * @param service The service to forward
     * @returns An `AdbServerClient.Socket` that can be used to communicate with the service
     */
    async createDeviceConnection(device, service) {
        let switchService;
        let transportId;
        if (!device) {
            await this.validateVersion(41);
            switchService = `host:tport:any`;
        }
        else if ("transportId" in device) {
            switchService = `host:transport-id:${device.transportId}`;
            transportId = device.transportId;
        }
        else if ("serial" in device) {
            await this.validateVersion(41);
            switchService = `host:tport:serial:${device.serial}`;
        }
        else if ("usb" in device) {
            await this.validateVersion(41);
            switchService = `host:tport:usb`;
        }
        else if ("tcp" in device) {
            await this.validateVersion(41);
            switchService = `host:tport:local`;
        }
        else {
            throw new TypeError("Invalid device selector");
        }
        const connection = await this.createConnection(switchService);
        try {
            await connection.writeString(service);
        }
        catch (e) {
            await connection.dispose();
            throw e;
        }
        try {
            if (transportId === undefined) {
                const array = await connection.readExactly(8);
                transportId = (0,uint64/* .getUint64LittleEndian */.gw)(array, 0);
            }
            await connection.readOkay();
            const socket = connection.release();
            return {
                transportId,
                service,
                readable: socket.readable,
                writable: socket.writable,
                get closed() {
                    return socket.closed;
                },
                async close() {
                    await socket.close();
                },
            };
        }
        catch (e) {
            await connection.dispose();
            throw e;
        }
    }
    async #waitForUnchecked(device, state, options) {
        let type;
        if (!device) {
            type = "any";
        }
        else if ("transportId" in device) {
            type = "any";
        }
        else if ("serial" in device) {
            type = "any";
        }
        else if ("usb" in device) {
            type = "usb";
        }
        else if ("tcp" in device) {
            type = "local";
        }
        else {
            throw new TypeError("Invalid device selector");
        }
        // `waitFor` can't use `connectDevice`, because the device
        // might not be available yet.
        const service = AdbServerClient.formatDeviceService(device, `wait-for-${type}-${state}`);
        const connection = await this.createConnection(service, options);
        try {
            await connection.readOkay();
        }
        finally {
            await connection.dispose();
        }
    }
    /**
     * Wait for a device to be connected or disconnected.
     *
     * `adb wait-for-<state>`
     *
     * @param device The device selector
     * @param state The state to wait for
     * @param options The options
     * @returns A promise that resolves when the condition is met.
     */
    async waitFor(device, state, options) {
        if (state === "disconnect") {
            await this.validateVersion(41);
        }
        return this.#waitForUnchecked(device, state, options);
    }
    async waitForDisconnect(transportId, options) {
        const serverVersion = await this.getVersion();
        if (serverVersion >= 41) {
            return this.#waitForUnchecked({ transportId }, "disconnect", options);
        }
        else {
            const observer = await this.trackDevices(options);
            return new Promise((resolve, reject) => {
                observer.onDeviceRemove((devices) => {
                    if (devices.some((device) => device.transportId === transportId)) {
                        observer.stop();
                        resolve();
                    }
                });
                observer.onError((e) => {
                    observer.stop();
                    reject(e);
                });
            });
        }
    }
    /**
     * Creates an ADB Transport for the specified device.
     */
    async createTransport(device) {
        const { transportId, features } = await this.getDeviceFeatures(device);
        const devices = await this.getDevices();
        const info = devices.find((device) => device.transportId === transportId);
        const banner = new AdbBanner(info?.product, info?.model, info?.device, features);
        const waitAbortController = new esm_stream/* .AbortController */.z1();
        const disconnected = this.waitForDisconnect(transportId, {
            unref: true,
            signal: waitAbortController.signal,
        });
        const transport = new AdbServerTransport(this, info?.serial ?? "", banner, transportId, disconnected);
        void transport.disconnected.finally(() => waitAbortController.abort());
        return transport;
    }
    async createAdb(device) {
        const transport = await this.createTransport(device);
        return new Adb(transport);
    }
}
async function raceSignal(callback, ...signals) {
    const abortPromise = new promise_resolver/* .PromiseResolver */.O();
    function abort() {
        abortPromise.reject(this.reason);
    }
    try {
        for (const signal of signals) {
            if (!signal) {
                continue;
            }
            if (signal.aborted) {
                throw signal.reason;
            }
            signal.addEventListener("abort", abort);
        }
        return await Promise.race([callback(), abortPromise.promise]);
    }
    finally {
        for (const signal of signals) {
            if (!signal) {
                continue;
            }
            signal.removeEventListener("abort", abort);
        }
    }
}
//# sourceMappingURL=client.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/server/index.js




//# sourceMappingURL=index.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/@yume-chan+adb@2.5.1/node_modules/@yume-chan/adb/esm/index.js








//# sourceMappingURL=index.js.map

},
"../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/maybe-consumable/utils.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
__webpack_require__.d(__webpack_exports__, {
  W: () => (tryConsume)
});
/* import */ var _consumable_js__rspack_import_0 = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/consumable.js");

function getValue(value) {
    return value instanceof Consumable ? value.value : value;
}
function tryConsume(value, callback) {
    if (value instanceof _consumable_js__rspack_import_0/* .Consumable */.G) {
        return value.tryConsume(callback);
    }
    else {
        return callback(value);
    }
}
//# sourceMappingURL=utils.js.map

},
"../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/maybe-consumable/writable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
__webpack_require__.d(__webpack_exports__, {
  g: () => (MaybeConsumableWritableStream)
});
/* import */ var _consumable_js__rspack_import_1 = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/consumable.js");
/* import */ var _stream_js__rspack_import_0 = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/stream.js");
/* import */ var _utils_js__rspack_import_2 = __webpack_require__("../../node_modules/.pnpm/@yume-chan+stream-extra@2.1.0/node_modules/@yume-chan/stream-extra/esm/maybe-consumable/utils.js");



class MaybeConsumableWritableStream extends _stream_js__rspack_import_0/* .WritableStream */.ho {
    constructor(sink, strategy) {
        let wrappedStrategy;
        if (strategy) {
            wrappedStrategy = {};
            if ("highWaterMark" in strategy) {
                wrappedStrategy.highWaterMark = strategy.highWaterMark;
            }
            if ("size" in strategy) {
                wrappedStrategy.size = (chunk) => {
                    return strategy.size(chunk instanceof _consumable_js__rspack_import_1/* .Consumable */.G ? chunk.value : chunk);
                };
            }
        }
        super({
            start(controller) {
                return sink.start?.(controller);
            },
            write(chunk, controller) {
                return (0,_utils_js__rspack_import_2/* .tryConsume */.W)(chunk, (chunk) => sink.write?.(chunk, controller));
            },
            abort(reason) {
                return sink.abort?.(reason);
            },
            close() {
                return sink.close?.();
            },
        }, wrappedStrategy);
    }
}
//# sourceMappingURL=writable.js.map

},

};
;